/** * Sets a JSON REST API option. * * @param mixed $path * @param mixed $value */ public function setJraOption($path, $value) { if (!isset($this->jraOptions)) { $this->jraOptions = []; } $this->jraOptions = Hash::insert($this->jraOptions, $path, $value); }
/** * Used to store a dynamic variable in Configure. * * Usage: * {{{ * Configure::write('One.key1', 'value of the Configure::One[key1]'); * Configure::write(['One.key1' => 'value of the Configure::One[key1]']); * Configure::write('One', [ * 'key1' => 'value of the Configure::One[key1]', * 'key2' => 'value of the Configure::One[key2]' * ]); * * Configure::write([ * 'One.key1' => 'value of the Configure::One[key1]', * 'One.key2' => 'value of the Configure::One[key2]' * ]); * }}} * * @link http://book.cakephp.org/2.0/en/development/configuration.html#Configure::write * @param string|array $config The key to write, can be a dot notation value. * Alternatively can be an array containing key(s) and value(s). * @param mixed $value Value to set for var * @return bool True if write was successful */ public static function write($config, $value = null) { if (!is_array($config)) { $config = [$config => $value]; } foreach ($config as $name => $value) { static::$_values = Hash::insert(static::$_values, $name, $value); } if (isset($config['debug']) && function_exists('ini_set')) { if (static::$_values['debug']) { ini_set('display_errors', 1); } else { ini_set('display_errors', 0); } } return true; }
/** * Convert a nested array of files to arrays. * * @param array $data The data to add files to. * @param array $files The file objects to convert. * @param string $path The current array path. * @return array Converted file data */ protected static function convertFiles($data, $files, $path = '') { foreach ($files as $key => $file) { $newPath = $path; if ($newPath === '') { $newPath = $key; } if ($newPath !== $key) { $newPath .= '.' . $key; } if (is_array($file)) { $data = static::convertFiles($data, $file, $newPath); } else { $data = Hash::insert($data, $newPath, static::convertFile($file)); } } return $data; }
/** * Insert new action pattern according to Hash::insert rules * * @param string $path * @param array $values * @return array */ public function insert($path, $values = null) { $this->_tools = Hash::insert($this->_tools, $path, $values); return $this->_tools; }
/** * _store * * Stores recent data in the $_data-variable. * * @param string $key The key. * @param mixed $value The value. * @return void */ protected static function _store($key, $value = null) { if (!is_array($key)) { $key = [$key => $value]; } foreach ($key as $name => $value) { self::$_data = Hash::insert(self::$_data, $name, $value); } }
/** * Ensure data key is present in Controller:$viewVars * * @param \Crud\Event\Subject $subject Subject * @return void */ protected function _ensureData(Subject $subject) { $controller = $this->_controller(); $action = $this->_action(); if (method_exists($action, 'viewVar')) { $viewVar = $action->viewVar(); } else { $viewVar = 'data'; } if (isset($controller->viewVars[$viewVar])) { return; } $key = $subject->success ? 'success' : 'error'; $config = $action->config('api.' . $key); $data = []; if (isset($config['data']['subject'])) { $config['data']['subject'] = Hash::normalize((array) $config['data']['subject']); $subjectArray = (array) $subject; foreach ($config['data']['subject'] as $keyPath => $valuePath) { if ($valuePath === null) { $valuePath = $keyPath; } $keyPath = $this->_expandPath($subject, $keyPath); $valuePath = $this->_expandPath($subject, $valuePath); $data = Hash::insert($data, $keyPath, Hash::get($subjectArray, $valuePath)); } } if (isset($config['data']['entity'])) { $config['data']['entity'] = Hash::normalize((array) $config['data']['entity']); foreach ($config['data']['entity'] as $keyPath => $valuePath) { if ($valuePath === null) { $valuePath = $keyPath; } if (method_exists($subject->entity, $valuePath)) { $data = Hash::insert($data, $keyPath, call_user_func([$subject->entity, $valuePath])); } elseif (isset($subject->entity->{$valuePath})) { $data = Hash::insert($data, $keyPath, $subject->entity->{$valuePath}); } } } if (isset($config['data']['raw'])) { foreach ($config['data']['raw'] as $path => $value) { $path = $this->_expandPath($subject, $path); $data = Hash::insert($data, $path, $value); } } if (method_exists($action, 'viewVar')) { $viewVar = $action->viewVar(); } else { $viewVar = 'data'; } $controller->set($viewVar, $data); }
/** * _normalizeField * * Normalizes the requested field. * * ### Options * - save boolean if the normalized data should be saved in config * default set to true * * @param string $field Field to normalize. * @param array $options Options. * @return array */ protected function _normalizeField($field, $options = []) { $_options = ['save' => true]; $options = Hash::merge($_options, $options); $data = $this->config($field); if (is_null($data)) { foreach ($this->config() as $key => $config) { if ($config == $field) { if ($options['save']) { $this->config($field, []); $this->_configDelete($key); } $data = []; } } } // adding the default directory-field if not set if (is_null(Hash::get($data, 'fields.filePath'))) { $data = Hash::insert($data, 'fields.filePath', $field); } $data = Hash::merge($this->config('defaultFieldConfig'), $data); if ($options['save']) { $this->config($field, $data); } return $data; }
/** * Write a value to the response cookies. * * You must use this method before any output is sent to the browser. * Failure to do so will result in header already sent errors. * * @param string|array $key Key for the value * @param mixed $value Value * @return void * @link http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#CookieComponent::write */ public function write($key, $value = null) { if (!is_array($key)) { $key = array($key => $value); } $keys = []; foreach ($key as $name => $value) { $this->_load($name); $this->_values = Hash::insert($this->_values, $name, $value); $parts = explode('.', $name); $keys[] = $parts[0]; } foreach ($keys as $name) { $this->_write($name, $this->_values[$name]); } }
/** * setRole * * This method is used inside the action-method * to set a custom boolean to the selected role for the selected action * * ``` * $this->Authorizer->action(["My action"], function($auth) { * $auth->setRole(2, $this->customMethod()); * }); * ``` * * The role-variable can be an integer or array with integers. * * The value is an boolean. * * @param int|array $roles Array or integer with the roles to allow. * @param boole $value The value to set to the selected role(s). * @return void */ public function setRole($roles, $value) { if (!is_array($roles)) { $roles = [$roles]; } $controller = $this->_current['controller']; $action = $this->_selected['action']; $path = $controller . '.' . $action . '.roles.'; foreach ($roles as $role) { self::$_data = Hash::insert(self::$_data, $path . $role, $value); } }
/** * Writes value to given session variable name. * * @param string|array $name Name of variable * @param mixed $value Value to write * @return void */ public function write($name, $value = null) { if (!$this->started()) { $this->start(); } $write = $name; if (!is_array($name)) { $write = [$name => $value]; } $data = isset($_SESSION) ? $_SESSION : []; foreach ($write as $key => $val) { $data = Hash::insert($data, $key, $val); } $this->_overwrite($_SESSION, $data); }
/** * Provides a read/write accessor for `$this->data`. Allows you * to use a syntax similar to `Cake\Model\Datasource\Session` for reading post data. * * ## Reading values. * * `$request->data('Post.title');` * * When reading values you will get `null` for keys/values that do not exist. * * ## Writing values * * `$request->data('Post.title', 'New post!');` * * You can write to any value, even paths/keys that do not exist, and the arrays * will be created for you. * * @param string $name,... Dot separated name of the value to read/write * @return mixed Either the value being read, or this so you can chain consecutive writes. */ public function data($name) { $args = func_get_args(); if (count($args) === 2) { $this->data = Hash::insert($this->data, $name, $args[1]); return $this; } return Hash::get($this->data, $name); }
<?php use Cake\Utility\Hash; use josegonzalez\Dotenv\Loader; $config = []; if (!env('APP_NAME')) { $dotenv = new Loader([__DIR__ . DS . '.env', __DIR__ . DS . '.env.default']); $dotenv->setFilters(['josegonzalez\\Dotenv\\Filter\\LowercaseKeyFilter', 'josegonzalez\\Dotenv\\Filter\\UppercaseFirstKeyFilter', 'josegonzalez\\Dotenv\\Filter\\UnderscoreArrayFilter', function ($data) { $keys = ['Debug' => 'debug', 'Emailtransport' => 'EmailTransport', 'Database' => 'Datasources.default', 'Test.database' => 'Datasources.test', 'Test' => null, 'Cache.duration' => null, 'Cache.cakemodel' => 'Cache._cake_model_', 'Cache.cakecore' => 'Cache._cake_core_']; foreach ($keys as $key => $newKey) { if ($newKey === null) { $data = Hash::remove($data, $key); continue; } $value = Hash::get($data, $key); $data = Hash::remove($data, $key); $data = Hash::insert($data, $newKey, $value); } return $data; }]); $dotenv->parse(); $dotenv->filter(); $config = $dotenv->toArray(); } return $config;
/** * Import public function * * @param string $filename path to the file under webroot * @return array of all data from the csv file in [Model][field] format * @author Dean Sofer */ public function importCsv($content, $fields = array(), $options = array()) { $config = $this->config(); $options = array_merge($config, $options); if (!$this->_trigger('beforeImportCsv', array($content, $fields, $options))) { return false; } if ($options['text']) { // store the content to a file and reset $file = fopen("php://memory", "rw"); fwrite($file, $content); fseek($file, 0); } else { $file = fopen($content, 'r'); } // open the file if ($file) { $data = []; if (empty($fields)) { // read the 1st row as headings $fields = fgetcsv($file, $options['length'], $options['delimiter'], $options['enclosure']); foreach ($fields as $key => $field) { $field = trim($field); if (empty($field)) { continue; } $fields[$key] = strtolower($field); } } elseif ($options['headers']) { fgetcsv($file, $options['length'], $options['delimiter'], $options['enclosure']); } // Row counter $r = 0; // read each data row in the file $alias = $this->_table->alias(); while ($row = fgetcsv($file, $options['length'], $options['delimiter'], $options['enclosure'])) { // for each header field foreach ($fields as $f => $field) { if (!isset($row[$f])) { $row[$f] = null; } $row[$f] = trim($row[$f]); // get the data field from Model.field if (strpos($field, '.')) { $keys = explode('.', $field); if ($keys[0] == $alias) { $field = $keys[1]; } if (!isset($data[$r])) { $data[$r] = []; } $data[$r] = Hash::insert($data[$r], $field, $row[$f]); } else { $data[$r][$field] = $row[$f]; } } $r++; } // close the file fclose($file); $this->_trigger('afterImportCsv', array($data)); // return the messages return $data; } else { return false; } }
/** * Test that insert() can insert data over a string value. * * @return void */ public function testInsertOverwriteStringValue() { $data = array('Some' => array('string' => 'value')); $result = Hash::insert($data, 'Some.string.value', array('values')); $expected = array('Some' => array('string' => array('value' => array('values')))); $this->assertEquals($expected, $result); }
/** * Write a value to the $_COOKIE[$key]; * * Optional [Name.], required key, optional $value, optional $encrypt, optional $expires * $this->Cookie->write('[Name.]key, $value); * * By default all values are encrypted. * You must pass $encrypt false to store values in clear test * * You must use this method before any output is sent to the browser. * Failure to do so will result in header already sent errors. * * @param string|array $key Key for the value * @param mixed $value Value * @param bool $encrypt Set to true to encrypt value, false otherwise * @param int|string $expires Can be either the number of seconds until a cookie * expires, or a strtotime compatible time offset. * @return void * @link http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#CookieComponent::write */ public function write($key, $value = null, $encrypt = true, $expires = null) { $cookieName = $this->config('name'); if (empty($this->_values[$cookieName])) { $this->read(); } if ($encrypt === null) { $encrypt = true; } $this->_encrypted = $encrypt; $this->_expire($expires); if (!is_array($key)) { $key = array($key => $value); } foreach ($key as $name => $value) { $names = array($name); if (strpos($name, '.') !== false) { $names = explode('.', $name, 2); } $firstName = $names[0]; $isMultiValue = is_array($value) || count($names) > 1; if (!isset($this->_values[$cookieName][$firstName]) && $isMultiValue) { $this->_values[$cookieName][$firstName] = array(); } if (count($names) > 1) { $this->_values[$cookieName][$firstName] = Hash::insert($this->_values[$cookieName][$firstName], $names[1], $value); } else { $this->_values[$cookieName][$firstName] = $value; } $this->_write('[' . $firstName . ']', $this->_values[$cookieName][$firstName]); } $this->_encrypted = true; }
/** * parses nested values out of keys. * * @param array $values Values to be exploded. * @return array Array of values exploded */ protected function _parseNestedValues($values) { foreach ($values as $key => $value) { if ($value === '1') { $value = true; } if ($value === '') { $value = false; } unset($values[$key]); if (strpos($key, '.') !== false) { $values = Hash::insert($values, $key, $value); } else { $values[$key] = $value; } } return $values; }
/** * Returns the extracted parameters from a parameters string. * * @param string $params The parameters string * @return array */ protected function formatParams($params) { //Clean parameters $params = preg_replace('/(\'[^\']+\')::[^ ,\\]]+/', '\\1', $params); if (preg_match('/^ARRAY\\[(.*)\\]$/', $params, $arrayParams)) { $params = [preg_split('/, /', $arrayParams[1], null, PREG_SPLIT_NO_EMPTY)]; } else { $params = preg_split('/, /', $params, null, PREG_SPLIT_NO_EMPTY); } //Trim quotes around values foreach (Hash::flatten($params) as $path => $value) { $params = Hash::insert($params, $path, preg_replace('/^\'(.*)\'$/', '\\1', $value)); } return $params; }
/** * Extract from the request the given field and return it. * * @param string $field name of the field to be extracted from the upload(s). * @return array|false */ protected function _uploadArrayPer($field = '') { if (empty($field)) { $field = $this->_upField; } $data = $this->request->data; $uploadArray = Hash::get($data, 'UploadDocuments.file.' . $field); $data = Hash::remove($data, 'UploadDocuments.file' . $field); if (empty($uploadArray)) { return false; } $data = Hash::insert($data, 'UploadDocuments.file', $uploadArray); return $data; }
/** * Add a menu item. * * @param $menu * @param $path * @param array $options */ public static function add($menu, $path, $options = []) { // Juggle argument for backward compatibility if (is_array($path)) { $options = $path; $path = $menu; $menu = self::activeMenu(); } else { self::activeMenu($menu); } $pathE = explode('.', $path); $pathE = array_splice($pathE, 0, count($pathE) - 2); $parent = join('.', $pathE); if (!empty($parent) && !Hash::check(self::$_items[$menu], $parent)) { $title = Inflector::humanize(end($pathE)); $opt = ['title' => $title]; self::_setupOptions($opt); self::add($parent, $opt); } self::_setupOptions($options); $current = Hash::extract(self::$_items[$menu], $path); if (!empty($current)) { self::_replace(self::$_items[$menu], $path, $options); } else { self::$_items[$menu] = Hash::insert(self::$_items[$menu], $path, $options); } }
/** * Safely access the values in $this->params. * * @param string $name The name of the parameter to get. * @return mixed The value of the provided parameter. Will * return false if the parameter doesn't exist or is falsey. */ public function param($name) { $args = func_get_args(); if (count($args) === 2) { $this->params = Hash::insert($this->params, $name, $args[1]); return $this; } if (!isset($this->params[$name])) { return Hash::get($this->params, $name, false); } return $this->params[$name]; }
/** * Writes value to given session variable name. * * @param string|array $name Name of variable * @param string $value Value to write * @return bool True if the write was successful, false if the write failed */ public function write($name, $value = null) { if (empty($name)) { return; } if (!$this->started()) { $this->start(); } $write = $name; if (!is_array($name)) { $write = array($name => $value); } $data = $_SESSION ?: []; foreach ($write as $key => $val) { $data = Hash::insert($data, $key, $val); } $this->_overwrite($_SESSION, $data); }
/** * Test that insert() can insert data over a string value. * * @return void */ public function testInsertOverwriteStringValue() { $data = ['Some' => ['string' => 'value']]; $result = Hash::insert($data, 'Some.string.value', ['values']); $expected = ['Some' => ['string' => ['value' => ['values']]]]; $this->assertEquals($expected, $result); }
/** * Writes value to given session variable name. * * @param string|array $name Name of variable * @param string $value Value to write * @return bool True if the write was successful, false if the write failed */ public static function write($name, $value = null) { if (empty($name) || !static::start()) { return false; } $write = $name; if (!is_array($name)) { $write = array($name => $value); } foreach ($write as $key => $val) { static::_overwrite($_SESSION, Hash::insert($_SESSION, $key, $val)); if (Hash::get($_SESSION, $key) !== $val) { return false; } } return true; }