Esempio n. 1
0
 /**
  * main
  *
  */
 public function main()
 {
     $schemaPo = APP . 'Locale' . DS . 'schema.pot';
     $conn = ConnectionManager::get('default');
     $collection = $conn->schemaCollection();
     $translations = new Translations();
     $tables = $collection->listTables();
     foreach ($tables as $table) {
         $translations->insert($table, Inflector::humanize(Inflector::underscore($table)));
         $translations->insert($table, Inflector::humanize(Inflector::underscore(Inflector::singularize($table))));
         $columns = $collection->describe($table)->columns();
         foreach ($columns as $column) {
             $c = $collection->describe($table)->column($column);
             $comment = $c['comment'];
             $t = new Translation($table . '.' . $column, Inflector::humanize(Inflector::underscore($column)));
             $translations[] = $t;
             $t->setTranslation($comment);
             $t = new Translation($table . '.' . $column, Inflector::humanize(Inflector::underscore(Inflector::singularize($table))) . ' ' . Inflector::humanize(Inflector::underscore($column)));
             $translations[] = $t;
             $t->setTranslation($comment);
         }
     }
     $poString = $translations->toPoString();
     $caked = preg_replace('/msgctxt "([^"]+)"/i', '#: \\1', $poString);
     $this->createFile($schemaPo, $caked);
 }
 /**
  * Upload (Ajax)
  **/
 public function upload($ref, $ref_id)
 {
     $this->layout = null;
     $this->autoRender = false;
     if (!$this->canUploadMedias($ref, $ref_id)) {
         throw new ForbiddenException();
     }
     $media = $this->Medias->newEntity();
     $model = Inflector::singularize($ref);
     if (isset($_FILES) && !empty($_FILES)) {
         $data['ref'] = $model;
         $data['ref_id'] = $ref_id;
         $data['file'] = $_FILES['file'];
         $new_media = $this->Medias->patchEntity($media, $data);
         $this->Medias->save($new_media, $_FILES);
         if ($this->Medias->error != "") {
             echo json_encode(array('error' => $this->Medias->error));
             return false;
         }
     }
     $this->loadModel($ref);
     $editor = isset($this->request->params['named']['editor']) ? $this->request->params['named']['editor'] : false;
     $id = isset($this->request->query['id']) ? $this->request->query['id'] : false;
     $this->set(compact('media', 'thumbID', 'editor', 'id'));
     $this->layout = 'json';
     $this->render('media');
 }
 public function output($field, $options = array())
 {
     // if there is a override type on the field, don't make it a belongsTo link
     if (!$this->helper->hasOverride($field)) {
         // if this is a belongsTo field, make it a link to the parent record
         if (in_array($field, $this->helper->foreignKeys()) && ($this->belongsTo = $this->fieldIsKey($field, 'manyToOne'))) {
             $nameable = new NameConventions($field);
             $association_name = strtolower($nameable->modelName);
             // This is the name of the associated entity. It will also be
             // the node on the parent entity where the associated entity
             // can be found (the conventional location)
             $association_entity = Inflector::singularize($association_name);
             // This is going to contain the associated Table object
             $association = $this->helper->CrudData->associationCollection()->get($association_name);
             if (!is_null($association) && is_subclass_of($this->helper->entity->{$association_entity}, 'Cake\\ORM\\Entity')) {
                 $displayField = $association->displayField();
                 $output = $this->helper->entity->{$association_entity}->{$displayField};
                 //					$this->helper->CrudData->_columns[$field] = ['type' => 'string']; ////// THIS CASCADES TO ATTRIBUTES TOO
                 //
                 //					$this->helper->swapEntity($this->helper->entity->$association_entity);
                 //					$output = $this->base->output($displayField, $options);
                 //					$this->helper->restoreEntity();
             } else {
                 $output = $this->base->output($field, $options);
             }
             return $this->helper->entity->has($this->belongsTo['property']) ? $this->helper->Html->link($output, ['controller' => $this->belongsTo['name'], 'action' => 'view', $this->helper->entity->{$field}]) : '';
         }
     }
     return $this->base->output($field, $options);
 }
