/** * Ctor * * @param array|\Traversable|null $options * @throws Exception\DomainException */ public function __construct($options = null) { if (!ArrayUtils::isHashTable($this->config, false)) { throw new Exception\DomainException(sprintf('"%s" expects that options map configuration property is an hash table', __METHOD__)); } parent::__construct($options); }
/** * Set the data * @param array $data [description] */ public function setData(array $data) { if (ArrayUtils::isHashTable($data)) { $data = array($data); } $this->data = $data; }
/** * Build component * * @param array|string $component * @return array */ protected function buildComponent($component) { $componentManager = $this->componentManager; $transformObj = function ($item) use($componentManager) { if (ArrayUtils::isHashTable($item) && isset($item['cmp'])) { $itemObj = $componentManager->get($item['cmp']); $itemObj->setProperties($item); unset($itemObj['cmp'], $itemObj['extend']); $item = $itemObj; } return $item; }; // Recursive mapping, convert to class later $map = function ($func, $arr) use(&$map, $transformObj) { $result = array(); if (ArrayUtils::isHashTable($arr)) { foreach ($arr as $k => $v) { $result[$k] = $map($func, $v); } $result = $transformObj($result); } elseif (ArrayUtils::isList($arr)) { foreach ($arr as $b) { $result[] = $transformObj($b); } } elseif (is_string($arr)) { $result = $arr; } return $result; }; return $map(function ($item) { return $item; }, $component); }
/** * Get real path for view path configs * @param array $configViewPaths * @return array * @throws Exception\InvalidArgumentException * @throws Exception\RuntimeException */ protected function filterViewPath($configViewPaths) { if (!ArrayUtils::isHashTable($configViewPaths)) { throw new Exception\InvalidArgumentException('Config view path is not valid'); } foreach ($configViewPaths as $moduleName => $viewPath) { $viewPath = realpath($viewPath); if (!$viewPath) { $errMsg = sprintf('Config view path for "%s" module is invalid', $moduleName); throw new Exception\RuntimeException($errMsg); } $configViewPaths[$moduleName] = $viewPath; } return $configViewPaths; }
public function init() { $this->add(['name' => 'adapter_name', 'required' => true, 'allow_empty' => false, 'error_message' => 'Please provide a unique, non-empty name for your database connection']); $this->add(['name' => 'database', 'required' => true, 'allow_empty' => false, 'error_message' => 'Please provide the database name; for SQLite, this will be a filesystem path']); $this->add(['name' => 'driver', 'error_message' => 'Please provide a Database Adapter driver name available to Zend Framework']); $this->add(['name' => 'dsn', 'required' => false, 'allow_empty' => true]); $this->add(['name' => 'username', 'required' => false, 'allow_empty' => true]); $this->add(['name' => 'password', 'required' => false, 'allow_empty' => true]); $this->add(['name' => 'hostname', 'required' => false, 'allow_empty' => true]); $this->add(['name' => 'port', 'required' => false, 'allow_empty' => true, 'validators' => [['name' => 'Digits']], 'error_message' => 'Please provide a valid port for accessing the database; must be an integer']); $this->add(['name' => 'charset', 'required' => false, 'allow_empty' => true]); $this->add(['name' => 'driver_options', 'required' => false, 'allow_empty' => true, 'validators' => [new CallbackValidator(function ($value) { return ArrayUtils::isHashTable($value); })], 'error_message' => 'Driver options must be provided as a set of key/value pairs']); }
/** * Auto register namespace and class map * @throws Exception\RuntimeException * @todo Should cache register classmap */ public function register() { $moduleHandler = $this->diFactory->get('moduleHandler'); $autoloadConf = $moduleHandler->getModulesAutoloadConfig(); if (isset($autoloadConf['namespaces'])) { if (!ArrayUtils::isHashTable($autoloadConf['namespaces'])) { throw new Exception\RuntimeException('Config autoload for namespace is invalid'); } $this->loader->registerNamespaces($autoloadConf['namespaces']); } if (isset($autoloadConf['classmap'])) { $this->registerClassMap($autoloadConf['classmap']); } $this->loader->register(); return $this; }
/** * Create or update settings in collection * * @param array $data * * @return JsonModel|ApiProblemResponse */ public function create($data) { if (!ArrayUtils::isHashTable($data)) { return new ApiProblemResponse(new ApiProblem(400, 'Data should be array of key => value pairs.')); } try { foreach ($data as $key => $value) { if ($this->settings->isValid($key, $value)) { continue; } return new ApiProblemResponse(new ApiProblem(400, 'Invalid parameters provided.')); } } catch (SettingDoesNotExistException $exception) { return new ApiProblemResponse(new ApiProblem(404, $exception->getMessage())); } foreach ($data as $key => $value) { $this->settings->setValue($key, $value); } return new JsonModel($data); }
/** * @return bool */ public function isHashTable() { return ArrayUtils::isHashTable($this->data()); }
/** * Does the request represent a collection? * * @param string $serviceName * @param array $data * @param RouteMatch $matches * @param HttpRequest $request * @return bool */ protected function isCollection($serviceName, $data, RouteMatch $matches, HttpRequest $request) { if (!array_key_exists($serviceName, $this->restControllers)) { return false; } if ($request->isPost() && (empty($data) || ArrayUtils::isHashTable($data))) { return false; } $identifierName = $this->restControllers[$serviceName]; if ($matches->getParam($identifierName)) { return false; } return null === $request->getQuery($identifierName, null); }
/** * @param string|array $value a field value or an array of field values if more fields have been configured to be * matched * @return array * @throws \Zend\Validator\Exception\RuntimeException */ protected function cleanSearchValue($value) { $value = is_object($value) ? array($value) : (array) $value; if (ArrayUtils::isHashTable($value)) { $matchedFieldsValues = array(); foreach ($this->fields as $field) { if (!array_key_exists($field, $value)) { throw new Exception\RuntimeException(sprintf('Field "%s" was not provided, but was expected since the configured field lists needs' . ' it for validation', $field)); } $matchedFieldsValues[$field] = $value[$field]; } } else { $matchedFieldsValues = @array_combine($this->fields, $value); if (false === $matchedFieldsValues) { throw new Exception\RuntimeException(sprintf('Provided values count is %s, while expected number of fields to be matched is %s', count($value), count($this->fields))); } } return $matchedFieldsValues; }
/** * Normalizes the listener configuration. * * Converts the options given in the main config file to an array * containing key => value pairs for easier consumption in * {@link attachListeners()} * * @param int|string $name Service or class name of the listener. (if int, we have config for an aggregate) * @param string|array $options String is either event name or aggregate name (when name is int). * Array are the options from config. [ [event,..], method, priority, lazy] * * @return array */ protected function normalizeListenerOptions($name, $options) { /* * $options is an array with following meta-syntax: * * $options = [ * string:listener => string:event, * string:listener => [ string|array:event{, string:methodName}{, int:priority}{, bool:lazy }], * string:aggregate, // implies integer value as $name * string:aggregate => int:priority, * string:listener => [ * 'events' => [ 'event', 'event' => priority, 'event' => 'method', * 'event' => [ 'method' => method, 'priority' => priority ], * 'event' => [ 'method' => [ 'method', 'method' => priority ], 'priority' => priority ] * ], * 'method' => method, * 'priority' => priority, * 'lazy' => bool * ] */ $normalized = ['service' => $name, 'attach' => null, 'priority' => 0, 'lazy' => false]; if (is_int($name)) { /* $options must be the name of an aggregate service or class. */ $normalized['service'] = $options; return $normalized; } if (is_int($options)) { /* $name must be the name of an aggregate and the priority is passed. */ $normalized['priority'] = $options; return $normalized; } if (is_string($options)) { /* Only an event name is provided in config */ $normalized['attach'] = [['events' => [$options], 'method' => null, 'priority' => 0]]; return $normalized; } if (ArrayUtils::isHashTable($options)) { $normalized['attach'] = $this->normalizeEventsSpec($options); if (isset($options['lazy'])) { $normalized['lazy'] = $options['lazy']; } return $normalized; } $event = $method = null; $priority = 0; $lazy = false; foreach ($options as $opt) { if (is_array($opt)) { /* Must be event names */ $event = $opt; } else { if (is_string($opt)) { if (null === $event) { /* first string found is assumed to be the event name */ $event = [$opt]; } else { /* second string found must be a method name. */ $method = $opt; } } else { if (is_int($opt)) { /* Integer values must be priority */ $priority = $opt; } else { if (is_bool($opt)) { /* Lazy option is passed. */ $lazy = $opt; } } } } } $normalized['attach'] = [['events' => $event, 'method' => $method, 'priority' => $priority]]; $normalized['lazy'] = $lazy; return $normalized; }
/** * Get autoload config in each module without cache * @return array * @throws Exception\RuntimeException */ protected function getModulesAutoloadConfigWithoutCache() { $result = []; foreach ($this->modules as $moduleName => $moduleConfig) { $className = $moduleConfig['className']; $module = new $className(); if (!$module instanceof AbstractModule) { $errMsg = sprintf('Class "%s" must be extended from %s', $className, AbstractModule::class); throw new Exception\RuntimeException($errMsg); } $autoloadConfig = $module->getAutoloaderConfig(); if (!ArrayUtils::isHashTable($autoloadConfig)) { $errMsg = sprintf('The autoloader configuration for module "%s" is invalid', $moduleName); throw new Exception\RuntimeException($errMsg); } $result = ArrayUtils::merge($result, $autoloadConfig); } foreach ($result as $moduleName => $configAutoload) { foreach ($configAutoload as $key => $value) { $result[$moduleName][$key] = realpath($value); } } return $result; }
/** * Merges the content of the $params array with the * parameters already registered. * * @param array $params */ public function setParams($params) { if (empty($params)) { return; } if (!ArrayUtils::isHashTable($params)) { throw new \InvalidArgumentException('Only hash tables (key-value pairs) are accepted as params.'); } $this->params->merge(new Config($params)); return $this; }
/** * Retrieve the RPCS from the request * * @return array */ protected function getRPC() { if (null == $this->rpcs) { $request = $this->getRequest(); if ($this->isForm()) { $post = $this->params()->fromPost(); $rpc = array('action' => $post['extAction'], 'method' => $post['extMethod'], 'tid' => $post['extTID'], 'module' => $post['extModule'], 'data' => ArrayUtils::merge($post, $this->params()->fromFiles())); $this->rpcs = RPC::factory($rpc); } else { $rpcs = array(); if ($request->getContent()) { $rpcs = json_decode($GLOBALS['HTTP_RAW_POST_DATA'], true); } elseif ($this->params()->fromQuery('callback')) { $rpcs = json_decode($this->params()->fromQuery('data'), true); } // TODO valid json check // Convert assoc array to array if (ArrayUtils::isHashTable($rpcs)) { $rpcs = array($rpcs); } $this->rpcs = array(); foreach ($rpcs as $rpc) { $this->rpcs[] = RPC::factory($rpc); } } } return $this->rpcs; }
/** * Replace a nested key * * First invocation should pass a dot-separated string representing a * nested key. * * This value will be exploded to a list of keys, and the first element of * the list will be compared against the provided configuration array; the * method will recurse as necessary in order to replace the key. * * @param string|array $keys * @param mixed $value * @param array $config * @return array */ public function replaceKey($keys, $value, array $config) { if (!is_array($keys)) { $keys = explode('.', $keys); } $key = array_shift($keys); $haveKeys = count($keys) > 0 ? true : false; // If no more keys, overwrite and return if (!$haveKeys) { $config[$key] = $value; return $config; } // If key does not exist, or the current value is not an associative // array, create nested set and return if (!isset($config[$key]) || !ArrayUtils::isHashTable($config[$key])) { $config[$key] = $this->replaceKey($keys, $value, []); return $config; } // Otherwise, recurse through it $config[$key] = $this->replaceKey($keys, $value, $config[$key]); return $config; }
public function testEmptyArrayReturnsFalse() { $test = array(); $this->assertFalse(ArrayUtils::hasStringKeys($test, false)); $this->assertFalse(ArrayUtils::hasIntegerKeys($test, false)); $this->assertFalse(ArrayUtils::hasNumericKeys($test, false)); $this->assertFalse(ArrayUtils::isList($test, false)); $this->assertFalse(ArrayUtils::isHashTable($test, false)); }
/** * Save a structure * * @param array|\User\Model\User\Settings\Structure $structure * @return int */ public function save(&$structure) { if ($structure instanceof Structure) { $userId = $structure->userId; $section = $structure->section; $settings = $structure->settings; } else { $data = (array) $structure; if (ArrayUtils::isHashTable($data)) { $userId = $data['userId']; $section = $data['section']; $settings = $data['settings']; } else { list($userId, $section, $settings) = $data; } } $rows = 0; $savedKeys = array(); $sql = $this->sql(); foreach ($settings as $key => $value) { $update = $sql->update()->set(array('value' => $value))->where(array('userId' => $userId, 'section' => $section, 'key' => $key)); $affected = $this->sql()->prepareStatementForSqlObject($update)->execute()->getAffectedRows(); if ($affected) { $rows += $affected; } else { $insert = $sql->insert()->values(array('userId' => $userId, 'section' => $section, 'key' => $key, 'value' => $value)); $rows += $this->sql()->prepareStatementForSqlObject($insert)->execute()->getAffectedRows(); } $savedKeys[] = $key; } $deleteWhere = array('userId' => $userId, 'section' => $section); if (!empty($savedKeys)) { $deleteWhere[] = new NotIn('key', $savedKeys); } $delete = $this->sql()->delete()->where($deleteWhere); $rows += $this->sql()->prepareStatementForSqlObject($delete)->execute()->getAffectedRows(); return $rows; }