/** * Returns filtered associations for controllers models. HasMany association are filtered if * already existing in BelongsToMany * * @param Table $model The model to build associations for. * @return array associations */ public function filterAssociations(Table $model) { $belongsToManyJunctionsAliases = $this->belongsToManyJunctionAliases($model); $keys = ['BelongsTo', 'HasOne', 'HasMany', 'BelongsToMany']; $associations = []; foreach ($keys as $type) { foreach ($model->associations()->type($type) as $assoc) { $target = $assoc->target(); $assocName = $assoc->name(); $alias = $target->alias(); //filter existing HasMany if ($type === 'HasMany' && in_array($alias, $belongsToManyJunctionsAliases)) { continue; } $targetClass = get_class($target); list(, $className) = namespaceSplit($targetClass); $navLink = true; $modelClass = get_class($model); if ($modelClass !== 'Cake\\ORM\\Table' && $targetClass === $modelClass) { $navLink = false; } $className = preg_replace('/(.*)Table$/', '\\1', $className); if ($className === '') { $className = $alias; } try { $associations[$type][$assocName] = ['property' => $assoc->property(), 'variable' => Inflector::variable($assocName), 'primaryKey' => (array) $target->primaryKey(), 'displayField' => $target->displayField(), 'foreignKey' => $assoc->foreignKey(), 'alias' => $alias, 'controller' => $className, 'fields' => $target->schema()->columns(), 'navLink' => $navLink]; } catch (Exception $e) { // Do nothing it could be a bogus association name. } } } return $associations; }
/** * @param array $data * @return User */ public function entity(array $data = []) { $user = new User(); foreach ($data as $key => $value) { $property = Inflector::variable($key); $user->{$property} = $value; } return $user; }
/** * @param array $data * @return Status */ public function entity(array $data = []) { $status = new Status(); foreach ($data as $key => $value) { $property = Inflector::variable($key); $status->{$property} = $value; } return $status; }
/** * @param array $data * @return Room */ public function entity(array $data = []) { $room = new Room(); foreach ($data as $key => $value) { $property = Inflector::variable($key); $room->{$property} = $value; } return $room; }
/** * Derive the viewVar based on the scope of the action * * Actions working on a single entity will use singular name, * and actions working on a full table will use plural name * * @throws Exception * @return string */ protected function _deriveViewVar() { if ($this->scope() === 'table') { return Inflector::variable($this->_controller()->name); } if ($this->scope() === 'entity') { return Inflector::variable(Inflector::singularize($this->_controller()->name)); } throw new Exception('Unknown action scope: ' . $this->scope()); }
/** * {@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)); } }
/** * @param array $data * @return File */ public function entity(array $data = []) { $userFactory = new UserFactory(); $file = new File(); $file->account = $userFactory->entity($data['account']); unset($data['account']); foreach ($data as $key => $value) { $property = Inflector::variable($key); $file->{$property} = $value; } return $file; }
/** * @param array $data * @return Message */ public function entity(array $data = []) { // @todo ここでnewするのなんとかしたい・・・ $userFactory = new UserFactory(); $message = new Message(); $message->account = $userFactory->entity($data['account']); unset($data['account']); foreach ($data as $key => $value) { $property = Inflector::variable($key); $message->{$property} = $value; } return $message; }
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); }
/** * Render action. * * @return null|string */ public function render() { $params = $this->_entity->params(); $links = $this->_getTree(); $style = Inflector::variable($params->get('style', 'default')); if ($style == 'bootstrap') { return $this->bootstrapMenu($links); } if ($style == 'bootstrapDropDown') { return $this->bootstrapDropDownMenu($links); } return $this->defaultMenu($links); }
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 ''; }
/** * Parses a string URL into an array. If it matches, it will convert the * controller and plugin keys to their CamelCased form and action key to * camelBacked form. * * @param string $url The URL to parse * @return array|false An array of request parameters, or false on failure. */ public function parse($url) { $params = parent::parse($url); if (!$params) { return false; } if (!empty($params['controller'])) { $params['controller'] = Inflector::camelize(str_replace('-', '_', $params['controller'])); } if (!empty($params['plugin'])) { $params['plugin'] = $this->_camelizePlugin($params['plugin']); } if (!empty($params['action'])) { $params['action'] = Inflector::variable(str_replace('-', '_', $params['action'])); } return $params; }
/** * Find and publish all related models to the view * for an action * * @param NULL|string $action If NULL the current action will be used * @return void */ public function publishRelatedModels($action = null) { $models = $this->models($action); if (empty($models)) { return; } $controller = $this->_controller(); foreach ($models as $name => $association) { list(, $associationName) = pluginSplit($association->name()); $viewVar = Inflector::variable($associationName); if (array_key_exists($viewVar, $controller->viewVars)) { continue; } $query = $association->target()->find('list'); $subject = $this->_subject(compact('name', 'viewVar', 'query', 'association')); $event = $this->_trigger('relatedModel', $subject); $controller->set($event->subject->viewVar, $event->subject->query->toArray()); } }
/** * @param array $data * @return Task */ public function entity(array $data = []) { // @todo あとでroomオブジェクトの生成方法とかを見直す $roomFactory = new RoomFactory(); $userFactory = new UserFactory(); $task = new Task(); foreach ($data as $key => $value) { $property = Inflector::variable($key); if ($property == 'room') { $task->{$property} = $roomFactory->entity($value); } else { if ($property == 'assignedByAccount' || $property == 'account') { $task->{$property} = $userFactory->entity($value); } else { $task->{$property} = $value; } } } return $task; }
/** * Loads Controller and sets variables for the template * Available template variables: * * - 'modelClass' * - 'primaryKey' * - 'displayField' * - 'singularVar' * - 'pluralVar' * - 'singularHumanName' * - 'pluralHumanName' * - 'fields' * - 'keyFields' * - 'schema' * * @return array Returns variables to be made available to a view template */ protected function _loadController() { $modelObj = TableRegistry::get($this->modelName); $tableWithPrefix = $this->Model->getPrefix() . $modelObj->table(); $modelObj->table($tableWithPrefix); $primaryKey = (array) $modelObj->primaryKey(); $displayField = $modelObj->displayField(); $singularVar = $this->_singularName($this->controllerName); $singularHumanName = $this->_singularHumanName($this->controllerName); $schema = $modelObj->schema(); $fields = $schema->columns(); $modelClass = $this->modelName; $associations = $this->_filteredAssociations($modelObj); $keyFields = []; if (!empty($associations['BelongsTo'])) { foreach ($associations['BelongsTo'] as $assoc) { $keyFields[$assoc['foreignKey']] = $assoc['variable']; } } $pluralVar = Inflector::variable($this->controllerName); $pluralHumanName = $this->_pluralHumanName($this->controllerName); return compact('modelClass', 'schema', 'primaryKey', 'displayField', 'singularVar', 'pluralVar', 'singularHumanName', 'pluralHumanName', 'fields', 'associations', 'keyFields'); }
/** * Provides the dynamic findBy and findByAll methods. * * @param string $method The method name that was fired. * @param array $args List of arguments passed to the function. * @return mixed * @throws \BadMethodCallException when there are missing arguments, or when * and & or are combined. */ protected function _dynamicFinder($method, $args) { $method = Inflector::underscore($method); preg_match('/^find_([\\w]+)_by_/', $method, $matches); if (empty($matches)) { // find_by_ is 8 characters. $fields = substr($method, 8); $findType = 'all'; } else { $fields = substr($method, strlen($matches[0])); $findType = Inflector::variable($matches[1]); } $hasOr = strpos($fields, '_or_'); $hasAnd = strpos($fields, '_and_'); $makeConditions = function ($fields, $args) { $conditions = []; if (count($args) < count($fields)) { throw new BadMethodCallException(sprintf('Not enough arguments for magic finder. Got %s required %s', count($args), count($fields))); } foreach ($fields as $field) { $conditions[$this->aliasField($field)] = array_shift($args); } return $conditions; }; if ($hasOr !== false && $hasAnd !== false) { throw new BadMethodCallException('Cannot mix "and" & "or" in a magic finder. Use find() instead.'); } if ($hasOr === false && $hasAnd === false) { $conditions = $makeConditions([$fields], $args); } elseif ($hasOr !== false) { $fields = explode('_or_', $fields); $conditions = ['OR' => $makeConditions($fields, $args)]; } elseif ($hasAnd !== false) { $fields = explode('_and_', $fields); $conditions = $makeConditions($fields, $args); } return $this->find($findType, ['conditions' => $conditions]); }
/** * 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)); }
/** * Get method name * * @param \Exception $exception Exception instance. * @return string */ protected function _method(\Exception $exception) { list(, $baseClass) = namespaceSplit(get_class($exception)); $baseClass = substr($baseClass, 0, -9); $method = Inflector::variable($baseClass) ?: 'error500'; return $this->method = $method; }
/** * Extract a field value from a either the CakeRequest::$data * or Controller::$viewVars for the current model + the supplied field * * @param string $field Name of field. * @return mixed */ protected function _deriveFieldFromContext($field) { $controller = $this->_controller(); $entity = $this->_entity(); $request = $this->_request(); $value = null; if ($value = $entity->get($field)) { return $value; } $path = "{$controller->modelClass}.{$field}"; if (!empty($request->data)) { $value = Hash::get((array) $request->data, $path); } $singularVar = Inflector::variable($controller->modelClass); if (!empty($controller->viewVars[$singularVar])) { $value = $entity->get($field); } return $value; }
/** * Triggers an event for handling undefined operators. Event listeners may * capture this event and provide operator handling logic, such listeners should * alter the provided Query object and then return it back. * * The triggered event follows the pattern: * * ``` * Search.operator<CamelCaseOperatorName> * ``` * * For example, `Search.operatorAuthorName` will be triggered for * handling an operator named either `author-name` or `author_name`. * * @param \Cake\ORM\Query $query The query that is expected to be scoped * @param \Search\TokenInterface $token Token describing an operator. e.g * `-op_name:op_value` * @return mixed Scoped query object expected or null if event was not captured * by any listener */ protected function _triggerOperator(Query $query, TokenInterface $token) { $eventName = 'Search.' . (string) Inflector::variable('operator_' . $token->name()); $event = new Event($eventName, $this->_table, compact('query', 'token')); return EventManager::instance()->dispatch($event)->result; }
/** * Creates the plural variable name for views * * @param string $name Name to use * @return string Plural name for views */ protected function _variableName($name) { return Inflector::variable($name); }
/** * testVariableNaming method * * @return void */ public function testVariableNaming() { $this->assertEquals('testField', Inflector::variable('test_field')); $this->assertEquals('testFieLd', Inflector::variable('test_fieLd')); $this->assertEquals('testField', Inflector::variable('test field')); $this->assertEquals('testField', Inflector::variable('Test_field')); }
/** * @param \PHP_CodeSniffer_File $phpcsFile PHPCS file * @param array $tokens Array of tokens * @param int $stackPtr The pointer * @param string $varName The variable name * @return void */ protected function _fixVar(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $varName) { $tokens = $phpcsFile->getTokens(); $phpcsFile->fixer->beginChangeset(); preg_match('/^(_*)(.+)/', $varName, $matches); $camelCapsVarName = '$' . $matches[1] . \Cake\Utility\Inflector::variable($matches[2]); $newToken = str_replace('$' . $varName, $camelCapsVarName, $tokens[$stackPtr]['content']); $phpcsFile->fixer->replaceToken($stackPtr, $newToken); $phpcsFile->fixer->endChangeset(); }
/** * Get method name * * @param Exception $exception Exception instance. * @return string */ protected function _method(Exception $exception) { $exception = $this->_unwrap($exception); list(, $baseClass) = namespaceSplit(get_class($exception)); if (substr($baseClass, -9) === 'Exception') { $baseClass = substr($baseClass, 0, -9); } $method = Inflector::variable($baseClass) ?: 'error500'; return $this->method = $method; }
/** * Parses a check constraint source code. * * @todo: ça et les méthodes pour formater dans un utilitaire ? * * @param string $constraint Le code source de la contrainte * @return array */ protected function getValidationRuleFromConstraint($constraint) { $result = []; if (preg_match('/^cakephp_validate_(?<function>[^\\(]+)\\((?<field>[^, ]+)(, *){0,1}(?<params>.*)\\)/', $constraint, $matches)) { $function = Inflector::variable($matches['function']); $field = $this->formatField($matches['field']); $params = $this->formatParams($matches['params']); $result = [$field, $function, ['rule' => array_merge((array) $function, $params), 'message' => $this->formatMessage($function, $params)]]; } return $result; }
/** * Dynamically loads all associations of the model. * * @return void */ protected function _loadAssociations() { foreach ($this->Model->associations()->getIterator() as $association => $assocData) { $this->set(Inflector::variable($assocData->alias()), $this->Model->{$association}->find('list')->toArray()); } }
-><?php echo $field; ?> )); CakePHPBakeCloseTag> </div> </div> <?php } } ?> </div> <?php $relations = $associations['HasMany'] + $associations['BelongsToMany']; foreach ($relations as $alias => $details) { $otherSingularVar = Inflector::variable($alias); $otherPluralHumanName = Inflector::humanize($details['controller']); ?> <div class="related row"> <div class="column large-12"> <h4 class="subheader"><CakePHPBakeOpenTag= __('Related <?php echo $otherPluralHumanName; ?> ') CakePHPBakeCloseTag></h4> <CakePHPBakeOpenTagphp if (!empty($<?php echo $singularVar; ?> -><?php echo $details['property']; ?> )): CakePHPBakeCloseTag>
/** * 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; }
/** * 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; }
/** * Add a new listener to Crud * * This will not load or initialize the listener, only lazy-load it. * * If `$name` is provided but no `$class` argument, the className will * be derived from the `$name`. * * CakePHP Plugin.ClassName format for `$name` and `$class` is supported. * * @param string $name Name * @param string $className Normal CakePHP plugin-dot annotation supported. * @param array $config Any default settings for a listener. * @return void */ public function addListener($name, $className = null, $config = []) { if (strpos($name, '.') !== false) { list($plugin, $name) = pluginSplit($name); $className = $plugin . '.' . Inflector::camelize($name); } $name = Inflector::variable($name); $this->config(sprintf('listeners.%s', $name), compact('className') + $config); }