protected function remainder(Validate $validate, $input) { $input = ArrayHelper::diffByKeys($input, array_keys($this->attributes)); $config = ['remainder' => $this->remainder, 'attributes' => $validate]; Instance::configure($this, $config); $this->validate($input); }
/** * Unserialize. * * @param string $value serialized array * @param array $params params: * * - key * - separator * * @return string */ public static function unserialize($value, array $params) { if (empty($value)) { return null; } if (!empty($params['key'])) { return ArrayHelper::getValue(Serialize::unserialize($value, false), explode(Helper::getValue($params['separator'], '.'), $params['key'])); } return Serialize::unserialize($value, false); }
protected function getCompare() { if (isset($this->compare)) { return $this->compare; } if ($globals = $this->getGlobalsVars()) { if ($global = ArrayHelper::searchByKey($this->csrf->csrfParam, $globals)) { return current($global); } } return $this->compare; }
protected function chain(Sanitize $sanitize, $input, $attribute) { $callback = function ($value) use($sanitize, $attribute) { if (is_array($value)) { if (!$this->recursive) { return $value; } $this->attributes = is_array($this->attributes) && isset($this->attributes[$attribute]) ? $this->attributes[$attribute] : $this->attributes; return $this->sanitize($value); } return $sanitize->sanitize($value); }; return ArrayHelper::updateValue($input, explode('.', $attribute), $callback); }
/** * Draws a text string on an existing image. * * @param string $filename the image file path or path alias. * @param string $text the text to write to the image * @param string $fontFile the file path or path alias * @param array $start the starting position of the text. This must be an array with two elements representing `x` and `y` coordinates. * @param array $fontOptions the font options. The following options may be specified: * * - color: The font color. Defaults to "fff". * - size: The font size. Defaults to 12. * - angle: The angle to use to write the text. Defaults to 0. * * @return ImageInterface * @throws \Exception if `$fontOptions` is invalid */ public static function text($filename, $text, $fontFile, array $start = [0, 0], array $fontOptions = []) { if (!isset($start[0], $start[1])) { throw new ImagineException('$start must be an array of two elements.'); } $fontSize = ArrayHelper::getValue($fontOptions, ['size'], 12); $fontColor = ArrayHelper::getValue($fontOptions, ['color'], 'fff'); $fontAngle = ArrayHelper::getValue($fontOptions, ['angle'], 0); $img = static::getImagine()->open(Alias::getAlias($filename)); $font = static::getImagine()->font(Alias::getAlias($fontFile), $fontSize, (new RGB())->color($fontColor)); $img->draw()->text($text, $font, new Point($start[0], $start[1]), $fontAngle); return $img; }
use rock\security\Security; use rock\template\Template; return array_merge(['route' => ['class' => \rock\route\Route::className()], 'access' => ['class' => \rock\access\Access::className()], 'behavior' => ['class' => \rock\components\Behavior::className()], 'db' => ['class' => \rock\db\Connection::className(), 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', 'dsn' => 'mysql:host=localhost;dbname=rockdemo;charset=utf8', 'tablePrefix' => 'spt_', 'aliasSeparator' => '__'], 'BatchQueryResult' => ['class' => BatchQueryResult::className()], 'template' => ['class' => Template::className(), 'locale' => [\rock\LocaleProperties::className(), 'locale'], 'autoEscape' => Template::ESCAPE | Template::TO_TYPE, 'handlerLink' => function ($link, Template $template, array $params = []) { if (!($link = Alias::getAlias("@{$link}", [], false))) { return '#'; } return $template->autoEscape(\rock\template\filters\BaseFilter::modifyUrl($link, $params)); }, 'extensions' => ['cfg' => function (array $keys) { return \rock\helpers\ArrayHelper::getValue(Rock::$config, $keys); }, 'user' => function (array $keys) { if (current($keys) === 'isGuest') { return Rock::$app->user->isGuest(); } elseif (in_array(current($keys), ['isLogged', 'isAuthenticated'], true)) { return !Rock::$app->user->isGuest(); } return \rock\helpers\ArrayHelper::getValue(Rock::$app->user->getAll(), $keys); }, 'call' => function (array $call, array $params = [], Template $template) { if (!isset($call[1])) { $call[1] = null; } list($class, $method) = $call; if ($class === 'context') { $object = $template->context; $function = [$object, $method]; } elseif (function_exists($class) && !$class instanceof \Closure) { return call_user_func_array($class, $params); } else { $object = \rock\di\Container::load($class); if (!method_exists($object, $method)) { throw new \rock\base\BaseException(\rock\base\BaseException::UNKNOWN_METHOD, ['method' => "{$class}::{$method}"]); }
\rock\base\Alias::setAlias('root', dirname(dirname(dirname(__DIR__)))); \rock\base\Alias::setAlias('rock', \rock\Rock::$dir); \rock\base\Alias::setAlias('vendor', '@root/vendor'); \rock\base\Alias::setAlias('assets', '@root/public/assets'); \rock\base\Alias::setAlias('web', '/assets'); \rock\base\Alias::setAlias('web.img', '/assets/images'); \rock\base\Alias::setAlias('app', '@root/apps'); \rock\base\Alias::setAlias('common', '@app/common'); \rock\base\Alias::setAlias('frontend', '@app/frontend'); \rock\base\Alias::setAlias('backend', '@app/backend'); \rock\base\Alias::setAlias('admin', '@backend'); // namespaces \rock\base\Alias::setAlias('common.ns', 'apps\\common'); \rock\base\Alias::setAlias('frontend.ns', 'apps\\frontend'); \rock\base\Alias::setAlias('backend.ns', 'apps\\backend'); \rock\base\Alias::setAlias('ns', '@common.ns'); // runtime \rock\base\Alias::setAlias('common.runtime', '@common/runtime'); // views \rock\base\Alias::setAlias('common.views', '@common/views'); \rock\base\Alias::setAlias('frontend.views', '@frontend/views'); // media \rock\base\Alias::setAlias('img', '@assets/images'); \rock\base\Alias::setAlias('images', '@img'); // links $request = new \rock\request\Request(); \rock\base\Alias::setAlias('link.home', $request->getHostInfo() ?: 'localhost'); \rock\base\Alias::setAlias('link.ajax', '@link.home/ajax'); \rock\base\Alias::setAlias('email', 'support@' . ($request->getHost() ?: 'localhost')); $config = \rock\helpers\ArrayHelper::merge(require \rock\base\Alias::getAlias('@rock/classes.php'), require __DIR__ . '/classes.php', require __DIR__ . '/controllers.php'); return ['components' => $config];
/** * Converts an object or an array of objects into an array. * * @param object|array $object the object to be converted into an array * @param array $properties a mapping from object class names to the properties that need to put into the resulting arrays. * The properties specified for each class is an array of the following format: * * ```php * [ * 'apps\models\Post' => [ * 'id', * 'title', * // the key name in array result => property name * 'createTime' => 'created_at', * // the key name in array result => anonymous function * 'length' => function ($post) { * return strlen($post->content); * }, * ], * ] * ``` * * The result of `Model::convert($post, $properties)` could be like the following: * * ```php * [ * 'id' => 123, * 'title' => 'test', * 'createTime' => '2013-01-01 12:00AM', * 'length' => 301, * ] * ``` * * @param boolean $recursive whether to recursively converts properties which are objects into arrays. * @return array the array representation of the object */ public static function convert($object, $properties = [], $recursive = true) { if (is_array($object)) { if ($recursive) { foreach ($object as $key => $value) { if (is_array($value) || is_object($value)) { $object[$key] = static::convert($value, $properties, true); } } } return $object; } elseif (is_object($object)) { if (!empty($properties)) { $className = get_class($object); if (!empty($properties[$className])) { $result = []; foreach ($properties[$className] as $key => $name) { if (is_int($key)) { $result[$name] = $object->{$name}; } else { $result[$key] = ArrayHelper::getValue($object, $name); } } return $recursive ? static::convert($result) : $result; } } if ($object instanceof Arrayable) { $result = $object->toArray(); } else { $result = []; foreach ($object as $key => $value) { $result[$key] = $value; } } return $recursive ? static::convert($result) : $result; } else { return [$object]; } }
/** * @inheritdoc */ public function getAll(array $only = [], array $exclude = []) { if (!$this->getIsActive()) { return null; } return ArrayHelper::only($this->storage->get($this->container), $only, $exclude); }
protected function load() { //@TODO cache if (!($dataItems = (new Query())->from($this->itemsTable)->orderBy(['order_index' => SORT_DESC])->indexBy('name')->all($this->connection))) { throw new RBACException('Items is empty.'); } static::$items = $dataItems; $alias = Query::alias($this->rolesTable, $this->rolesTable); //@TODO cache if (!($dataRolesItems = (new Query())->select(SelectBuilder::selects([['roles' => ['name', 'type', 'description', 'data']], ['access_items' => ['name', 'type', 'description', 'data'], 'items']]))->from($this->rolesItemsTable)->innerJoin($this->itemsTable, "{$this->rolesItemsTable}.item = {$this->itemsTable}.name")->innerJoin($this->rolesTable, "{$this->rolesItemsTable}.role = {$alias}.name")->andWhere(["{$alias}.[[type]]" => RBACInterface::TYPE_ROLE])->orderBy(["{$alias}.[[order_index]]" => SORT_DESC])->asSubattributes()->all($this->connection))) { return; } $result = []; foreach ($dataRolesItems as $value) { if (isset($result[$value['name']])) { $result[$value['name']]['items'] = array_merge($result[$value['name']]['items'], (array) $value['items']['name']); continue; } $value['items'] = [$value['items']['name']]; $result[$value['name']] = $value; } static::$items = ArrayHelper::toType(ArrayHelper::filterRecursive($result + static::$items, function ($value, $key) { return !in_array($key, ['name'], true); })); }
protected function errorsToPlaceholders(Model $model) { $errors = ArrayHelper::only($model->getErrors(), [], $model->safeAttributes()); $this->template->addMultiPlaceholders($errors); }
/** * @inheritdoc */ public static function populateRecord($record, $row, ConnectionInterface $connection = null) { if (!isset($connection)) { $connection = static::getConnection(); } if ($connection->typeCast) { $columns = static::getTableSchema($connection)->columns; foreach ($row as $name => $value) { if (isset($columns[$name])) { $row[$name] = $columns[$name]->phpTypecast($value); } elseif (is_array($value)) { $row[$name] = ArrayHelper::toType($value); } } } parent::populateRecord($record, $row); }
/** * Serializes a set of models. * @param array $models * @return array the array representation of the models */ protected function serializeModels(array $models) { list($fields, $expand) = $this->getRequestedFields(); foreach ($models as $i => $model) { if ($model instanceof Arrayable) { $models[$i] = $model->toArray($fields, $expand); } elseif (is_array($model)) { $models[$i] = ArrayHelper::toArray($model); } } return $models; }
protected function rawPostInternal($name = null, $default = null) { $params = $this->getBodyParams(); if (!isset($name)) { return $params; } return ArrayHelper::getValue($params, $name, $default); }
<?php // Config scope "frontend" $config = (require dirname(dirname(__DIR__)) . '/common/configs/configs.php'); \rock\base\Alias::setAlias('scope', '@frontend'); \rock\base\Alias::setAlias('views', '@frontend/views'); \rock\base\Alias::setAlias('runtime', '@frontend/runtime'); \rock\base\Alias::setAlias('ns', '@frontend.ns'); $request = new \rock\request\Request(); \rock\base\Alias::setAlias('link.home', $request->getHostInfo()); \rock\base\Alias::setAlias('link.ajax', '@link.home/ajax'); \rock\base\Alias::setAlias('email', 'support@' . $request->getHost()); $config['components'] = \rock\helpers\ArrayHelper::merge($config['components'], require __DIR__ . '/classes.php', require __DIR__ . '/models.php', require __DIR__ . '/controllers.php'); return $config;
/** * Renders the option tags. * * That can be used by {@see \rock\template\Html::dropDownList()} and {@see \rock\template\Html::listBox()}. * * @param string|array $selection the selected value(s). This can be either a string for single selection * or an array for multiple selections. * @param array $items the option data items. The array keys are option values, and the array values * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too). * For each sub-array, an option group will be generated whose label is the key associated with the sub-array. * If you have a list of data models, you may convert them into the format described above using {@see \rock\helpers\ArrayHelper::map()}. * * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in * the labels will also be HTML-encoded. * @param array $tagOptions the $options parameter that * is passed to the {@see \rock\template\Html::dropDownList()} or {@see \rock\template\Html::listBox()} call. * This method will take out these elements, if any: "prompt", "options" and "groups". See more details * in {@see \rock\template\Html::dropDownList()} for the explanation of these elements. * * @return string the generated list options */ public static function renderSelectOptions($selection, $items, &$tagOptions = []) { $lines = []; $encodeSpaces = static::remove($tagOptions, 'encodeSpaces', false); if (isset($tagOptions['prompt'])) { $prompt = $encodeSpaces ? str_replace(' ', ' ', static::encode($tagOptions['prompt'])) : static::encode($tagOptions['prompt']); $lines[] = static::tag('option', $prompt, ['value' => '']); } $options = isset($tagOptions['options']) ? $tagOptions['options'] : []; $groups = isset($tagOptions['groups']) ? $tagOptions['groups'] : []; unset($tagOptions['prompt'], $tagOptions['options'], $tagOptions['groups']); $options['encodeSpaces'] = ArrayHelper::getValue($options, 'encodeSpaces', $encodeSpaces); foreach ($items as $key => $value) { if (is_array($value)) { $groupAttrs = isset($groups[$key]) ? $groups[$key] : []; $groupAttrs['label'] = $key; $attrs = ['options' => $options, 'groups' => $groups, 'encodeSpaces' => $encodeSpaces]; $content = static::renderSelectOptions($selection, $value, $attrs); $lines[] = static::tag('optgroup', "\n" . $content . "\n", $groupAttrs); } else { $attrs = isset($options[$key]) ? $options[$key] : []; $attrs['value'] = (string) $key; $attrs['selected'] = $selection !== null && (!is_array($selection) && !strcmp($key, $selection) || is_array($selection) && in_array($key, $selection)); $lines[] = static::tag('option', $encodeSpaces ? str_replace(' ', ' ', static::encode($value)) : static::encode($value), $attrs); } } return implode("\n", $lines); }
protected function normalizeRules(array &$result = [], array &$aliases = [], array $rules, array $params = [], array $group = []) { foreach ($rules as $alias => $rule) { if ($rule[0] === self::REST) { $this->normalizeRules($result, $aliases, ArrayHelper::only($this->RESTHandlers, Helper::getValue($rule['only'], []), Helper::getValue($rule['exclude'], [])), ['prefix' => $alias, 'replace' => $rule[1], 'controller' => $rule[2], 'filters' => isset($rule['filters']) ? $rule['filters'] : null], $group); continue; } list(, $pattern) = $rule; if (is_string($alias)) { if (isset($params['replace'])) { if (isset($params['prefix']) && !is_string($params['prefix'])) { $params['prefix'] = $params['replace']; } $alias = "{$params['prefix']}.{$alias}"; } if (isset($group['as'])) { $alias = "{$group['as']}.{$alias}"; } } $result[$alias] = $rule; if (isset($params['controller'])) { $result[$alias]['params']['controller'] = $params['controller']; } if (isset($params['filters']) && !isset($result[$alias][3])) { $result[$alias]['filters'] = $params['filters']; } if (!is_array($pattern)) { $value = $pattern; $pattern = []; $pattern[self::FILTER_PATH] = $value; } if (isset($pattern[self::FILTER_PATH])) { if (isset($params['replace'])) { $pattern[self::FILTER_PATH] = is_array($params['replace']) ? strtr($pattern[self::FILTER_PATH], $params['replace']) : str_replace('{url}', $params['replace'], $pattern[self::FILTER_PATH]); } if (isset($group[self::FILTER_PATH])) { $pattern[self::FILTER_PATH] = rtrim($group[self::FILTER_PATH], '/') . '/' . ltrim($pattern[self::FILTER_PATH], '/'); } } foreach ($pattern as $key => &$data) { if (is_array($data)) { foreach ($data as $k => $value) { if (is_string($value)) { $data[$k] = $this->parse($value, '.+'); } } continue; } $data = $key != self::FILTER_PATH ? $this->parse($data, '.+') : $this->parse($data); } $result[$alias][1] = $pattern; if (is_string($alias)) { $build = $this->buildAlias($pattern, $params, $group); $placeholders = ['self_path' => $this->request->getUrlWithoutArgs(), 'self_scheme' => $this->request->getScheme()]; foreach ($this->request->rawGet() ?: [] as $name => $placeholder) { $placeholders["self_query_{$name}"] = $placeholder; } Alias::setAlias(str_replace('/', '.', $alias), StringHelper::replace($build, $placeholders, false), false); $aliases[$alias] = $build; } } }
protected function processing($row, array $fields, $value) { if (is_array($row)) { $callback = function () use($value) { return $value; }; return ArrayHelper::updateValue($row, $fields, $callback, false); } $r = $row; foreach ($fields as $field) { if (!isset($r->{$field})) { break; } if (is_string($r->{$field})) { $r->{$field} = $value; break; } $r = $r->{$field}; } return $row; }
/** * @inheritdoc */ public function remove($keys) { $_SESSION = ArrayHelper::removeValue($_SESSION, $keys); }
protected function isREST($url, $controller, $filters) { $handlers = ArrayHelper::only($this->RESTHandlers, Helper::getValue($filters['only'], []), Helper::getValue($filters['exclude'], [])); foreach ($handlers as $value) { if (!isset($value[3])) { $value[3] = null; } list($verbs, $pattern, $handler, $_filters) = $value; $filters = !empty($filters['filters']) ? $filters['filters'] : $_filters; if (StringHelper::isRegexp($pattern)) { $url = preg_quote($url, '/'); $pattern = "~{$pattern}"; } $pattern = str_replace('{url}', $url, $pattern); $this->params['controller'] = $controller; if ($this->isRoute($verbs, $pattern, $handler, $filters)) { $this->errors = 0; return true; } else { $this->errors |= $this->errors; } } return false; }
protected function translateInternal($keys, array $placeholders = []) { if (!isset(static::$data[$this->locale][$this->category])) { static::$data[$this->locale][$this->category] = []; } $result = ArrayHelper::getValue(static::$data[$this->locale][$this->category], $keys); if (!isset($result)) { if ($this->throwException) { $keys = is_array($keys) ? implode('][', $keys) : $keys; throw new i18nException(i18nException::UNKNOWN_I18N, ['name' => "{$this->category}[{$keys}]"]); } return null; } return StringHelper::replace($result, $placeholders, $this->removeBraces); }
/** * Adding pagination. * * @return void */ protected function calculatePagination() { if (empty($this->pagination['array']) && empty($this->pagination['call'])) { return; } if (isset($this->pagination['call'])) { $this->pagination['array'] = $this->callFunction($this->pagination['call']); } $keys = ['toPlaceholder']; $pagination = $this->template->getSnippet('pagination', ArrayHelper::diffByKeys($this->pagination, $keys)); if (!empty($this->pagination['toPlaceholder'])) { $this->template->addPlaceholder($this->pagination['toPlaceholder'], $pagination); $this->template->cachePlaceholders[$this->pagination['toPlaceholder']] = $pagination; return; } $this->template->addPlaceholder('pagination', $pagination); }
/** * @param mixed $rows * @param ConnectionInterface $connection * @return array */ public function typeCast($rows, ConnectionInterface $connection = null) { if (isset($connection)) { $this->setConnection($connection); } $connection = $this->getConnection(); if ($connection->typeCast) { $rows = is_array($rows) ? ArrayHelper::toType($rows) : Helper::toType($rows); } return $rows; }
/** * @inheritdoc */ public function getAll(array $only = [], array $exclude = [], Sanitize $sanitize = null) { if (empty($_COOKIE)) { return []; } static::$data = Serialize::unserializeRecursive($_COOKIE); static::$data = $this->sanitize(static::$data, $sanitize); return static::$data = ArrayHelper::only(static::$data, $only, $exclude); }
/** * Sorts the data models according to the given sort definition * @param array $models the models to be sorted * @param Sort $sort the sort definition * @return array the sorted data models */ protected function sortModels($models, $sort) { $orders = $sort->getOrders(); if (!empty($orders)) { ArrayHelper::multisort($models, array_keys($orders), array_values($orders)); } return $models; }
protected function login(User $user, Users $users) { $data = $users->toArray(); $user->addMulti(ArrayHelper::intersectByKeys($data, ['id', 'username', 'url'])); $user->login(); }
protected static function getHash($token) { if (is_array($token)) { $token = ArrayHelper::only($token, [], static::$exclude); $token = serialize($token); } return crc32($token); }
/** * @inheritdoc */ public function getAll(array $only = [], array $exclude = []) { return ArrayHelper::only(static::$items, $only, $exclude); }
private function _merge(array $array1, array $array2, $recursive = false) { if ($recursive) { return ArrayHelper::merge($array1, $array2); } return array_merge($array1, $array2); }
/** * Finds ActiveRecord instance(s) by the given condition. * * This method is internally called by {@see BaseActiveRecord::findOne()} and {@see BaseActiveRecord::findAll()}. * * @param mixed $condition please refer to {@see BaseActiveRecord::findOne()} for the explanation of this parameter * @return ActiveQueryInterface the newly created {@see \rock\db\common\ActiveQueryInterface} instance. * @throws DbException if there is no primary key defined * @internal */ protected static function findByCondition($condition) { $query = static::find(); if (!ArrayHelper::isAssociative($condition)) { // query by primary key $primaryKey = static::primaryKey(); if (isset($primaryKey[0])) { $condition = [$primaryKey[0] => $condition]; } else { throw new DbException('"' . get_called_class() . '" must have a primary key.'); } } return $query->andWhere($condition); }