Esempio n. 4
0
 /**
  * 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());
 }
Esempio n. 5
0
 /**
  * Sets the property name that should be filled with data from the target table
  * in the source table record.
  * If no arguments are passed, currently configured type is returned.
  *
  * @param string|null $name The name of the property. Pass null to read the current value.
  * @return string
  */
 public function property($name = null)
 {
     if ($name !== null) {
         return parent::property($name);
     }
     if ($name === null && !$this->_propertyName) {
         list(, $name) = pluginSplit($this->_name);
         $this->_propertyName = Inflector::underscore(Inflector::singularize($name));
     }
     return $this->_propertyName;
 }
 /**
  * Sets the name of the field representing the foreign key to the source table.
  * If no parameters are passed current field is returned
  *
  * @param string $key the key to be used to link both tables together
  * @return string
  */
 public function foreignKey($key = null)
 {
     if ($key === null) {
         if ($this->_foreignKey === null) {
             $key = Inflector::singularize($this->source()->alias());
             $this->_foreignKey = Inflector::underscore($key) . '_id';
         }
         return $this->_foreignKey;
     }
     return parent::foreignKey($key);
 }
Esempio n. 7
0
 /**
  * Delete action.
  *
  * @param string|null $id Menu id.
  * @return void Redirects to index.
  * @throws \Cake\Network\Exception\NotFoundException When record not found.
  */
 public function delete($id = null)
 {
     $this->request->allowMethod(['post', 'delete']);
     $controllerName = Inflector::singularize($this->name);
     $lowerController = mb_strtolower($controllerName);
     $record = $this->{$this->name}->get($id);
     $domain = Plugin::getPluginName($this->plugin);
     if ($this->{$this->name}->delete($record)) {
         $this->Flash->success(__d($domain, 'The {0} has been deleted.', $lowerController));
     } else {
         $this->Flash->error(__d($domain, 'The {0} could not be deleted. Please, try again.', $lowerController));
     }
     return $this->redirect(['action' => 'index']);
 }
 public function alterSchema(Schema $schema)
 {
     $customizedType = Inflector::singularize($schema->name());
     $customFields = $this->find()->cache('custom_fields_' . $this->connection()->configName());
     /** @var \Muffin\Webservice\Model\Resource[] $customFields */
     foreach ($customFields as $customField) {
         if ($customField->customized_type !== $customizedType) {
             continue;
         }
         $columnKeys = ['type' => $customField->field_format, 'default' => $customField->default_value, 'custom_field_id' => $customField->id, 'custom_field_filterable' => $customField->is_filter];
         $schema->addColumn(Schema::nameToField($customField->name), $columnKeys);
     }
     return $schema;
 }
 public function setDefaultTitle()
 {
     switch ($this->request->params['action']) {
         case 'index':
             return Inflector::humanize($this->request->params['controller']);
         case 'add':
             return 'New ' . Inflector::singularize(Inflector::humanize($this->request->params['controller']));
         case 'edit':
             return 'Edit ' . Inflector::singularize(Inflector::humanize($this->request->params['controller']));
         case 'image':
             return 'Image for ' . Inflector::singularize(Inflector::humanize($this->request->params['controller']));
         default:
             return Inflector::humanize($this->request->params['action']);
     }
     return false;
 }
 /**
  * Method that adds elements to index View top menu.
  *
  * @param  Cake\Event\Event     $event   Event object
  * @param  Cake\Network\Request $request Request object
  * @param  array                $options Entity options
  * @return undefined
  */
 public function getIndexMenuTop(Event $event, Request $request, array $options)
 {
     $appView = $event->subject();
     if (!$appView instanceof View) {
         $appView = new AppView();
     }
     $urlAdd = ['plugin' => $request->plugin, 'controller' => $request->controller, 'action' => 'add'];
     $btnAdd = $appView->Html->link($appView->Html->icon('plus') . self::BLANK_SPACE . __('Add {0}', Inflector::singularize($options['title'])), $urlAdd, ['escape' => false, 'class' => 'btn btn-primary']);
     $menu = [['label' => $btnAdd, 'url' => $urlAdd, 'capabilities' => 'fromUrl']];
     if ($appView->elementExists(static::MENU_ELEMENT)) {
         $result = $appView->element(static::MENU_ELEMENT, ['menu' => $menu, 'renderAs' => 'provided']);
     } else {
         $result = $btnAdd;
     }
     return $result;
 }
 /**
  * Upload a file to the server
  * @param upload - file to upload
  * @param owner - contains model name and id associated with the file
  * @return array - uploaded file information or null for failure
  */
 public function upload($upload, $owner = null)
 {
     // Filesize verification
     if ($upload['size'] == 0) {
         return null;
     }
     if ($upload['size'] > $this->maxFileSize) {
         return null;
     }
     $path = $this->storagePath;
     // Owner separated storage
     if ($this->storeOwner == true && $owner) {
         // Directory should be lower case
         $ownerTable = strtolower($owner->source());
         // Owner specific directory must be unique (uuid)
         $ownerDirectory = Inflector::singularize($ownerTable) . $owner->id;
         $path .= DS . $ownerTable . DS . $ownerDirectory;
     }
     // If types do not match, default subdir is 'document'
     $subdir = 'document';
     $types = ['image', 'audio', 'video'];
     // Check for filetype
     foreach ($types as $type) {
         if (strstr($upload['type'], $type)) {
             $subdir = $type;
         }
     }
     // Append the subdirectory (filtype directory)
     $path .= DS . $subdir;
     // Make directory if there is none
     $directory = new Folder();
     if (!$directory->create(WWW_ROOT . DS . $path)) {
         return null;
     }
     // Find file in tmp
     $file = new File($upload['tmp_name']);
     // File's name must be unique, making the path unique as well
     $name = time() . '_' . Inflector::slug($upload['name']);
     $path .= DS . $name;
     // Copy from tmp to perm (create)
     if ($file->copy($path)) {
         return ['original_name' => $upload['name'], 'name' => $name, 'path' => $path, 'type' => $upload['type'], 'size' => $upload['size']];
     } else {
         return null;
     }
 }
