Exemplo n.º 1
0
 public function get()
 {
     if (!isset($this->subject, $this->operands, $this->then) || empty($this->operands)) {
         return null;
     }
     $operands = $this->operands;
     $this->template->addMultiPlaceholders($this->template->findPlaceholders($this->addPlaceholders));
     $paramsTpl = ['subject' => $this->subject, 'params' => $operands, 'then' => $this->then, 'template' => $this->template];
     if (isset($this->else)) {
         $paramsTpl['else'] = $this->else;
     }
     $data = [];
     $this->subject = strip_tags($this->subject);
     foreach ($operands as $keyParam => $valueParam) {
         $valueParam = Helper::toType($valueParam);
         if (is_string($valueParam)) {
             $valueParam = addslashes($valueParam);
         }
         $data[$keyParam] = $valueParam;
     }
     $value = '
         $template = $params[\'template\'];
         if (' . preg_replace('/:([\\w]+)/', '$data[\'$1\']', $this->subject) . ') {
             return $template->replace($params[\'then\']);
         }' . (isset($this->else) ? ' else {return $template->replace($params[\'else\']);}' : null);
     return $this->execute->get(StringHelper::removeSpaces($value), $paramsTpl, $data);
 }
Exemplo n.º 2
0
 /**
  * @param object|string|array|static $reference an object or a reference to the desired object.
  * @param string|null $defaultClass default name of class
  * @param array $args arguments of constructor.
  * @param bool $throwException
  * @return ObjectInterface
  * @throws InstanceException
  */
 public static function ensure($reference, $defaultClass = null, array $args = [], $throwException = true)
 {
     if (is_object($reference)) {
         return $reference;
     }
     if (isset($reference) && class_exists('\\rock\\di\\Container')) {
         return \rock\di\Container::load($reference, $args, $throwException);
     } else {
         $config = [];
         if (is_array($reference)) {
             $config = $reference;
             if (!isset($defaultClass)) {
                 $defaultClass = $config['class'];
             }
             unset($config['class']);
         } elseif (is_string($reference) && !isset($defaultClass)) {
             $defaultClass = $reference;
         }
         if (!class_exists($defaultClass)) {
             if ($throwException) {
                 throw new InstanceException(InstanceException::UNKNOWN_CLASS, ['class' => Helper::getValue($defaultClass, 'null', true)]);
             }
             return null;
         }
         $reflect = new \ReflectionClass($defaultClass);
         $args = static::calculateArgs($reflect, $args, $config);
         return $reflect->newInstanceArgs($reflect->getConstructor() ? $args : []);
     }
 }
 /**
  * Formats the specified response.
  * @param Response $response the response to be formatted.
  */
 public function format(Response $response)
 {
     $charset = $this->encoding === null ? $response->charset : $this->encoding;
     if (stripos($this->contentType, 'charset') === false) {
         $this->contentType .= '; charset=' . $charset;
     }
     $response->getHeaders()->set('Content-Type', $this->contentType);
     foreach ($response->data as $value) {
         $this->_sitemap->add($value['loc'], Helper::getValue($value['lastmod']), Helper::getValue($value['changefreq']), isset($value['priority']) ? $value['priority'] : null);
     }
     $response->content = $this->_sitemap->toString();
 }
Exemplo n.º 4
0
 protected function callback($handler)
 {
     if (!isset($handler)) {
         return;
     }
     if ($handler instanceof \Closure) {
         $handler = [$handler];
     }
     $handler[1] = Helper::getValue($handler[1], [], true);
     list($function, $data) = $handler;
     $this->data = $data;
     call_user_func($function, $this);
 }
Exemplo n.º 5
0
 public function get()
 {
     if (!isset($this->subject) || empty($this->operands)) {
         return null;
     }
     $data = [];
     $this->subject = strip_tags($this->subject);
     foreach ($this->operands as $keyParam => $valueParam) {
         $valueParam = Helper::toType($valueParam);
         if (is_string($valueParam)) {
             $valueParam = addslashes($valueParam);
         }
         $data[$keyParam] = $valueParam;
     }
     return $this->execute->get(StringHelper::removeSpaces('return ' . preg_replace('/:([\\w]+)/', '$data[\'$1\']', $this->subject) . ';'), ['subject' => $this->subject, 'operands' => $this->operands], $data);
 }
Exemplo n.º 6
0
 /**
  * Remove session.
  *
  * @param string|null $name
  */
 public function removeSession($name = null)
 {
     $this->session->removeFlash(Helper::getValue($name, $this->sessionName));
 }
Exemplo n.º 7
0
 /**
  * Conversion to type of array values.
  *
  * @param array $array current array
  * @param bool $recursive
  * @return array
  */
 public static function toType(array $array, $recursive = true)
 {
     return static::map($array, function ($value) {
         return Helper::toType($value);
     }, $recursive);
 }
Exemplo n.º 8
0
 /**
  * @param array      $params
  * @throws DbException
  * @return array
  */
 public function build(&$params = [])
 {
     /** @var Connection $connection */
     $connection = Instance::ensure($this->connection, Connection::className());
     $result = [];
     foreach ($this->selects as $key => $select) {
         $alias = false;
         $aliasSeparator = null;
         if (is_array($select) && !is_string($key) && !is_string(key($select))) {
             $select[1] = Helper::getValue($select[1], false, true);
             $select[2] = Helper::getValue($select[2], null, true);
             list($select, $alias, $aliasSeparator) = $select;
         }
         if ($select instanceof ActiveQuery) {
             if (!isset($select->modelClass)) {
                 continue;
             }
             /** @var ActiveRecord $class */
             $class = $select->modelClass;
             $table = $class::tableAlias() ?: $class::tableName();
             $tableAlias = $table;
             if (is_string($alias)) {
                 $tableAlias = $alias;
                 $alias = true;
             }
             $connection = $class::getConnection();
             if (!($columns = $select->select)) {
                 continue;
             }
         } elseif (is_array($select)) {
             if (!is_string($key)) {
                 $table = key($select);
                 $select[0] = Helper::getValue($select[0], false, true);
                 $select[1] = Helper::getValue($select[1], null, true);
                 list($alias, $aliasSeparator) = $select;
                 $columns = current($select);
             } else {
                 $table = $key;
                 $columns = $select;
             }
             $tableAlias = $table;
             if (is_string($alias)) {
                 $tableAlias = $alias;
                 $alias = true;
             }
         } else {
             throw new DbException(DbException::WRONG_TYPE, ['name' => json_encode($select)]);
         }
         $aliasSeparator = Helper::getValue($aliasSeparator, $connection->aliasSeparator);
         foreach ($columns as $i => $column) {
             if ($column instanceof Expression) {
                 $columns[$i] = $column->expression;
                 $params = array_merge($params, $column->params);
             } elseif (is_string($i)) {
                 if (strpos($column, '(') === false) {
                     $column = $this->connection->quoteColumnName($column);
                 }
                 $columns[$i] = "{$column} AS " . $connection->quoteSimpleColumnName($i);
             } elseif (strpos($column, '(') === false) {
                 if (preg_match('/^(.*?)(?i:\\s+as\\s+|\\s+)([\\w\\-_\\.]+)$/', $column, $matches)) {
                     $matches[2] = $alias === true ? $tableAlias . $aliasSeparator . $matches[2] : $matches[2];
                     $columns[$i] = "{{{$table}}}." . $this->connection->quoteColumnName($matches[1]) . ' AS ' . $connection->quoteSimpleColumnName($matches[2]);
                 } else {
                     $columns[$i] = "{{{$table}}}." . $this->connection->quoteColumnName($column) . ($alias === true ? ' AS ' . $connection->quoteSimpleColumnName($tableAlias . $aliasSeparator . $column) : null);
                 }
             } elseif (strpos($column, '(') !== false) {
                 if (preg_match('/^(.*?)(?i:\\s+as\\s+|\\s+)([\\w\\-_\\.]+)$/', $column, $matches)) {
                     $matches[2] = $alias === true ? $tableAlias . $aliasSeparator . $matches[2] : $matches[2];
                     $columns[$i] = "{$matches['1']} AS " . $connection->quoteSimpleColumnName($matches[2]);
                 } else {
                     $columns[$i] = "{{{$table}}}." . $this->connection->quoteColumnName($column) . ($alias === true ? ' AS ' . $connection->quoteSimpleColumnName($tableAlias . $aliasSeparator . $column) : null);
                 }
             }
         }
         $result = array_merge($result, $columns);
     }
     return implode(', ', $result);
 }
Exemplo n.º 9
0
 protected function prepareFields(\rock\widgets\ActiveForm $form, array $fields, array &$result)
 {
     $form->submitted = $this->model->isLoad();
     foreach ($fields as $attributeName => $params) {
         if (is_int($attributeName)) {
             $result[] = $this->template->replace($params);
             continue;
         }
         if (isset($params['options']['enabled']) && $params['options']['enabled'] === false) {
             continue;
         }
         unset($params['options']['enabled']);
         $field = $form->field($this->model, $attributeName, Helper::getValue($params['options'], []));
         unset($params['options']);
         foreach ($params as $additionName => $additionParams) {
             if (is_int($additionName)) {
                 $additionName = $additionParams;
                 unset($additionParams);
             }
             call_user_func_array([$field, $additionName], Helper::getValue($additionParams, []));
         }
         $result[] = $field->render();
     }
     return $result;
 }
Exemplo n.º 10
0
 public function getHost()
 {
     if ($this->_host === null && isset($_SERVER['SERVER_NAME'])) {
         $this->_host = Helper::getValue($_SERVER['HTTP_HOST'], $_SERVER['SERVER_NAME']);
     }
     return $this->_host;
 }
Exemplo n.º 11
0
 protected function calculateArray()
 {
     $this->array = Helper::getValue($this->array);
     if (!empty($this->call)) {
         $this->array = $this->callFunction($this->call);
     }
 }
Exemplo n.º 12
0
 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;
         }
     }
 }
Exemplo n.º 13
0
 /**
  * @inheritdoc
  */
 public function sanitize($input)
 {
     return Helper::toType($input);
 }
Exemplo n.º 14
0
 /**
  * Adds dicts.
  *
  * ```php
  *  [ 'ru' =>
  *    [
  *     'path/lang/ru/lang.php',
  *     'path/lang/ru/validate.php',
  *    ]
  *  ]
  * ```
  *
  * @param array $dicts
  * @throws \Exception
  * @throws i18nException
  */
 public function addDicts(array $dicts)
 {
     if (!empty(static::$data)) {
         return;
     }
     foreach ($dicts as $lang => $paths) {
         $total = [];
         foreach ($paths as $path) {
             $path = Alias::getAlias($path);
             if (!file_exists($path) || !($data = (require $path)) || !is_array($data)) {
                 throw new i18nException(i18nException::UNKNOWN_FILE, ['path' => $path]);
                 break 2;
             }
             $context = basename($path, '.php');
             $total[$context] = array_merge(Helper::getValue($total[$context], [], true), $data);
         }
         static::$data[$lang] = array_merge(Helper::getValue(static::$data[$lang], [], true), $total);
     }
 }
Exemplo n.º 15
0
 public static function paragraph($value, array $params = [])
 {
     if (empty($value)) {
         return $value;
     }
     /** @var \rock\markdown\Markdown $markdown */
     $markdown = Instance::ensure(isset($params['markdown']) ? $params['markdown'] : 'markdown', '\\rock\\markdown\\Markdown');
     $markdown->dummy = Helper::getValue($params['enabledDummy'], false);
     if (!empty($params['enableNewlines'])) {
         $markdown->enableNewlines = true;
     }
     $markdown->denyTags = Helper::getValue($params['denyTags'], []);
     return $markdown->parseParagraph($value);
 }
Exemplo n.º 16
0
 /**
  * @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;
 }
Exemplo n.º 17
0
 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;
 }
Exemplo n.º 18
0
 /**
  * Get thumb.
  *
  * @param string $path src to image
  * @param array $params params:
  *
  * - type:     get `src`, `<a>`, `<img>` (default: `<img>`)
  * - w:        width
  * - h:        height
  * - q:        quality
  * - class:    attr `class`
  * - alt:      attr `alt`
  * - const
  * - dummy
  * @param Template $template
  * @return string
  * @throws \rock\helpers\InstanceException
  */
 public static function thumb($path, array $params, Template $template)
 {
     if (empty($path)) {
         if (empty($params['dummy'])) {
             return '';
         }
         $path = $params['dummy'];
     }
     $const = Helper::getValue($params['const'], 1, true);
     /** @var ImageProvider $imageProvider */
     $imageProvider = Instance::ensure(isset($params['imageProvider']) ? $params['imageProvider'] : 'imageProvider');
     $src = $imageProvider->get($path, Helper::getValue($params['w']), Helper::getValue($params['h']));
     if (!($const & ThumbInterface::WITHOUT_WIDTH_HEIGHT)) {
         $params['width'] = $imageProvider->width;
         $params['height'] = $imageProvider->height;
     }
     unset($params['h'], $params['w'], $params['type'], $params['const']);
     if (!empty($params['alt'])) {
         $params['alt'] = $template->replace($params['alt']);
     }
     return $const & ThumbInterface::OUTPUT_IMG ? Html::img($src, $params) : $src;
 }
Exemplo n.º 19
0
 /**
  * @param array $placeholders
  *
  * ```php
  * ['call' => '\foo\FooSnippet', 'params' => [...]]
  * ['call' => function{}()]
  * ['call' => [Foo::className(), 'staticMethod']]
  * ['call' => [new Foo(), 'method']]
  * ```
  */
 protected function prepareItem(array &$placeholders)
 {
     if (empty($this->prepare['call'])) {
         return;
     }
     $this->prepare['params'] = Helper::getValue($this->prepare['params'], []);
     $this->prepare['params']['placeholders'] = $placeholders;
     $this->prepare['params']['sanitize'] = Template::SANITIZE_DISABLE;
     $placeholders = $this->callFunction($this->prepare['call'], $this->prepare['params']);
 }
Exemplo n.º 20
0
 protected function calculateCacheParams(array &$params = [])
 {
     if (empty($params) || empty($params['cacheKey'])) {
         unset($params['cacheKey'], $params['cacheExpire'], $params['cacheTags']);
         return [null, null, null];
     }
     $cacheKey = $params['cacheKey'];
     $cacheExpire = Helper::getValue($params['cacheExpire'], 0, true);
     $cacheTags = Helper::getValue($params['cacheTags'], []);
     unset($params['cacheKey'], $params['cacheExpire'], $params['cacheTags']);
     return [$cacheKey, $cacheExpire, $cacheTags];
 }
Exemplo n.º 21
0
 /**
  * Parses an image indicated by `![`.
  * @marker ![
  */
 protected function parseImage($markdown)
 {
     if (($parts = $this->parseLinkOrImage(substr($markdown, 1))) !== false) {
         list($text, $url, $title, $offset, $key, $data) = $parts;
         if (isset($data['macros'])) {
             if ($this->isTag('thumb') && $data['macros'] === 'thumb') {
                 if (!isset($this->imageProvider)) {
                     if ($this->throwException) {
                         throw new MarkdownException(MarkdownException::NOT_INSTALL_IMAGE);
                     }
                     return $this->skipImage($markdown);
                 }
             } elseif ($this->isTag('video') && $data['macros'] !== 'thumb') {
                 $width = isset($data['width']) ? $data['width'] : $this->dimensionsVideo[0];
                 $height = isset($data['height']) ? $data['height'] : $this->dimensionsVideo[1];
                 $video = $this->calculateVideo($url, $width, $height, $title ?: null);
                 $video['refkey'] = $key;
                 $video['orig'] = substr($markdown, 0, $offset + 1);
                 $video['hosting'] = $data['macros'];
                 return [$video, $offset + 1];
             }
         }
         if (isset($this->imageProvider)) {
             $url = $this->imageProvider->get('/' . ltrim($url, '/'), Helper::getValue($data['width'], 0), Helper::getValue($data['height'], 0));
         }
         return [['image', 'text' => $text, 'url' => $url, 'title' => $title, 'refkey' => $key, 'orig' => substr($markdown, 0, $offset + 1)], $offset + 1];
     } else {
         return $this->skipImage($markdown);
     }
 }
Exemplo n.º 22
0
 /**
  * Match by Custom
  *
  * @param array $rule array data of access
  * @return bool
  */
 protected function matchCustom(array $rule)
 {
     $rule['custom'][1] = Helper::getValue($rule['custom'][1], [], true);
     list($function, $args) = $rule['custom'];
     $result = (bool) call_user_func($function, array_merge(['owner' => $this->owner], $args));
     if (!$result && $this->sendHeaders && $this->response instanceof \rock\response\Response) {
         $this->response->status403();
     }
     return $result;
 }
Exemplo n.º 23
0
 /**
  * Adds a query params.
  * @param array $queryParams list arguments.
  * @return $this
  */
 public function addQueryParams(array $queryParams)
 {
     $this->data['query'] = array_merge(Helper::getValue($this->data['query'], []), $queryParams);
     $this->data['query'] = array_filter($this->data['query']);
     return $this;
 }