本文整理汇总了PHP中Craft\Craft类的典型用法代码示例。如果您正苦于以下问题:PHP Craft类的具体用法?PHP Craft怎么用?PHP Craft使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Craft类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: _validateoptions
private function _validateoptions($options)
{
if (empty($options)) {
throw new Exception(Craft::t('vCard Parameters must be supplied'));
}
return true;
}
示例2: sortByFieldFilter
/**
* The "sortByField" filter sorts an array of entries by the specified field's value
*
* Usage: {% for entry in craft.entries|sortByField('ordering', 'desc') %}
*/
public function sortByFieldFilter($content, $sort_by = null, $direction = 'asc')
{
if (!is_array($content)) {
throw new Exception(Craft::t('Variable passed to the sortByField filter is not an array'));
} elseif (!(isset($content[0]) && is_object($content[0]) && (get_class($content[0]) === 'Craft\\EntryModel' || get_class($content[0]) === 'Craft\\Commerce_ProductModel'))) {
throw new Exception(Craft::t('Variables passed to the sortByField filter are not entries'));
} elseif ($sort_by === null) {
throw new Exception(Craft::t('No sort by parameter passed to the sortByField filter'));
} elseif (!$content[0]->__isset($sort_by)) {
throw new Exception(Craft::t('Entries passed to the sortByField filter do not have the field "' . $sort_by . '"'));
} else {
// Unfortunately have to suppress warnings here due to __get function
// causing usort to think that the array has been modified:
// usort(): Array was modified by the user comparison function
@usort($content, function ($a, $b) use($sort_by, $direction) {
$flip = $direction === 'desc' ? -1 : 1;
$a_sort_value = $a->__get($sort_by);
$b_sort_value = $b->__get($sort_by);
if ($a_sort_value == $b_sort_value) {
return 0;
} else {
if ($a_sort_value > $b_sort_value) {
return 1 * $flip;
} else {
return -1 * $flip;
}
}
});
}
return $content;
}
示例3: __construct
public function __construct()
{
$this->document_root = \Craft\Craft::getPathOfAlias('webroot');
$this->cache_dir = $this->document_root . "/cache";
$this->cache_url = $this->makeBaseCacheUrl();
IOHelper::ensureFolderExists($this->cache_dir);
}
示例4: InfiniteScrollFilter
public function InfiniteScrollFilter($paginate, $containerSelector = null, $itemSelector = null, $loadingMessage = null, $loadingImage = null, $finishedMessage = null)
{
if (!$containerSelector || !$itemSelector) {
return null;
}
$content = '';
if ($paginate->getNextUrl()) {
$content .= '<div class="infinite-pagination"><a href="' . $paginate->getNextUrl() . '">' . Craft::t('Next Page') . '</a></div>';
}
$content .= craft()->templates->includeJsResource('infinitescroll/js/jquery.infinitescroll.min.js');
$script = 'var totalNumOfPages = ' . $paginate->totalPages . ';';
$script .= 'var containerSelector = "' . $containerSelector . '";';
$script .= 'var itemSelector = "' . $itemSelector . '";';
$loadingImage = $loadingImage ? $loadingImage : UrlHelper::getResourceUrl('infinitescroll/img/ajax-loader.gif');
$script .= 'var loadingImage = "' . $loadingImage . '";';
if ($loadingMessage) {
$script .= 'var loadingMessage = "' . $loadingMessage . '";';
}
if ($finishedMessage) {
$script .= 'var finishedMessage = "' . $finishedMessage . '";';
}
$content .= craft()->templates->includeJs($script);
$content .= craft()->templates->includeJsResource('infinitescroll/js/infinitescroll.js');
return $content;
}
示例5: optimizeImage
public function optimizeImage($imageToOptimize)
{
if ($this->_settings && $this->_settings->useServerImageOptim) {
$this->setToolAvailability();
Craft::import('plugins.amtools.libraries.PHPImageOptim.PHPImageOptim', true);
Craft::import('plugins.amtools.libraries.PHPImageOptim.Tools.Common', true);
Craft::import('plugins.amtools.libraries.PHPImageOptim.Tools.ToolsInterface', true);
$imageOptim = new \PHPImageOptim\PHPImageOptim();
$imageOptim->setImage($imageToOptimize);
switch (strtolower(pathinfo($imageToOptimize, PATHINFO_EXTENSION))) {
case 'gif':
return $this->optimizeGif($imageOptim);
break;
case 'png':
return $this->optimizePng($imageOptim);
break;
case 'jpg':
case 'jpeg':
return $this->optimizeJpeg($imageOptim);
break;
}
} elseif ($this->_settings && $this->_settings->useImagickImageOptim) {
return $this->_optimizeAsset($imageToOptimize);
}
return true;
}
示例6: getCraft
/**
* @return ConsoleApp|WebApp
*/
protected function getCraft()
{
if (!$this->craft) {
$this->craft = Craft::app();
}
return $this->craft;
}
示例7: actionIndex
/**
* Exports the Craft datamodel.
*
* @param string $file file to write the schema to
* @param array $exclude Data to not export
*
* @return int
*/
public function actionIndex($file = 'craft/config/schema.yml', array $exclude = null)
{
$dataTypes = Schematic::getExportableDataTypes();
// If there are data exclusions.
if ($exclude !== null) {
// Find any invalid data to exclude.
$invalidExcludes = array_diff($exclude, $dataTypes);
// If any invalid exclusions were specified.
if (count($invalidExcludes) > 0) {
$errorMessage = 'Invalid exlude';
if (count($invalidExcludes) > 1) {
$errorMessage .= 's';
}
$errorMessage .= ': ' . implode(', ', $invalidExcludes) . '.';
$errorMessage .= ' Valid exclusions are ' . implode(', ', $dataTypes);
// Output an error message outlining what invalid exclusions were specified.
echo "\n" . $errorMessage . "\n\n";
return 1;
}
// Remove any explicitly excluded data types from the list of data types to export.
$dataTypes = array_diff($dataTypes, $exclude);
}
Craft::app()->schematic->exportToYaml($file, $dataTypes);
Craft::log(Craft::t('Exported schema to {file}', ['file' => $file]));
return 0;
}
示例8: createCommand
/**
* @param string $name command name (case-insensitive)
*
* @return \CConsoleCommand The command object. Null if the name is invalid.
*/
public function createCommand($name)
{
$name = StringHelper::toLowerCase($name);
$command = null;
if (isset($this->commands[$name])) {
$command = $this->commands[$name];
} else {
$commands = array_change_key_case($this->commands);
if (isset($commands[$name])) {
$command = $commands[$name];
}
}
if ($command !== null) {
if (is_string($command)) {
$className = 'NerdsAndCompany\\Schematic\\ConsoleCommands\\' . IOHelper::getFileName($command, false);
return new $className($name, $this);
} else {
// an array configuration
return Craft::createComponent($command, $name, $this);
}
} elseif ($name === 'help') {
return new \CHelpCommand('help', $this);
} else {
return;
}
}
示例9: doDisplay
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
$context["forms"] = $this->env->loadTemplate("_includes/forms");
// line 2
echo "\n\n";
// line 4
echo $context["forms"]->gettextField(array("label" => \Craft\Craft::t("Placeholder Text"), "instructions" => \Craft\Craft::t("The text that will be shown if the field doesn’t have a value."), "id" => "placeholder", "name" => "placeholder", "value" => $this->getAttribute($this->getContext($context, "settings"), "placeholder"), "translatable" => true, "errors" => $this->getAttribute($this->getContext($context, "settings"), "getErrors", array(0 => "placeholder"), "method")));
// line 12
echo "\n\n";
// line 14
echo $context["forms"]->gettextField(array("label" => \Craft\Craft::t("Max Length"), "instructions" => \Craft\Craft::t("The maximum length of characters the field is allowed to have."), "id" => "maxLength", "name" => "maxLength", "value" => $this->getAttribute($this->getContext($context, "settings"), "maxLength"), "size" => 3, "errors" => $this->getAttribute($this->getContext($context, "settings"), "getErrors", array(0 => "maxLength"), "method")));
// line 22
echo "\n\n";
// line 24
echo $context["forms"]->getcheckboxField(array("label" => \Craft\Craft::t("Allow line breaks"), "name" => "multiline", "checked" => $this->getAttribute($this->getContext($context, "settings"), "multiline"), "toggle" => "initialRowsContainer"));
// line 29
echo "\n\n\n<div id=\"initialRowsContainer\" class=\"nested-fields";
// line 32
if (!$this->getAttribute($this->getContext($context, "settings"), "multiline")) {
echo " hidden";
}
echo "\">\n\t";
// line 33
echo $context["forms"]->gettextField(array("label" => \Craft\Craft::t("Initial Rows"), "id" => "initialRows", "name" => "initialRows", "value" => $this->getAttribute($this->getContext($context, "settings"), "initialRows"), "size" => 3, "errors" => $this->getAttribute($this->getContext($context, "settings"), "getErrors", array(0 => "initialRows"), "method")));
// line 40
echo "\n</div>\n";
}
开发者ID:scisahaha,项目名称:generator-craft,代码行数:28,代码来源:008a8f3123ede362a4b694b692faff97ed3826b5f10db619eea237abd6e7.php
示例10: fire
/**
* {@inheritdoc}
*/
protected function fire()
{
$caches = '*';
$tool = craft()->components->getComponentByTypeAndClass(ComponentType::Tool, 'ClearCaches');
if ($this->option('select')) {
$reflectionMethod = new ReflectionMethod($tool, '_getFolders');
$reflectionMethod->setAccessible(true);
$values = $reflectionMethod->invoke($tool);
$values['assetTransformIndex'] = Craft::t('Asset transform index');
$values['assetIndexingData'] = Craft::t('Asset indexing data');
$values['templateCaches'] = Craft::t('Template caches');
$keys = array_keys($values);
$options = array_values($values);
$dialog = $this->getHelper('dialog');
$selected = $dialog->select($this->output, 'Select which caches to clear (separate multiple by comma)', $options, null, false, 'Value "%s" is invalid', true);
$caches = array();
foreach ($selected as $index) {
$caches[] = $keys[$index];
}
}
$this->suppressOutput(function () use($tool, $caches) {
$tool->performAction(compact('caches'));
});
$this->info('Cache(s) cleared.');
}
示例11: actionGetElements
/**
* Returns the requested elements as JSON
*
* @param callable|null $configFactory A function for generating the config
* @param array|null $config The API endpoint configuration
*
* @throws Exception
* @throws HttpException
*/
public function actionGetElements($configFactory = null, array $config = null)
{
if ($configFactory !== null) {
$params = craft()->urlManager->getRouteParams();
$variables = isset($params['variables']) ? $params['variables'] : null;
$config = $this->_callWithParams($configFactory, $variables);
}
// Merge in default config options
$config = array_merge(['paginate' => true, 'pageParam' => 'page', 'elementsPerPage' => 100, 'first' => false, 'transformer' => 'Craft\\ElementApi_ElementTransformer'], craft()->config->get('defaults', 'elementapi'), $config);
if ($config['pageParam'] == 'p') {
throw new Exception('The pageParam setting cannot be set to "p" because that’s the parameter Craft uses to check the requested path.');
}
if (!isset($config['elementType'])) {
throw new Exception('Element API configs must specify the elementType.');
}
/** @var ElementCriteriaModel $criteria */
$criteria = craft()->elements->getCriteria($config['elementType'], ['limit' => null]);
if (!empty($config['criteria'])) {
$criteria->setAttributes($config['criteria']);
}
// Load Fractal
$pluginPath = craft()->path->getPluginsPath() . 'elementapi/';
require $pluginPath . 'vendor/autoload.php';
$fractal = new Manager();
$fractal->setSerializer(new ArraySerializer());
// Define the transformer
if (is_callable($config['transformer']) || $config['transformer'] instanceof TransformerAbstract) {
$transformer = $config['transformer'];
} else {
Craft::import('plugins.elementapi.ElementApi_ElementTransformer');
$transformer = Craft::createComponent($config['transformer']);
}
if ($config['first']) {
$element = $criteria->first();
if (!$element) {
throw new HttpException(404);
}
$resource = new Item($element, $transformer);
} else {
if ($config['paginate']) {
// Create the paginator
require $pluginPath . 'ElementApi_PaginatorAdapter.php';
$paginator = new ElementApi_PaginatorAdapter($config['elementsPerPage'], $criteria->total(), $config['pageParam']);
// Fetch this page's elements
$criteria->offset = $config['elementsPerPage'] * ($paginator->getCurrentPage() - 1);
$criteria->limit = $config['elementsPerPage'];
$elements = $criteria->find();
$paginator->setCount(count($elements));
$resource = new Collection($elements, $transformer);
$resource->setPaginator($paginator);
} else {
$resource = new Collection($criteria, $transformer);
}
}
JsonHelper::sendJsonHeaders();
echo $fractal->createData($resource)->toJson();
// End the request
craft()->end();
}
示例12: save
/**
* @param Market_OrderStatusModel $model
* @param array $emailsIds
*
* @return bool
* @throws Exception
* @throws \CDbException
* @throws \Exception
*/
public function save(Market_OrderStatusModel $model, array $emailsIds)
{
if ($model->id) {
$record = Market_OrderStatusRecord::model()->findById($model->id);
if (!$record->id) {
throw new Exception(Craft::t('No order status exists with the ID “{id}”', ['id' => $model->id]));
}
} else {
$record = new Market_OrderStatusRecord();
}
$record->name = $model->name;
$record->handle = $model->handle;
$record->color = $model->color;
$record->default = $model->default;
$record->validate();
$model->addErrors($record->getErrors());
//validating emails ids
$criteria = new \CDbCriteria();
$criteria->addInCondition('id', $emailsIds);
$exist = Market_EmailRecord::model()->exists($criteria);
$hasEmails = (bool) count($emailsIds);
if (!$exist && $hasEmails) {
$model->addError('emails', 'One or more emails do not exist in the system.');
}
//saving
if (!$model->hasErrors()) {
MarketDbHelper::beginStackedTransaction();
try {
//only one default status can be among statuses of one order type
if ($record->default) {
Market_OrderStatusRecord::model()->updateAll(['default' => 0]);
}
// Save it!
$record->save(false);
//Delete old links
if ($model->id) {
Market_OrderStatusEmailRecord::model()->deleteAllByAttributes(['orderStatusId' => $model->id]);
}
//Save new links
$rows = array_map(function ($id) use($record) {
return [$id, $record->id];
}, $emailsIds);
$cols = ['emailId', 'orderStatusId'];
$table = Market_OrderStatusEmailRecord::model()->getTableName();
craft()->db->createCommand()->insertAll($table, $cols, $rows);
// Now that we have a calendar ID, save it on the model
$model->id = $record->id;
MarketDbHelper::commitStackedTransaction();
} catch (\Exception $e) {
MarketDbHelper::rollbackStackedTransaction();
throw $e;
}
return true;
} else {
return false;
}
}
示例13: export
/**
* @param array $data
*
* @return array
*/
public function export(array $data = [])
{
Craft::log(Craft::t('Exporting Locales'));
$locales = $this->getLocalizationService()->getSiteLocales();
$localeDefinitions = [];
foreach ($locales as $locale) {
$localeDefinitions[] = $locale->getId();
}
return $localeDefinitions;
}
示例14: initMarketNav
/**
* Temporary nav until 2.5 is released.
*/
private function initMarketNav()
{
if (craft()->request->isCpRequest()) {
craft()->templates->includeCssResource('market/market-nav.css');
craft()->templates->includeJsResource('market/market-nav.js');
$nav = [['url' => 'market/orders', 'title' => Craft::t("Orders"), 'selected' => craft()->request->getSegment(2) == 'orders' ? true : false], ['url' => 'market/products', 'title' => Craft::t("Products"), 'selected' => craft()->request->getSegment(2) == 'products' ? true : false], ['url' => 'market/promotions', 'title' => Craft::t("Promotions"), 'selected' => craft()->request->getSegment(2) == 'promotions' ? true : false], ['url' => 'market/customers', 'title' => Craft::t("Customers"), 'selected' => craft()->request->getSegment(2) == 'customers' ? true : false], ['url' => 'market/settings', 'title' => Craft::t("Settings"), 'selected' => craft()->request->getSegment(2) == 'settings' ? true : false]];
$navJson = JsonHelper::encode($nav);
craft()->templates->includeJs('new Craft.MarketNav(' . $navJson . ');');
}
}
示例15: setApplication
/**
* @param $val
*
* @return null
*/
protected function setApplication($val)
{
// Save the original one for tearDown()
if (!isset($this->_originalApplication)) {
$this->_originalApplication = craft();
}
// Call null to clear the app singleton.
Craft::setApplication(null);
// Set the new one.
Craft::setApplication($val);
}