Esempio n. 12
0
 /**
  * Build Form::inputs structure
  *
  * @param ParameterRegistry $parameters Form parameters collection.
  * @param array $options Additional input options.
  * @return array
  */
 public function inputs(ParameterRegistry $parameters, $options = [])
 {
     $result = [];
     $entityName = Inflector::singularize($parameters->formName);
     foreach ($parameters->collection() as $primaryParameter) {
         foreach ($primaryParameter->viewValues() as $param) {
             $name = $param->config('name');
             $inputOptions = array_key_exists($name, $options) ? $options[$name] : [];
             $input = $this->input($param, $inputOptions);
             $field = $param->config('field');
             if (!empty($entityName)) {
                 $field = "{$entityName}.{$field}";
             }
             $result[$field] = $input;
         }
     }
     return $result;
 }
 /**
  * @param string $entityName
  * @param array $data
  * @return Entity\EntityInterface
  * @throws Exception\LogicException
  */
 public function getEntity($entityName, array $data = [])
 {
     $class = '';
     $classCandidates = [__NAMESPACE__ . '\\Entity\\' . trim($entityName, '\\'), __NAMESPACE__ . '\\Entity\\Subset\\' . trim($entityName, '\\')];
     foreach ($classCandidates as $classCandidate) {
         if (class_exists($classCandidate)) {
             $class = $classCandidate;
             break;
         }
     }
     if (!$class) {
         throw new LogicException("Entity \"{$entityName}\" is undefined.");
     }
     $entity = new $class();
     if (!$entity instanceof EntityInterface) {
         throw new LogicException("Class \"{$class}\" isn't an implement of EntityInterface.");
     }
     foreach ($data as $key => $value) {
         if (is_array($value)) {
             $childEntityName = Inflector::singularize((string) Inflector::camelize($key));
             if (Hash::check($value, '{s}')) {
                 // has string key => entity.
                 $value = $this->getEntity($childEntityName, $value);
             } elseif (Hash::check($value, '{n}.{s}')) {
                 // has string key under number key => array of entities.
                 $children = [];
                 foreach ($value as $child) {
                     $children[] = $this->getEntity($childEntityName, $child);
                 }
                 $value = $children;
             } else {
                 // else => array of scalar.
             }
         }
         if (property_exists($entity, $key)) {
             $entity->{$key} = $value;
         }
     }
     return $entity;
 }
