slice() public static méthode

Usage examples: embed:lithium\tests\cases\util\SetTest::testSetSlice(1-4)
public static slice ( array $data, array | string $keys ) : array
$data array
$keys array | string An array of keys or a single key as string
Résultat array An array containing both arrays, having the array with requested keys first and the remainder as second element
 public function run($id = null)
 {
     $id = !is_null($id) ? $id : $this->request->id;
     $model = $this->scaffold['model'];
     $object = $model::first($id);
     if (!$object) {
         $url = array('action' => 'index');
         return $this->redirect($url);
     }
     list($temp, $options) = Set::slice($this->request->data, array('validate', 'strict'));
     switch ($this->request->data['mode']) {
         case 'keep':
             $options['overwrite'] = false;
             break;
         case 'remove':
             $options['prune'] = true;
             break;
     }
     $result = $object->run($options);
     $url = array('action' => 'view', 'args' => array((string) $object->{$model::key()}));
     return $this->redirect($url);
 }
Exemple #2
0
 /**
  * Convert the query's properties to the data sources' syntax and return it as an array.
  *
  * @param \lithium\data\Source $source Instance of the data source to use for conversion.
  * @param array $options Options to use when exporting the data.
  * @return array Returns an array containing a data source-specific representation of a query.
  */
 public function export(Source $source, array $options = array())
 {
     $defaults = array('keys' => array());
     $options += $defaults;
     if ($options['keys']) {
         $keys = array_flip($options['keys']);
     } else {
         $keys =& $this->_config;
     }
     list($copy, $apply) = Set::slice($keys, $source->methods());
     if (isset($keys['with'])) {
         $this->applyStrategy($source);
     }
     foreach ($apply as $item => $value) {
         $results[$item] = $source->{$item}($this->{$item}(), $this);
     }
     foreach ($copy as $item => $value) {
         $results[$item] = $this->_config[$item];
     }
     if (array_key_exists('data', $keys)) {
         $results['data'] = $this->_exportData();
     }
     if (array_key_exists('source', $keys)) {
         $results['source'] = $source->name($results['source']);
     }
     if (!isset($results['fields'])) {
         return $results;
     }
     $created = array('fields', 'values');
     if (is_array($results['fields']) && array_keys($results['fields']) == $created) {
         $results = $results['fields'] + $results;
     }
     return $results;
 }
 public function testSetSlice()
 {
     $data = array('key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3');
     list($kept, $removed) = Set::slice($data, array('key3'));
     $this->assertEqual(array('key3' => 'val3'), $removed);
     $this->assertEqual(array('key1' => 'val1', 'key2' => 'val2'), $kept);
     $data = array('key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3');
     list($kept, $removed) = Set::slice($data, array('key1', 'key3'));
     $this->assertEqual(array('key1' => 'val1', 'key3' => 'val3'), $removed);
     $this->assertEqual(array('key2' => 'val2'), $kept);
     $data = array('key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3');
     list($kept, $removed) = Set::slice($data, 'key2');
     $this->assertEqual(array('key2' => 'val2'), $removed);
     $this->assertEqual(array('key1' => 'val1', 'key3' => 'val3'), $kept);
     $data = array('key1' => 'val1', 'key2' => 'val2', 'key3' => array('foo' => 'bar'));
     list($kept, $removed) = Set::slice($data, array('key1', 'key3'));
     $this->assertEqual(array('key1' => 'val1', 'key3' => array('foo' => 'bar')), $removed);
     $this->assertEqual(array('key2' => 'val2'), $kept);
 }
Exemple #4
0
 /**
  * Initializer. Initializes properties like `Database::$_strategies` because
  * closures cannot be created within the class definition.
  *
  * @see lithium\data\source\Database::$_columns
  * @see lithium\data\source\Database::$_strings
  * @see lithium\data\source\Database::$_strategies
  */
 protected function _init()
 {
     parent::_init();
     $formatters = $this->_formatters();
     foreach ($this->_columns as $type => $column) {
         if (isset($formatters[$type])) {
             $this->_columns[$type]['formatter'] = $formatters[$type];
         }
     }
     $this->_strings += array('read' => 'SELECT {:fields} FROM {:source} {:alias} {:joins} {:conditions} {:group} ' . '{:having} {:order} {:limit};{:comment}');
     $this->_strategies += array('joined' => function ($self, $model, $context) {
         $with = $context->with();
         $strategy = function ($me, $model, $tree, $path, $from, &$deps) use($self, $context, $with) {
             foreach ($tree as $name => $childs) {
                 if (!($rel = $model::relations($name))) {
                     throw new QueryException("Model relationship `{$name}` not found.");
                 }
                 $constraints = array();
                 $alias = $name;
                 $relPath = $path ? $path . '.' . $name : $name;
                 if (isset($with[$relPath])) {
                     list($unallowed, $allowed) = Set::slice($with[$relPath], array('alias', 'constraints'));
                     if ($unallowed) {
                         $message = "Only `'alias'` and `'constraints'` are allowed in ";
                         $message .= "`'with'` using the `'joined'` strategy.";
                         throw new QueryException($message);
                     }
                     extract($with[$relPath]);
                 }
                 $to = $context->alias($alias, $relPath);
                 $deps[$to] = $deps[$from];
                 $deps[$to][] = $from;
                 if ($context->relationships($relPath) === null) {
                     $context->relationships($relPath, array('type' => $rel->type(), 'model' => $rel->to(), 'fieldName' => $rel->fieldName(), 'alias' => $to));
                     $self->join($context, $rel, $from, $to, $constraints);
                 }
                 if (!empty($childs)) {
                     $me($me, $rel->to(), $childs, $relPath, $to, $deps);
                 }
             }
         };
         $tree = Set::expand(array_fill_keys(array_keys($with), false));
         $alias = $context->alias();
         $deps = array($alias => array());
         $strategy($strategy, $model, $tree, '', $alias, $deps);
         $models = $context->models();
         foreach ($context->fields() as $field) {
             if (!is_string($field)) {
                 continue;
             }
             list($alias, $field) = $self->invokeMethod('_splitFieldname', array($field));
             $alias = $alias ?: $field;
             if ($alias && isset($models[$alias])) {
                 foreach ($deps[$alias] as $depAlias) {
                     $depModel = $models[$depAlias];
                     $context->fields(array($depAlias => (array) $depModel::meta('key')));
                 }
             }
         }
     }, 'nested' => function ($self, $model, $context) {
         throw new QueryException("This strategy is not yet implemented.");
     });
 }
