/** * Index method * * @param string $filter Parameter to filter on * @param string $id Id of the model to filter * * @return \Cake\Network\Response|void */ public function index($filter = null, $id = null) { $findOptions = ['fields' => ['id', 'name', 'description', 'created', 'modified', 'sfw', 'status', 'user_id'], 'conditions' => ['Albums.status' => 1], 'contain' => ['Users' => ['fields' => ['id', 'username', 'realname']], 'Languages' => ['fields' => ['id', 'name', 'iso639_1']], 'Projects' => ['fields' => ['id', 'name', 'ProjectsAlbums.album_id']], 'Files' => ['fields' => ['id', 'name', 'filename', 'sfw', 'AlbumsFiles.album_id'], 'conditions' => ['status' => STATUS_PUBLISHED]]], 'order' => ['created' => 'desc'], 'sortWhitelist' => ['created', 'name', 'modified']]; // Sfw condition if (!$this->request->session()->read('seeNSFW')) { $findOptions['conditions']['sfw'] = true; } // Other conditions: if (!is_null($filter)) { switch ($filter) { case 'language': $findOptions['conditions']['Languages.id'] = $id; break; case 'license': $findOptions['conditions']['Licenses.id'] = $id; break; case 'user': $findOptions['conditions']['Users.id'] = $id; break; default: throw new \Cake\Network\Exception\NotFoundException(); } // Get additionnal infos infos $modelName = \Cake\Utility\Inflector::camelize(\Cake\Utility\Inflector::pluralize($filter)); $FilterModel = \Cake\ORM\TableRegistry::get($modelName); $filterData = $FilterModel->get($id); $this->set('filterData', $filterData); } $this->set('filter', $filter); $this->paginate = $findOptions; $this->set('albums', $this->paginate($this->Albums)); $this->set('_serialize', ['files']); }
/** * Sets up the configuration for the model, and loads ACL models if they haven't been already * * @param Table $model Table instance being attached * @param array $config Configuration * @return void */ public function __construct(Table $model, array $config = []) { $this->_table = $model; if (isset($config[0])) { $config['type'] = $config[0]; unset($config[0]); } if (isset($config['type'])) { $config['type'] = strtolower($config['type']); } parent::__construct($model, $config); $types = $this->_typeMaps[$this->config()['type']]; if (!is_array($types)) { $types = [$types]; } foreach ($types as $type) { $alias = Inflector::pluralize($type); $className = App::className($alias . 'Table', 'Model/Table'); if ($className == false) { $className = App::className('Acl.' . $alias . 'Table', 'Model/Table'); } $config = []; if (!TableRegistry::exists($alias)) { $config = ['className' => $className]; } $model->hasMany($type, ['targetTable' => TableRegistry::get($alias, $config)]); } if (!method_exists($model->entityClass(), 'parentNode')) { trigger_error(__d('cake_dev', 'Callback {0} not defined in {1}', ['parentNode()', $model->entityClass()]), E_USER_WARNING); } }
/** * {@inheritdoc} * * @param array $config Strategy's configuration. * @return $this */ public function initialize($config) { $config = parent::initialize($config)->config(); $assocName = Inflector::pluralize(Inflector::classify($this->_alias)); $this->_table->belongsTo($assocName, ['className' => $this->modelClass, 'foreignKey' => $config['field'], 'bindingKey' => 'name', 'conditions' => [$assocName . '.prefix' => $config['prefix']]]); return $this; }
/** * Class constructor * * @param Neomerx\JsonApi\Contracts\Schema\ContainerInterface $factory ContainerInterface * @param Neomerx\JsonApi\Contracts\Schema\SchemaFactoryInterface $container SchemaFactoryInterface * @param Cake\View\View $view Instance of the cake view we are rendering this in * @param string $entityName Name of the entity this schema is for */ public function __construct(SchemaFactoryInterface $factory, ContainerInterface $container, View $view, $entityName) { $this->_view = $view; if (!$this->resourceType) { $this->resourceType = strtolower(Inflector::pluralize($entityName)); } parent::__construct($factory, $container); }
/** * Gets the repository for this entity * * @param EntityInterface $entity * @return Table */ protected function _repository($entity) { $source = $entity->source(); if ($source === null) { list(, $class) = namespaceSplit(get_class($entity)); $source = Inflector::pluralize($class); } return TableRegistry::get($source); }
public function setCustomMaker() { $factory = $this->getFactoryClass(); $factory::setCustomMaker(function ($class) { $parts = explode('\\', $class); $object = new $class(); $object->source(Inflector::pluralize(array_pop($parts))); return $object; }); }
/** * Auto-pluralizing a word using the Inflection class * //TODO: move to lib or bootstrap * * @param string $singular The string to be pl. * @param int $count * @return string "member" or "members" OR "Mitglied"/"Mitglieder" if autoTranslate TRUE */ public function asp($singular, $count, $autoTranslate = false) { if ((int) $count !== 1) { $pural = Inflector::pluralize($singular); } else { $pural = null; // No pluralization necessary } return $this->sp($singular, $pural, $count, $autoTranslate); }
/** * {@inheritDoc} */ public function startup() { $controller = $this->_registry->getController(); $table = $controller->loadModel(); $tableAlias = $table->table(); if (empty($table->enums)) { return; } foreach ($table->enums as $field => $enum) { $controller->set(Inflector::pluralize(Inflector::variable($field)), $table->enum($field)); } }
protected function _optionsOptions($fieldName, $options) { $pluralize = true; if (substr($fieldName, -5) === '._ids') { $fieldName = substr($fieldName, 0, -5); $pluralize = false; } elseif (substr($fieldName, -3) === '_id') { $fieldName = substr($fieldName, 0, -3); } $fieldName = array_slice(explode('.', $fieldName), -1)[0]; $varName = Inflector::variable($pluralize ? Inflector::pluralize($fieldName) : $fieldName); return $this->_View->get($varName); }
/** * Make the helper, possibly configuring with CrudData objects * * @param \Cake\View\View $View * @param array $config An array of CrudData objects */ public function __construct(View $View, array $config = array()) { parent::__construct($View, $config); $config += ['_CrudData' => [], 'actions' => []]; $this->_defaultAlias = new NameConventions(Inflector::pluralize(Inflector::classify($this->request->controller))); $this->_CrudData = $config['_CrudData']; $this->DecorationSetups = new DecorationFactory($this); // $this->_Field = new Collection(); foreach ($config['actions'] as $name => $pattern) { $this->{$name} = $pattern; } $this->useCrudData($this->_defaultAlias->name); }
protected function _label($field) { if (!isset($this->_properties[$field])) { return ''; } $Table = TableRegistry::get($this->_registryAlias); $f = Inflector::variable(Inflector::pluralize($field)); $values = $Table->{$f}; $value = $this->{$field}; if (isset($values[$value])) { return $values[$value]; } return ''; }
/** * {@inheritDoc} */ public function display($fieldname, $value, $model = null) { $tableString = str_replace('_id', '', $fieldname); $tableName = Inflector::camelize(Inflector::pluralize($tableString)); $table = TableRegistry::get($tableName); $tableConfig = []; if (defined('PHPUNIT_TESTSUITE')) { $tableConfig = ['className' => 'ModelHistoryTestApp\\Model\\Table\\ArticlesTable']; } $historizableBehavior = TableRegistry::get($model, $tableConfig)->behaviors()->get('Historizable'); if (is_object($historizableBehavior) && method_exists($historizableBehavior, 'getRelationLink')) { return $historizableBehavior->getRelationLink($fieldname, $value); } return $value; }
/** * _checkAssociation method * @param array $data Candidate relation's data * @param string $candidate Candidate key * @param array $table Associated table * @param string $parentAssociation Name of the parent association * @return array */ protected function _checkAssocitation($data, $candidate, $table, $parentAssociation = '') { if (!is_array($data)) { return []; } $associations = []; $pluralSec = Inflector::pluralize($candidate); if ($table->association($pluralSec)) { $association = ucwords($pluralSec); $assocString = $parentAssociation != '' ? $parentAssociation . '.' . $association : $association; $associations[] = $assocString; foreach ($data as $key => $info) { $associations = array_merge($associations, $this->_checkAssocitation($info, $key, $table->{$association}, $assocString)); } } return $associations; }
protected function _getTarget() { if (is_null($this->target)) { $name = Inflector::pluralize($this->entity); $table = TableRegistry::get($name); $keys = [$this->key1, $this->key2]; $primary = $table->primaryKey(); if (!is_array($primary)) { $primary = [$primary]; } $where = []; foreach ($primary as $i => $id) { $where[$name . '.' . $id] = $keys[$i]; } $q = $table->find()->where($where); $this->target = $table->findWithContain($q)->first(); } return $this->target; }
/** * Process tests regarding fixture usage and update it for 3.x * * @param string $content Fixture content. * @return bool */ protected function _process($path) { $original = $contents = $this->Stage->source($path); // Serializes data from PHP data into PHP code. // Basically a code style conformant version of var_export() $export = function ($values) use(&$export) { $vals = []; if (!is_array($values)) { return $vals; } foreach ($values as $key => $val) { if (is_array($val)) { $vals[] = "'{$key}' => [" . implode(", ", $export($val)) . "]"; } else { $val = var_export($val, true); if ($val === 'NULL') { $val = 'null'; } if (!is_numeric($key)) { $vals[] = "'{$key}' => {$val}"; } else { $vals[] = "{$val}"; } } } return $vals; }; // Process field property. $processor = function ($matches) use($export) { eval('$data = [' . $matches[2] . '];'); $out = []; foreach ($data as $key => $fixture) { $pieces = explode('.', $fixture); $fixtureName = $pieces[count($pieces) - 1]; $fixtureName = Inflector::pluralize($fixtureName); $pieces[count($pieces) - 1] = $fixtureName; $out[] = implode('.', $pieces); } return $matches[1] . "\n\t\t" . implode(",\n\t\t", $export($out)) . "\n\t" . $matches[3]; }; $contents = preg_replace_callback('/(public \\$fixtures\\s+=\\s+(?:array\\(|\\[))(.*?)(\\);|\\];)/ms', $processor, $contents, -1, $count); return $this->Stage->change($path, $original, $contents); }
/** * Behavior configuration * * @param array $config * @return void */ public function initialize(array $config = []) { $config = $this->_config; if (empty($config['bits'])) { $config['bits'] = Inflector::pluralize($config['field']); } $entity = $this->_table->newEntity(); if (is_callable($config['bits'])) { $config['bits'] = call_user_func($config['bits']); } elseif (is_string($config['bits']) && method_exists($entity, $config['bits'])) { $config['bits'] = $entity->{$config['bits']}(); } elseif (is_string($config['bits']) && method_exists($this->_table, $config['bits'])) { $config['bits'] = $this->_table->{$config['bits']}(); } elseif (!is_array($config['bits'])) { $config['bits'] = false; } if (empty($config['bits'])) { throw new \Exception('Bits not found'); } ksort($config['bits'], SORT_NUMERIC); $this->_config = $config; }
/** * Creates the proper model name from a foreign key * * @param string $key Foreign key * @return string Model name */ protected function _modelNameFromKey($key) { $key = str_replace('_id', '', $key); return Inflector::camelize(Inflector::pluralize($key)); }
function beforeSave($event, $entity, $options = array()) { //debug($options); die('lol'); if ($entity->ref != "") { $ref = $entity->ref; $ref = Inflector::pluralize($ref); $table = TableRegistry::get($ref); if (!in_array('Media', $table->Behaviors()->loaded())) { throw new NotImplementedException(__d('media', "La table '%s' n'a pas le comportement 'Media'", $ref)); } } if (isset($options['file']) && is_array($options['file']) && $entity->ref != "") { $ref = $entity->ref; $ref = Inflector::pluralize($ref); $table = TableRegistry::get($ref); $ref_id = $entity->ref_id; $table = $table->Behaviors()->get('Media'); if (method_exists($ref, 'uploadMediasPath')) { $path = $this->{$ref}->uploadMediasPath($ref_id); } else { $path = $table->medias['path']; } $pathinfo = pathinfo($options['file']['name']); $extension = strtolower($pathinfo['extension']) == 'jpeg' ? 'jpg' : strtolower($pathinfo['extension']); if (!in_array($extension, $table->medias['extensions'])) { $this->error = __d('media', 'Vous ne pouvez pas uploader ce type de fichier ({%s} seulement)', implode(', ', $table->medias['extensions'])); return false; } // Limit files count by ref/ref_id if ($table->medias['limit'] > 0 && $entity->ref_id > 0) { $qty = $this->find('all', array('conditions' => array('ref' => $entity->ref, 'ref_id' => $entity->ref_id)))->count(); if ($qty >= $table->medias['limit']) { $this->error = __d('media', "Vous ne pouvez envoyer qu'un nombre limité de fichier (%d). Veuillez en supprimer avant d'en envoyer de nouveau.", $model->medias['limit']); return false; } } // Limit image size (for png/jpg/bmp/tiff) if (in_array($extension, array('jpg', 'png', 'bmp', 'tiff')) && ($table->medias['max_width'] > 0 || $table->medias['max_height'] > 0)) { list($width, $height) = getimagesize($options['file']['tmp_name']); if ($table->medias['max_width'] > 0 && $width > $table->medias['max_width']) { $this->error = __d('media', "La largeur maximum autorisée est de %dpx", $table->medias['max_width']); return false; } if ($table->medias['max_height'] > 0 && $height > $table->medias['max_height']) { $this->error = __d('media', "La hauteur maximum autorisée est de %dpx", $model->medias['max_height']); return false; } } // Limit Image size if ($table->medias['size'] > 0 && floor($options['file']['size'] / 1024) > $table->medias['size']) { $humanSize = $table->medias['size'] > 1024 ? round($table->medias['size'] / 1024, 1) . ' Mo' : $table->medias['size'] . ' Ko'; $this->error = __d('media', "Vous ne pouvez pas envoyer un fichier supérieur à %s", $humanSize); return false; } if (method_exists($ref, 'uploadMediasPath')) { $path = $this->{$ref}->uploadMediasPath($ref_id); } else { $path = $table->medias['path']; } $filename = Inflector::slug($pathinfo['filename'], '-'); $search = array('/', '%id', '%mid', '%cid', '%y', '%m', '%f'); $replace = array(DS, $ref_id, ceil($ref_id / 1000), ceil($ref_id / 100), date('Y'), date('m'), Inflector::slug($filename)); $file = str_replace($search, $replace, $path) . '.' . $extension; $this->testDuplicate($file); if (!file_exists(dirname(WWW_ROOT . $file))) { @mkdir(dirname(WWW_ROOT . $file), 0777, true); } $this->move_uploaded_file($options['file']['tmp_name'], WWW_ROOT . $file); @chmod(WWW_ROOT . $file, 0777); $entity->file = '/' . trim(str_replace(DS, '/', $file), '/'); } return true; }
/** * Prepare some additional data from the context. * * If the table option was provided to the constructor and it * was a string, ORM\TableRegistry will be used to get the correct table instance. * * If an object is provided as the table option, it will be used as is. * * If no table option is provided, the table name will be derived based on * naming conventions. This inference will work with a number of common objects * like arrays, Collection objects and ResultSets. * * @return void * @throws \RuntimeException When a table object cannot be located/inferred. */ protected function _prepare() { $table = $this->_context['table']; $entity = $this->_context['entity']; if (empty($table)) { if (is_array($entity) || $entity instanceof Traversable) { $entity = (new Collection($entity))->first(); } $isEntity = $entity instanceof Entity; if ($isEntity) { $table = $entity->source(); } if (!$table && $isEntity && get_class($entity) !== 'Cake\\ORM\\Entity') { list($ns, $entityClass) = namespaceSplit(get_class($entity)); $table = Inflector::pluralize($entityClass); } } if (is_string($table)) { $table = TableRegistry::get($table); } if (!is_object($table)) { throw new \RuntimeException('Unable to find table class for current entity'); } $this->_isCollection = is_array($entity) || $entity instanceof Traversable; $alias = $this->_rootName = $table->alias(); $this->_tables[$alias] = $table; }
/** * Returns associations for controllers models. * * @param array $whitelist Whitelist of associations to return. * @return array Associations for model */ protected function _associations(array $whitelist = []) { $table = $this->_table(); $associationConfiguration = []; $associations = $table->associations(); $keys = $associations->keys(); if ($whitelist) { $keys = array_intersect($keys, array_map('strtolower', $whitelist)); } foreach ($keys as $associationName) { $association = $associations->get($associationName); $type = $association->type(); if (!isset($associationConfiguration[$type])) { $associationConfiguration[$type] = []; } $assocKey = $association->name(); $associationConfiguration[$type][$assocKey]['model'] = $assocKey; $associationConfiguration[$type][$assocKey]['type'] = $type; $associationConfiguration[$type][$assocKey]['primaryKey'] = $association->target()->primaryKey(); $associationConfiguration[$type][$assocKey]['displayField'] = $association->target()->displayField(); $associationConfiguration[$type][$assocKey]['foreignKey'] = $association->foreignKey(); $associationConfiguration[$type][$assocKey]['propertyName'] = $association->property(); $associationConfiguration[$type][$assocKey]['plugin'] = null; $associationConfiguration[$type][$assocKey]['controller'] = Inflector::pluralize($assocKey); $associationConfiguration[$type][$assocKey]['entity'] = Inflector::singularize(Inflector::underscore($assocKey)); $associationConfiguration[$type][$assocKey]['entities'] = Inflector::underscore($assocKey); } return $associationConfiguration; }
/** * Initialize the fixture. * * @return void * @throws \Cake\ORM\Error\MissingTableException When importing from a table that does not exist. */ public function init() { if ($this->table === null) { list($namespace, $class) = namespaceSplit(get_class($this)); preg_match('/^(.*)Fixture$/', $class, $matches); $table = $class; if (isset($matches[1])) { $table = $matches[1]; } $this->table = Inflector::tableize(Inflector::pluralize($table)); } if (empty($this->import) && !empty($this->fields)) { $this->_schemaFromFields(); } if (!empty($this->import)) { $this->_schemaFromImport(); } }
/** * Selects the variable containing the options for a select field if present, * and sets the value to the 'options' key in the options array. * * @param string $fieldName The name of the field to find options for. * @param array $options Options list. * @return array */ protected function _optionsOptions($fieldName, $options) { if (isset($options['options'])) { return $options; } $fieldName = array_slice(explode('.', $fieldName), -1)[0]; $varName = Inflector::variable(Inflector::pluralize(preg_replace('/_id$/', '', $fieldName))); $varOptions = $this->_View->get($varName); if (!is_array($varOptions) && !$varOptions instanceof Traversable) { return $options; } if ($options['type'] !== 'radio') { $options['type'] = 'select'; } $options['options'] = $varOptions; return $options; }
/** * Creates the plural name for views * * @param string $name Name to use * @return string Plural name for views */ protected function _pluralName($name) { return Inflector::variable(Inflector::pluralize($name)); }
/** * Populates the configuration array with defaults values. * * @return void */ public function populate() { // @todo must run checks to check defaults // @todo must run checks to check general // // Prefixes // // foreach ($this->_config['defaults']['actions'] as $prefix => $actions) { // $routingPrefixes = (is_array(Configure::read('Routing.prefixes'))) ? Configure::read('Routing.prefixes') : []; // if ($prefix != 'public' && !in_array($prefix, $routingPrefixes)) { // $this->log("Prefix <strong>$prefix</strong> is not enabled in core.php but is used in your config file.", 'error', 1); // } // } // // Plugins // $this->log('Populating plugins.', 'part', 1); foreach ($this->_config['plugins'] as $plugin => $pluginConfig) { $this->log("Populating plugin \"<strong>{$plugin}</strong>\".", 'part', 2); // // Plugin configuration // if (is_array($pluginConfig)) { // Plugin has no displayName if (!isset($pluginConfig['displayName'])) { $pluginConfig['displayName'] = Inflector::humanize(Inflector::underscore($plugin)); $this->log("Plugin has no displayName.<br>" . " =>I'll use \"<strong>{$pluginConfig['displayName']}</strong>\" instead.", 'warning', 3); } // Merging with default plugin $pluginConfig = $this->updateArray($this->_config['defaults']['plugin'], $pluginConfig, true); // // Parts // $this->log("Populating parts...", 'part', 3); foreach ($pluginConfig['parts'] as $part => $partConfig) { $this->log("Populating \"<strong>{$part}</strong>\"", 'part', 4); // Merge part with defaults $partConfig = $this->updateArray($this->_config['defaults']['part'], $partConfig, true); // // Model // // Must have a model ? if ($partConfig['haveModel'] === true) { $this->log("Model configuration", 'part', 5); // String definition if (!is_array($partConfig['model'])) { if (empty($partConfig['model'])) { $this->log("The model should be defined as an array.<br>" . " => I'll base the name on the part name (\"<strong>" . Inflector::singularize($part) . "</strong>\")", 'warning', 6); $partConfig['model'] = ['name' => Inflector::singularize($part)]; } else { $this->log("The model should be defined as an array.<br>" . " => I'll use \"<strong>{$partConfig['model']}</strong>\" as <model>.name", 'warning', 6); $partConfig['model'] = ['name' => $partConfig['model']]; } } else { // Empty 'name' attribute if (!isset($partConfig['model']['name']) || empty($partConfig['model']['name'])) { $this->log("The model definition should contain a name attribute.<br>" . " => I'll base the name on the part name (\"<strong>" . Inflector::singularize($part) . "</strong>\")", 'warning', 6); $partConfig['model']['name'] = Inflector::singularize($part); } } // Model population $partConfig['model'] = $this->updateArray($this->_config['defaults']['model'], $partConfig['model']); // Merging part config with model options $partConfig['model']['options'] = $this->updateArray($partConfig['options'], $partConfig['model']['options'], true); // Snippets foreach ($partConfig['model']['snippets'] as $snippet => $snippetConfig) { // Merging snippets with defaults $partConfig['model']['snippets'][$snippet] = $this->updateArray($this->getConfig('defaults.snippet'), $snippetConfig); //Merging snippet options with part options $partConfig['model']['snippets'][$snippet]['options'] = $this->updateArray($partConfig['options'], $partConfig['model']['snippets'][$snippet]['options']); } $this->log("Model \"<strong>" . $partConfig['model']['name'] . "</strong>\" populated.", 'success', 5); } else { $this->log("This part should not have model", 'info', 5); unset($partConfig['model']); } // // Controller // // Must have a controller ? if ($partConfig['haveController'] === true) { $this->log("Controller configuration", 'part', 5); // String definition if (!is_array($partConfig['controller'])) { if (empty($partConfig['controller'])) { if ($partConfig['haveModel'] === false) { $this->log("The controller should be defined as an array.<br>" . " => I'll use \"<strong>" . $part . "</strong>\" as name (part name)", 'warning', 6); $partConfig['controller'] = ['name' => $part]; } else { $this->log("The controller should be defined as an array.<br>" . " => I'll use \"<strong>" . Inflector::pluralize($partConfig['model']['name']) . "</strong>\", based on the model name", 'warning', 6); $partConfig['controller'] = ['name' => Inflector::pluralize($partConfig['model']['name'])]; } } else { $this->log("The controller should be defined as an array.<br>" . " => I'll use \"<strong>{$partConfig['controller']}</strong>\" as <controller>.name", 'warning', 6); $partConfig['controller'] = ['name' => $partConfig['controller']]; } } else { // Empty 'name' attribute if (!isset($partConfig['controller']['name']) || empty($partConfig['controller']['name'])) { if ($partConfig['haveModel'] === false) { $this->log("The controller definition should have a name.<br>" . " => I'll use \"<strong>" . $part . "</strong>\" as name (part name)", 'warning', 6); $partConfig['controller']['name'] = $part; } else { $this->log("The controller definition should have a name.<br>" . " => I'll use \"<strong>" . Inflector::pluralize($partConfig['model']['name']) . "</strong>\", based on the model name", 'warning', 6); $partConfig['controller']['name'] = Inflector::pluralize($partConfig['model']['name']); } } } // Controller population $partConfig['controller'] = $this->updateArray($this->_config['defaults']['controller'], $partConfig['controller'], true); // Display name check if (empty($partConfig['controller']['displayName'])) { $this->log("The controller should have display name.<br>" . " => I'll base one on the controller name : \"<strong>" . ucfirst(strtolower(Inflector::humanize(Inflector::underscore($partConfig['controller']['name'])))) . "</strong>\"", 'warning', 6); $partConfig['controller']['displayName'] = ucfirst(strtolower(Inflector::humanize(Inflector::underscore($partConfig['controller']['name'])))); } // // Actions // $partConfig['controller']['actions'] = $this->updateArray($this->_config['defaults']['actions'], $partConfig['controller']['actions'], true); // Merge each action with the defaults for it, and fill the view array foreach ($partConfig['controller']['actions'] as $prefix => $actions) { foreach ($actions as $action => $actionConfig) { // Action $partConfig['controller']['actions'][$prefix][$action] = $this->updateArray($this->_config['defaults']['action'], $actionConfig, true); // Options from part $partConfig['controller']['actions'][$prefix][$action]['options'] = $this->updateArray($partConfig['options'], $partConfig['controller']['actions'][$prefix][$action]['options'], true); // // View // if ($partConfig['controller']['actions'][$prefix][$action]['haveView'] === true) { if (empty($actionConfig['view'])) { $actionConfig['view'] = []; } $partConfig['controller']['actions'][$prefix][$action]['view'] = $this->updateArray($this->_config['defaults']['view'], $actionConfig['view'], true); // Options from part $partConfig['controller']['actions'][$prefix][$action]['view']['options'] = $this->updateArray($partConfig['options'], $partConfig['controller']['actions'][$prefix][$action]['view']['options'], true); // Options from action $partConfig['controller']['actions'][$prefix][$action]['view']['options'] = $this->updateArray($partConfig['controller']['actions'][$prefix][$action]['options'], $partConfig['controller']['actions'][$prefix][$action]['view']['options'], true); } } } // Now, searching for actions to remove foreach ($partConfig['controller']['actions'] as $prefix => $actions) { foreach ($actions as $action => $actionConfig) { if ($actionConfig['blackListed'] === true) { $this->log("Removing blacklisted action \"<strong>{$prefix}.{$action}</strong>\"", 'info', 6); unset($partConfig['controller']['actions'][$prefix][$action]); } } } $this->log("Controller \"<strong>" . $partConfig['controller']['name'] . "</strong>\" populated.", 'success', 5); } else { $this->log("This part should not have controller", 'info', 5); unset($partConfig['controller']); } // No more things to do for this part. Setting it in the plugin config $pluginConfig['parts'][$part] = $partConfig; $this->log("Part \"{$part}\" populated.", 'success', 4); } $this->log("Parts population is over.", 'success', 3); // // Menus // $this->log("Populating menus...", 'part', 3); foreach ($pluginConfig['menus'] as $menu => $menuConfig) { $pluginConfig['menus'][$menu] = $this->updateArray($this->_config['defaults']['menu'], $menuConfig, true); if (empty($pluginConfig['menus'][$menu]['template'])) { $this->log("No template set, using \"" . $menu . "\" as template name", 'warning', 5); $pluginConfig['menus'][$menu]['fileName'] = $menu; } if (empty($pluginConfig['menus'][$menu]['targetFileName'])) { $this->log("No target file set, using \"" . $menu . "\" as target file", 'warning', 5); $pluginConfig['menus'][$menu]['targetFileName'] = $menu; } $this->log("Added {$menu}", 'success', 4); } $this->log("Menus population is over.", 'success', 3); // // Files // $this->log("Populating files...", 'part', 3); foreach ($pluginConfig['files'] as $file => $fileConfig) { $this->log("File \"{$file}\"", 'part', 4); $pluginConfig['files'][$file] = $this->updateArray($this->_config['defaults']['file'], $fileConfig, true); if (empty($pluginConfig['files'][$file]['template'])) { $this->log("No fileName set, using \"" . $file . "\" as template name", 'warning', 5); $pluginConfig['files'][$file]['fileName'] = $file; } if (empty($pluginConfig['files'][$file]['targetFileName'])) { $this->log("No target file set, using \"" . $file . "\" as target file", 'warning', 5); $pluginConfig['files'][$file]['targetFileName'] = $file; } $this->log("Added {$file}", 'success', 4); } $this->log("Files population is over.", 'success', 3); // // Required files // $this->log("Populating required files...", 'part', 3); foreach ($pluginConfig['required'] as $required => $requiredConfig) { $pluginConfig['required'][$required] = $this->updateArray($this->_config['defaults']['required'], $requiredConfig, true); if (empty($pluginConfig['required'][$required]['type'])) { $this->log("No file type set, removing {$required} from configuration.", 'error', 5); unset($pluginConfig['required'][$required]); $error = 1; } elseif (empty($pluginConfig['required'][$required]['target'])) { $this->log("No target set, removing {$required} from configuration.", 'error', 5); unset($pluginConfig['required'][$required]); $error = 1; } elseif (empty($pluginConfig['required'][$required]['source'])) { $this->log("No source set, removing {$required} from configuration.", 'error', 5); unset($pluginConfig['required'][$required]); $error = 1; } else { $error = 0; $this->log("Added {$required}", 'success', 4); } } $this->log("Files population is over.", 'success', 3); // @todo maybe check the templates existence. // $this->_config['plugins'][$plugin] = $pluginConfig; $this->log("Plugin \"{$plugin}\" populated.", 'success', 2); // } else { $this->log("Plugin <strong>\"{$plugin}\"</strong> is empty<br>" . " => It will now be removed from configuration.", 'error', 3); unset($this->_config['plugins'][$plugin]); } } }
/** * Test resetting inflection rules. * * @return void */ public function testCustomRuleWithReset() { $uninflected = ['atlas', 'lapis', 'onibus', 'pires', 'virus', '.*x']; $pluralIrregular = ['as' => 'ases']; Inflector::rules('singular', ['/^(.*)(a|e|o|u)is$/i' => '\\1\\2l'], true); Inflector::rules('plural', ['/^(.*)(a|e|o|u)l$/i' => '\\1\\2is'], true); Inflector::rules('uninflected', $uninflected, true); Inflector::rules('irregular', $pluralIrregular, true); $this->assertEquals('Alcoois', Inflector::pluralize('Alcool')); $this->assertEquals('Atlas', Inflector::pluralize('Atlas')); $this->assertEquals('Alcool', Inflector::singularize('Alcoois')); $this->assertEquals('Atlas', Inflector::singularize('Atlas')); }
/** * Returns associations for controllers models. * * @return array Associations for model */ protected function _associations() { $table = $this->_table(); $associationConfiguration = []; $associations = $table->associations(); foreach ($associations->keys() as $associationName) { $association = $associations->get($associationName); $type = $association->type(); if (!isset($associationConfiguration[$type])) { $associationConfiguration[$type] = []; } $assocKey = $association->name(); $associationConfiguration[$type][$assocKey]['model'] = $assocKey; $associationConfiguration[$type][$assocKey]['type'] = $type; $associationConfiguration[$type][$assocKey]['primaryKey'] = $association->target()->primaryKey(); $associationConfiguration[$type][$assocKey]['displayField'] = $association->target()->displayField(); $associationConfiguration[$type][$assocKey]['foreignKey'] = $association->foreignKey(); $associationConfiguration[$type][$assocKey]['plugin'] = null; $associationConfiguration[$type][$assocKey]['controller'] = Inflector::pluralize($assocKey); $associationConfiguration[$type][$assocKey]['entity'] = Inflector::singularize(Inflector::underscore($assocKey)); $associationConfiguration[$type][$assocKey]['entities'] = Inflector::underscore($assocKey); } return $associationConfiguration; }
/** * Met l'image à la une **/ public function thumb($id) { $this->Medias->id = $id; $media = $this->Medias->get($id); if (empty($media)) { throw new NotFoundException(); } if (!$this->canUploadMedias($media->ref, $media['Media']['ref_id'])) { throw new ForbiddenException(); } $ref = $media->ref; $ref_id = $media->ref_id; $this->loadModel($ref); $table = Inflector::pluralize($ref); $reference = $this->{$table}->get($ref_id); $reference->media_id = $id; $this->{$table}->save($reference); $this->redirect(array('action' => 'index', $table, $ref_id)); }
/** * Set the modelClass and modelKey properties based on conventions. * * If the properties are already set they will not be overwritten * * @param string $name * @return void */ protected function _setModelClass($name) { if (empty($this->modelClass)) { $this->modelClass = Inflector::pluralize($name); } }
/** * Selects the variable containing the options for a select field if present, * and sets the value to the 'options' key in the options array. * * @param string $fieldName The name of the field to find options for. * @param array $options Options list. * @return array */ protected function _optionsOptions($fieldName, $options) { if (isset($options['options'])) { return $options; } $pluralize = true; if (substr($fieldName, -5) === '._ids') { $fieldName = substr($fieldName, 0, -5); $pluralize = false; } elseif (substr($fieldName, -3) === '_id') { $fieldName = substr($fieldName, 0, -3); } $fieldName = array_slice(explode('.', $fieldName), -1)[0]; $varName = Inflector::variable($pluralize ? Inflector::pluralize($fieldName) : $fieldName); $varOptions = $this->_View->get($varName); if (!is_array($varOptions) && !$varOptions instanceof Traversable) { return $options; } if ($options['type'] !== 'radio') { $options['type'] = 'select'; } $options['options'] = $varOptions; return $options; }
/** * Detects the action and table from the name of a migration * * @param string $name Name of migration * @return array **/ public function detectAction($name) { if (preg_match('/^(Create|Drop)(.*)/', $name, $matches)) { $action = strtolower($matches[1]) . '_table'; $table = Inflector::tableize(Inflector::pluralize($matches[2])); } elseif (preg_match('/^(Add).+?(?:To)(.*)/', $name, $matches)) { $action = 'add_field'; $table = Inflector::tableize(Inflector::pluralize($matches[2])); } elseif (preg_match('/^(Remove).+?(?:From)(.*)/', $name, $matches)) { $action = 'drop_field'; $table = Inflector::tableize(Inflector::pluralize($matches[2])); } elseif (preg_match('/^(Alter)(.*)/', $name, $matches)) { $action = 'alter_table'; $table = Inflector::tableize(Inflector::pluralize($matches[2])); } else { return []; } return [$action, $table]; }