Esempio n. 14
0
 public function paginate($query = null, array $settings = [])
 {
     $action = $this->request->action;
     $nested = strcmp(substr($action, -5, 5), 'Index') === 0;
     if (!$nested) {
         foreach (explode(' ', $this->request->query('q')) as $q) {
             foreach ($this->searchFields as $field) {
                 $ORs["{$field} LIKE"] = "%{$q}%";
             }
             if (empty($q) || empty($ORs)) {
                 continue;
             }
             $query->where(["OR" => $ORs]);
         }
     } else {
         if (isset($this->viewVars['parent'])) {
             $key = Inflector::singularize(substr($action, 0, -5)) . '_id';
             $query->where([$key => $this->viewVars['parent']->id]);
         }
     }
     return $query->all();
 }
Esempio n. 15
0
 /**
  * Returns the class used to hydrate rows for this table or sets
  * a new one
  *
  * @param string|null $name the name of the class to use
  * @throws \Cake\ORM\Exception\MissingEntityException when the entity class cannot be found
  * @return string
  */
 public function entityClass($name = null)
 {
     if ($name === null && !$this->_entityClass) {
         $default = '\\Cake\\ORM\\Entity';
         $self = get_called_class();
         $parts = explode('\\', $self);
         if ($self === __CLASS__ || count($parts) < 3) {
             return $this->_entityClass = $default;
         }
         $alias = Inflector::singularize(substr(array_pop($parts), 0, -5));
         $name = implode('\\', array_slice($parts, 0, -1)) . '\\Entity\\' . $alias;
         if (!class_exists($name)) {
             return $this->_entityClass = $default;
         }
     }
     if ($name !== null) {
         $class = Core::className($name, 'Model/Entity');
         $this->_entityClass = $class;
     }
     if (!$this->_entityClass) {
         throw new MissingEntityException([$name]);
     }
     return $this->_entityClass;
 }
Esempio n. 16
0
 /**
  * Wrap a set of inputs in a fieldset
  *
  * @param string $fields the form inputs to wrap in a fieldset
  * @param array $options Options array. Valid keys are:
  * - `fieldset` Set to false to disable the fieldset. You can also pass an array of params to be
  *    applied as HTML attributes to the fieldset tag. If you pass an empty array, the fieldset will
  *    be enabled
  * - `legend` Set to false to disable the legend for the generated input set. Or supply a string
  *    to customize the legend text.
  * @return string Completed form inputs.
  */
 public function fieldset($fields = '', array $options = [])
 {
     $fieldset = $legend = true;
     $context = $this->_getContext();
     $out = $fields;
     if (isset($options['legend'])) {
         $legend = $options['legend'];
     }
     if (isset($options['fieldset'])) {
         $fieldset = $options['fieldset'];
     }
     if ($legend === true) {
         $actionName = __d('cake', 'New %s');
         $isCreate = $context->isCreate();
         if (!$isCreate) {
             $actionName = __d('cake', 'Edit %s');
         }
         $modelName = Inflector::humanize(Inflector::singularize($this->request->params['controller']));
         $legend = sprintf($actionName, $modelName);
     }
     if ($fieldset !== false) {
         if ($legend) {
             $out = $this->formatTemplate('legend', ['text' => $legend]) . $out;
         }
         $fieldsetParams = ['content' => $out, 'attrs' => ''];
         if (is_array($fieldset) && !empty($fieldset)) {
             $fieldsetParams['attrs'] = $this->templater()->formatAttributes($fieldset);
         }
         $out = $this->formatTemplate('fieldset', $fieldsetParams);
     }
     return $out;
 }
