本文整理汇总了PHP中Craft\Craft类的典型用法代码示例。如果您正苦于以下问题:PHP Craft类的具体用法?PHP Craft怎么用?PHP Craft使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Craft类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。
示例1: _validateoptions
private function _validateoptions($options)
{
if (empty($options)) {
throw new Exception(Craft::t('vCard Parameters must be supplied'));
}
return true;
}
开发者ID:nfourtythree,项目名称:craft-vcard,代码行数:7,代码来源:VCardService.php
示例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;
}
开发者ID:jonleesmith,项目名称:jonleesmith,代码行数:36,代码来源:SortByFieldTwigExtension.php
示例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);
}
开发者ID:Hambrook,项目名称:Compressor,代码行数:7,代码来源:CompressorService.php
示例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;
}
开发者ID:Wiejeben,项目名称:BM-Infinite-Scroll,代码行数:25,代码来源:InfiniteScrollTwigExtension.php
示例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;
}
开发者ID:am-impact,项目名称:amtools,代码行数:26,代码来源:AmTools_ImageOptimService.php
示例6: getCraft
/**
* @return ConsoleApp|WebApp
*/
protected function getCraft()
{
if (!$this->craft) {
$this->craft = Craft::app();
}
return $this->craft;
}
开发者ID:nerds-and-company,项目名称:craft-unit-test-suite,代码行数:10,代码来源:AbstractTest.php
示例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;
}
开发者ID:itmundi,项目名称:schematic,代码行数:34,代码来源:ExportCommand.php
示例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;
}
}
开发者ID:ostark,项目名称:schematic,代码行数:31,代码来源:CommandRunner.php
示例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.');
}
开发者ID:mattstauffer,项目名称:craft-cli,代码行数:28,代码来源:ClearCacheCommand.php
示例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();
}
开发者ID:jonleesmith,项目名称:jonleesmith,代码行数:68,代码来源:ElementApiController.php
示例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;
}
}
开发者ID:aladrach,项目名称:Bluefoot-Craft-Starter,代码行数:66,代码来源:Market_OrderStatusService.php
示例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;
}
开发者ID:ostark,项目名称:schematic,代码行数:15,代码来源:Locales.php
示例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 . ');');
}
}
开发者ID:aladrach,项目名称:Bluefoot-Craft-Starter,代码行数:13,代码来源:MarketPlugin.php
示例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);
}
开发者ID:kentonquatman,项目名称:portfolio,代码行数:16,代码来源:BaseTest.php
示例16: testRowShouldLogErrorWhenColumnsAndDataDoNotMatch
/**
* @covers ::row
*/
public function testRowShouldLogErrorWhenColumnsAndDataDoNotMatch()
{
$row = 1;
$historyId = 2;
$settings = array('map' => array('column1', 'column2', 'column3'), 'history' => $historyId);
$data = array('row1value1', 'row2', 'value2', 'row3value3');
$message = array(array(Craft::t('Columns and data did not match, could be due to malformed CSV row.')));
$this->setMockImportHistoryService($historyId, $row, $message);
$service = new ImportService();
$service->row($row, $data, $settings);
}
开发者ID:boboldehampsink,项目名称:import,代码行数:14,代码来源:ImportServiceTest.php
示例17: doDisplay
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
$context["__internal_8bc6326091755a7238d5805374fab8e110743b6ddea9106be2b518883cdf1153"] = $this->env->loadTemplate("_includes/forms");
// line 2
echo "\n";
// line 3
echo $context["__internal_8bc6326091755a7238d5805374fab8e110743b6ddea9106be2b518883cdf1153"]->gettextField(array("label" => \Craft\Craft::t($this->getAttribute($this->getAttribute($this->getContext($context, "entry"), "getType", array(), "method"), "titleLabel")), "id" => "title", "name" => "title", "value" => $this->getAttribute($this->getContext($context, "entry"), "title"), "errors" => $this->getAttribute($this->getContext($context, "entry"), "getErrors", array(0 => "title"), "method"), "first" => true, "autofocus" => true, "required" => true));
// line 12
echo "\n";
}
开发者ID:scisahaha,项目名称:generator-craft,代码行数:11,代码来源:f353b796cc9c79b14483d0a236e1f3b1310b46a6cf1b358754944b6dd144.php
示例18: populate
/**
* @param array $fieldDefinition
* @param FieldModel $field
* @param string $fieldHandle
* @param FieldGroupModel|null $group
*/
public function populate(array $fieldDefinition, FieldModel $field, $fieldHandle, FieldGroupModel $group = null)
{
parent::populate($fieldDefinition, $field, $fieldHandle, $group);
$settings = $fieldDefinition['settings'];
$defaultUploadLocationSourceId = $settings['defaultUploadLocationSource'];
$defaultUploadLocationSource = Craft::app()->schematic_assetSources->getSourceTypeByHandle($defaultUploadLocationSourceId);
$settings['defaultUploadLocationSource'] = $defaultUploadLocationSource ? $defaultUploadLocationSource->id : '';
$singleUploadLocationSourceId = $settings['singleUploadLocationSource'];
$singleUploadLocationSource = Craft::app()->schematic_assetSources->getSourceTypeByHandle($singleUploadLocationSourceId);
$settings['singleUploadLocationSource'] = $singleUploadLocationSource ? $singleUploadLocationSource->id : '';
$field->settings = $settings;
}
开发者ID:ostark,项目名称:schematic,代码行数:18,代码来源:AssetsField.php
示例19: getColorPalette
/**
* Gets color palette for image
*
* @param AssetFileModel|string $image
* @param $colorCount
* @param $quality
* @param $colorValue
* @return array
* @throws Exception
*/
public function getColorPalette($image, $colorCount, $quality, $colorValue)
{
$pathsModel = new Imager_ImagePathsModel($image);
if (!IOHelper::getRealPath($pathsModel->sourcePath)) {
throw new Exception(Craft::t('Source folder “{sourcePath}” does not exist', array('sourcePath' => $pathsModel->sourcePath)));
}
if (!IOHelper::fileExists($pathsModel->sourcePath . $pathsModel->sourceFilename)) {
throw new Exception(Craft::t('Requested image “{fileName}” does not exist in path “{sourcePath}”', array('fileName' => $pathsModel->sourceFilename, 'sourcePath' => $pathsModel->sourcePath)));
}
$palette = ColorThief::getPalette($pathsModel->sourcePath . $pathsModel->sourceFilename, $colorCount, $quality);
return $colorValue == 'hex' ? $this->_paletteToHex($palette) : $palette;
}
开发者ID:aelvan,项目名称:Imager-Craft,代码行数:22,代码来源:Imager_ColorService.php
示例20: authenticate
public function authenticate()
{
\Craft\Craft::log(__METHOD__, \Craft\LogLevel::Info, true);
$socialUser = \Craft\craft()->social->getSocialUserById($this->socialUserId);
if ($socialUser) {
$this->_id = $socialUser->user->id;
$this->username = $socialUser->user->username;
$this->errorCode = static::ERROR_NONE;
return true;
} else {
return false;
}
}
开发者ID:jamiepittock,项目名称:WhereForArt,代码行数:13,代码来源:TokenIdentity.php
注:本文中的Craft\Craft类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论