Exemple #5
0
 /**
  * imports data attribute into database. Allows importing of all model data within one file.
  * Will call a method on each model, named `bulkImport` (can be customized) to do the heavy
  * lifting of import. Thus, it allows overwriting the import on a per-model basis.
  *
  * The data of the asset, to be decoded must have the following structure:
  *
  *	Array (
  *		'radium\\models\\Contents' => Array (
  *			'5328587a4eaa3af84e000000' => Array (
  *				'key' => 'value'   // all data per model
  *			),
  *			'5428587a4eaa3af84e000001' => Array (
  *				'key' => 'value'   // all data per model
  *			),
  *		),
  *
  * @see radium\data\BaseModel::bulkImport()
  * @param object $asset instance of current record
  * @param array $options additional options, will be passed into bulkImport method.
  *        - `function`: pass in a callback to handle the import of each record on the
  *                      corresponding model class, defaults to `bulkImport`.
  * @return array parsed content of Assets bytes
  */
 public function import($asset, array $options = array())
 {
     $defaults = array('function' => 'bulkImport');
     $options += $defaults;
     $data = $asset->decode();
     $result = array();
     list($temp, $params) = Set::slice($options, array('dry', 'prune', 'overwrite', 'strict'));
     $models = array_keys($data);
     foreach ($models as $model) {
         $items =& $data[$model];
         $result[$model] = call_user_func(array($model, $options['function']), $items, $params);
     }
     return $result;
 }
 /**
  * Creates the database object and set default values for it.
  *
  * Options defined:
  *  - 'database' _string_ Name of the database to use. Defaults to `null`.
  *  - 'host' _string_ Name/address of server to connect to. Defaults to 'localhost'.
  *  - 'login' _string_ Username to use when connecting to server. Defaults to 'root'.
  *  - 'password' _string_ Password to use when connecting to server. Defaults to `''`.
  *  - 'persistent' _boolean_ If true a persistent connection will be attempted, provided the
  *    adapter supports it. Defaults to `true`.
  *
  * @param $config array Array of configuration options.
  * @return Database object.
  */
 public function __construct(array $config = array())
 {
     $defaults = array('persistent' => true, 'host' => 'localhost', 'login' => 'root', 'password' => '', 'database' => null, 'encoding' => null, 'dsn' => null, 'options' => array());
     $this->_strings += array('read' => 'SELECT {:fields} FROM {:source} {:alias} {:joins} {:conditions} {:group} ' . '{:having} {:order} {:limit};{:comment}');
     $this->_strategies += array('joined' => function ($self, $model, $context) {
         $with = $context->with();
         $strategy = function ($me, $model, $tree, $path, $from, &$deps) use($self, $context, $with) {
             foreach ($tree as $name => $childs) {
                 if (!($rel = $model::relations($name))) {
                     throw new QueryException("Model relationship `{$name}` not found.");
                 }
                 $constraints = array();
                 $alias = $name;
                 $relPath = $path ? $path . '.' . $name : $name;
                 if (isset($with[$relPath])) {
                     list($unallowed, $allowed) = Set::slice($with[$relPath], array('alias', 'constraints'));
                     if ($unallowed) {
                         $message = "Only `'alias'` and `'constraints'` are allowed in ";
                         $message .= "`'with'` using the `'joined'` strategy.";
                         throw new QueryException($message);
                     }
                     extract($with[$relPath]);
                 }
                 $to = $context->alias($alias, $relPath);
                 $deps[$to] = $deps[$from];
                 $deps[$to][] = $from;
                 if ($context->relationships($relPath) === null) {
                     $context->relationships($relPath, array('type' => $rel->type(), 'model' => $rel->to(), 'fieldName' => $rel->fieldName(), 'alias' => $to));
                     $self->join($context, $rel, $from, $to, $constraints);
                 }
                 if (!empty($childs)) {
                     $me($me, $rel->to(), $childs, $relPath, $to, $deps);
                 }
             }
         };
         $tree = Set::expand(Set::normalize(array_keys($with)));
         $alias = $context->alias();
         $deps = array($alias => array());
         $strategy($strategy, $model, $tree, '', $alias, $deps);
         $models = $context->models();
         foreach ($context->fields() as $field) {
             list($alias, $field) = $self->invokeMethod('_splitFieldname', array($field));
             $alias = $alias ?: $field;
             if ($alias && isset($models[$alias])) {
                 foreach ($deps[$alias] as $depAlias) {
                     $depModel = $models[$depAlias];
                     $context->fields(array($depAlias => (array) $depModel::meta('key')));
                 }
             }
         }
     }, 'nested' => function ($self, $model, $context) {
         throw new QueryException("This strategy is not yet implemented.");
     });
     parent::__construct($config + $defaults);
 }