Esempio n. 17
0
 /**
  * Get CounterCaches
  *
  * @param \Cake\ORM\Table $model The table to get counter cache fields for.
  * @return array CounterCache configurations
  */
 public function getCounterCache($model)
 {
     $belongsTo = $this->findBelongsTo($model, ['belongsTo' => []]);
     $counterCache = [];
     foreach ($belongsTo['belongsTo'] as $otherTable) {
         $otherAlias = $otherTable['alias'];
         $otherModel = $this->getTableObject($this->_camelize($otherAlias), Inflector::underscore($otherAlias));
         try {
             $otherSchema = $otherModel->schema();
         } catch (\Cake\Database\Exception $e) {
             continue;
         }
         $otherFields = $otherSchema->columns();
         $alias = $model->alias();
         $field = Inflector::singularize(Inflector::underscore($alias)) . '_count';
         if (in_array($field, $otherFields, true)) {
             $counterCache[] = "'{$otherAlias}' => ['{$field}']";
         }
     }
     return $counterCache;
 }
Esempio n. 18
0
 /**
  * Generate REST resource routes for the given controller(s).
  *
  * A quick way to generate a default routes to a set of REST resources (controller(s)).
  *
  * ### Usage
  *
  * Connect resource routes for an app controller:
  *
  * ```
  * $routes->resources('Posts');
  * ```
  *
  * Connect resource routes for the Comments controller in the
  * Comments plugin:
  *
  * ```
  * Router::plugin('Comments', function ($routes) {
  *   $routes->resources('Comments');
  * });
  * ```
  *
  * Plugins will create lower_case underscored resource routes. e.g
  * `/comments/comments`
  *
  * Connect resource routes for the Articles controller in the
  * Admin prefix:
  *
  * ```
  * Router::prefix('admin', function ($routes) {
  *   $routes->resources('Articles');
  * });
  * ```
  *
  * Prefixes will create lower_case underscored resource routes. e.g
  * `/admin/posts`
  *
  * You can create nested resources by passing a callback in:
  *
  * ```
  * $routes->resources('Articles', function ($routes) {
  *   $routes->resources('Comments');
  * });
  * ```
  *
  * The above would generate both resource routes for `/articles`, and `/articles/:article_id/comments`.
  * You can use the `map` option to connect additional resource methods:
  *
  * ```
  * $routes->resources('Articles', [
  *   'map' => ['deleteAll' => ['action' => 'deleteAll', 'method' => 'DELETE']]
  * ]);
  * ```
  *
  * In addition to the default routes, this would also connect a route for `/articles/delete_all`.
  * By default the path segment will match the key name. You can use the 'path' key inside the resource
  * definition to customize the path name.
  *
  * You can use the `inflect` option to change how path segments are generated:
  *
  * ```
  * $routes->resources('PaymentTypes', ['inflect' => 'dasherize']);
  * ```
  *
  * Will generate routes like `/payment-types` instead of `/payment_types`
  *
  * ### Options:
  *
  * - 'id' - The regular expression fragment to use when matching IDs. By default, matches
  *    integer values and UUIDs.
  * - 'inflect' - Choose the inflection method used on the resource name. Defaults to 'underscore'.
  * - 'only' - Only connect the specific list of actions.
  * - 'actions' - Override the method names used for connecting actions.
  * - 'map' - Additional resource routes that should be connected. If you define 'only' and 'map',
  *   make sure that your mapped methods are also in the 'only' list.
  * - 'prefix' - Define a routing prefix for the resource controller. If the current scope
  *   defines a prefix, this prefix will be appended to it.
  * - 'connectOptions' – Custom options for connecting the routes.
  *
  * @param string $name A controller name to connect resource routes for.
  * @param array|callable $options Options to use when generating REST routes, or a callback.
  * @param callable|null $callback An optional callback to be executed in a nested scope. Nested
  *   scopes inherit the existing path and 'id' parameter.
  * @return void
  */
 public function resources($name, $options = [], $callback = null)
 {
     if (is_callable($options) && $callback === null) {
         $callback = $options;
         $options = [];
     }
     $options += ['connectOptions' => [], 'inflect' => 'underscore', 'id' => static::ID . '|' . static::UUID, 'only' => [], 'actions' => [], 'map' => [], 'prefix' => null];
     foreach ($options['map'] as $k => $mapped) {
         $options['map'][$k] += ['method' => 'GET', 'path' => $k, 'action' => ''];
     }
     $ext = null;
     if (!empty($options['_ext'])) {
         $ext = $options['_ext'];
     }
     $connectOptions = $options['connectOptions'];
     $method = $options['inflect'];
     $urlName = Inflector::$method($name);
     $resourceMap = array_merge(static::$_resourceMap, $options['map']);
     $only = (array) $options['only'];
     if (empty($only)) {
         $only = array_keys($resourceMap);
     }
     $prefix = '';
     if ($options['prefix']) {
         $prefix = $options['prefix'];
     }
     if (isset($this->_params['prefix']) && $prefix) {
         $prefix = $this->_params['prefix'] . '/' . $prefix;
     }
     foreach ($resourceMap as $method => $params) {
         if (!in_array($method, $only, true)) {
             continue;
         }
         $action = $params['action'];
         if (isset($options['actions'][$method])) {
             $action = $options['actions'][$method];
         }
         $url = '/' . implode('/', array_filter([$urlName, $params['path']]));
         $params = ['controller' => $name, 'action' => $action, '_method' => $params['method']];
         if ($prefix) {
             $params['prefix'] = $prefix;
         }
         $routeOptions = $connectOptions + ['id' => $options['id'], 'pass' => ['id'], '_ext' => $ext];
         $this->connect($url, $params, $routeOptions);
     }
     if (is_callable($callback)) {
         $idName = Inflector::singularize(str_replace('-', '_', $urlName)) . '_id';
         $path = '/' . $urlName . '/:' . $idName;
         $this->scope($path, [], $callback);
     }
 }
Esempio n. 19
0
'), ['action' => 'add']) CakePHPBakeCloseTag> </li>
<?php 
$done = [];
foreach ($associations as $type => $data) {
    foreach ($data as $alias => $details) {
        if ($details['controller'] != $this->name && !in_array($details['controller'], $done)) {
            ?>
        <li><CakePHPBakeOpenTag= $this->Html->link(__('List <?php 
            echo $this->_pluralHumanName($alias);
            ?>
'), ['controller' => '<?php 
            echo $details['controller'];
            ?>
', 'action' => 'index']) CakePHPBakeCloseTag> </li>
        <li><CakePHPBakeOpenTag= $this->Html->link(__('New <?php 
            echo Inflector::humanize(Inflector::singularize(Inflector::underscore($alias)));
            ?>
'), ['controller' => '<?php 
            echo $details['controller'];
            ?>
', 'action' => 'add']) CakePHPBakeCloseTag> </li>
<?php 
            $done[] = $details['controller'];
        }
    }
}
?>
    </ul>
</div>
<div class="<?php 
echo $pluralVar;
Esempio n. 20
0
 /**
  * Upload (Ajax)
  **/
 public function upload($ref, $ref_id)
 {
     $this->viewBuilder()->layout(null);
     $this->autoRender = false;
     if (!$this->canUploadMedias($ref, $ref_id)) {
         //throw new ForbiddenException();
         die('probleme');
     }
     $media = $this->Medias->newEntity();
     $file = $_FILES;
     //debug($file); die();
     if (empty($file)) {
         die('fichier trop volumineux');
         return false;
     }
     //debug($media);die();
     $model = Inflector::singularize($ref);
     if (isset($_FILES) && !empty($_FILES)) {
         $data = ['ref' => $ref, 'ref_id' => $ref_id, 'file' => $_FILES['file']['name'], 'name' => $_FILES['file']['name']];
         $new_media = $this->Medias->patchEntity($media, $data);
         //debug($media);die();
         $this->Medias->save($new_media, $file);
         if (!empty($new_media->errors())) {
             echo json_encode(array('error' => $new_media->errors()));
             return false;
         }
     }
     //$media = $this->Medias->find('all');
     $this->loadModel($ref);
     $thumbID = false;
     if ($this->{$ref}->hasField('media_id')) {
         $reference = $this->{$ref}->get($ref_id);
         $thumbID = $reference->media_id;
     }
     $editor = isset($this->request->params['named']['editor']) ? $this->request->params['named']['editor'] : false;
     $id = isset($this->request->query['id']) ? $this->request->query['id'] : false;
     $this->set(compact('media', 'thumbID', 'editor', 'id', 'file', 'ref'));
     $this->viewBuilder()->layout('json');
     $this->render('media');
 }
Esempio n. 21
0
 /**
  * Returns the class used to hydrate rows for this table or sets
  * a new one
  *
  * @param string $name the name of the class to use
  * @throws \RuntimeException when the entity class cannot be found
  * @return string
  */
 public function entityClass($name = null)
 {
     if ($name === null && !$this->_documentClass) {
         $default = '\\Cake\\ElasticSearch\\Document';
         $self = get_called_class();
         $parts = explode('\\', $self);
         if ($self === __CLASS__ || count($parts) < 3) {
             return $this->_documentClass = $default;
         }
         $alias = Inflector::singularize(substr(array_pop($parts), 0, -4));
         $name = implode('\\', array_slice($parts, 0, -1)) . '\\Document\\' . $alias;
         if (!class_exists($name)) {
             return $this->_documentClass = $default;
         }
     }
     if ($name !== null) {
         $class = App::classname($name, 'Model/Document');
         $this->_documentClass = $class;
     }
     if (!$this->_documentClass) {
         throw new \RuntimeException(sprintf('Missing document class "%s"', $class));
     }
     return $this->_documentClass;
 }
Esempio n. 22
0
 /**
  * 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;
 }
 /**
  * addButton
  *
  * An `add`-button with a link to add a new PostType Entity.
  *
  * ### Options
  * - `before` - Html before the button.
  * - `after` - Html after the button.
  *
  * The link will be created via the HtmlHelper.
  *
  * @param array $options Options.
  * @return string
  */
 public function addButton($options = [])
 {
     $_options = ['before' => 'New ', 'after' => ''];
     $options = array_merge($_options, $options);
     $string = $options['before'] . h(Inflector::singularize($this->_type['alias'])) . $options['after'];
     return $this->Html->link($string, ['action' => 'add', 'type' => $this->_type['slug']]);
 }
Esempio n. 24
0
 /**
  * Creates the singular human name used in views
  *
  * @param string $name Controller name
  * @return string Singular human name
  */
 protected function _singularHumanName($name)
 {
     return Inflector::humanize(Inflector::underscore(Inflector::singularize($name)));
 }
Esempio n. 25
0
 /**
  * Derive resource name
  *
  * @return string
  */
 protected function _deriveResourceName()
 {
     $inflectionType = $this->config('inflection');
     if ($inflectionType === null) {
         $inflectionType = $this->scope() === 'entity' ? 'singular' : 'plural';
     }
     if ($inflectionType === 'singular') {
         return strtolower(Inflector::humanize(Inflector::singularize(Inflector::underscore($this->_table()->alias()))));
     }
     return strtolower(Inflector::humanize(Inflector::underscore($this->_table()->alias())));
 }
Esempio n. 26
0
 /**
  * Mock a model, maintain fixtures and table association
  *
  * @param string $alias The model to get a mock for.
  * @param mixed $methods The list of methods to mock
  * @param array $options The config data for the mock's constructor.
  * @throws \Cake\ORM\Exception\MissingTableClassException
  * @return \Cake\ORM\Table|\PHPUnit_Framework_MockObject_MockObject
  */
 public function getMockForModel($alias, array $methods = [], array $options = [])
 {
     if (empty($options['className'])) {
         $class = Inflector::camelize($alias);
         $className = App::className($class, 'Model/Table', 'Table');
         if (!$className) {
             throw new MissingTableClassException([$alias]);
         }
         $options['className'] = $className;
     }
     $connectionName = $options['className']::defaultConnectionName();
     $connection = ConnectionManager::get($connectionName);
     list(, $baseClass) = pluginSplit($alias);
     $options += ['alias' => $baseClass, 'connection' => $connection];
     $options += TableRegistry::config($alias);
     $mock = $this->getMock($options['className'], $methods, [$options]);
     if (empty($options['entityClass']) && $mock->entityClass() === '\\Cake\\ORM\\Entity') {
         $parts = explode('\\', $options['className']);
         $entityAlias = Inflector::singularize(substr(array_pop($parts), 0, -5));
         $entityClass = implode('\\', array_slice($parts, 0, -1)) . '\\Entity\\' . $entityAlias;
         if (class_exists($entityClass)) {
             $mock->entityClass($entityClass);
         }
     }
     TableRegistry::set($baseClass, $mock);
     return $mock;
 }
Esempio n. 27
0
 /**
  * Delete method
  *
  * @param string|null $id User id.
  * @return Response Redirects to index.
  * @throws NotFoundException When record not found.
  */
 public function delete($id = null)
 {
     $this->request->allowMethod(['post', 'delete']);
     $table = $this->loadModel();
     $tableAlias = $table->alias();
     $entity = $table->get($id, ['contain' => []]);
     $singular = Inflector::singularize(Inflector::humanize($tableAlias));
     if ($table->delete($entity)) {
         $this->Flash->success(__d('CakeDC/Users', 'The {0} has been deleted', $singular));
     } else {
         $this->Flash->error(__d('CakeDC/Users', 'The {0} could not be deleted', $singular));
     }
     return $this->redirect(['action' => 'index']);
 }
Esempio n. 28
0
 /**
  * Returns default property name based on association name.
  *
  * @return string
  */
 protected function _propertyName()
 {
     list(, $name) = pluginSplit($this->_name);
     return Inflector::underscore(Inflector::singularize($name));
 }
 /**
  * Delete method
  *
  * @param string|null $id entity id.
  * @return Response Redirects to index.
  * @throws NotFoundException When record not found.
  */
 public function delete($id = null)
 {
     $table = $this->loadModel();
     $tableAlias = $table->alias();
     $entity = $table->get($id, ['contain' => []]);
     $singular = Inflector::singularize(Inflector::humanize($tableAlias));
     if ($table->delete($entity)) {
         $this->Flash->success(__('The {0} has been deleted', $singular));
     } else {
         $this->Flash->error(__('The {0} could not be deleted', $singular));
     }
     return $this->redirect($this->referer());
 }
Esempio n. 30
0
 /**
  * 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;
 }