Exemple #1
0
 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);
 }
Exemple #2
0
 /**
  * Returns the Mongo collection for the file chunks.
  * @param boolean $refresh whether to reload the collection instance even if it is found in the cache.
  * @return \rock\mongodb\Collection mongo collection instance.
  */
 public function getChunkCollection($refresh = false)
 {
     if ($refresh || !is_object($this->_chunkCollection)) {
         $this->_chunkCollection = Instance::ensure(['class' => \rock\mongodb\Collection::className(), 'mongoCollection' => $this->mongoCollection->chunks]);
     }
     return $this->_chunkCollection;
 }
 /**
  * Attaches a behavior to this component.
  *
  * @param string|integer $name the name of the behavior. If this is an integer, it means the behavior
  * is an anonymous one. Otherwise, the behavior is a named one and any existing behavior with the same name
  * will be detached first.
  * @param string|array|Behavior $behavior the behavior to be attached
  * @return Behavior the attached behavior.
  * @throws BaseException
  */
 private function _attachBehaviorInternal($name, $behavior)
 {
     if (is_array($behavior)) {
         if (isset($behavior['class'])) {
             if (is_subclass_of($behavior['class'], '\\rock\\filters\\FilterInterface') && $this instanceof Responseble) {
                 $behavior['response'] = $this->response;
             } elseif (is_subclass_of($behavior['class'], '\\rock\\request\\Requestable') && $this instanceof \rock\request\Requestable) {
                 $behavior['request'] = $this->request;
             }
         }
     } elseif ($behavior instanceof FilterInterface && $this instanceof Responseble) {
         $behavior->response = $this->response;
     } elseif ($behavior instanceof \rock\request\Requestable && $this instanceof \rock\request\Requestable) {
         $behavior->request = $this->request;
     }
     /** @var Behavior $behavior */
     $behavior = Instance::ensure($behavior);
     /** @var ComponentsInterface|static $this */
     if (is_int($name)) {
         $behavior->attach($this);
         $this->_behaviors[] = $behavior;
     } else {
         if (isset($this->_behaviors[$name])) {
             $this->_behaviors[$name]->detach();
         }
         $behavior->attach($this);
         $this->_behaviors[$name] = $behavior;
     }
     return $behavior;
 }
 /**
  * Initializes the DB connection component.
  * This method will initialize the {@see \rock\data\ActiveDataProvider::$connection} property to make sure it refers to a valid DB connection.
  * @throws InstanceException if {@see \rock\data\ActiveDataProvider::$connection} is invalid.
  */
 public function init()
 {
     parent::init();
     if (isset($this->connection)) {
         $this->connection = Instance::ensure($this->connection);
     }
 }
Exemple #5
0
 public function init()
 {
     $this->request = Instance::ensure($this->request);
     $this->storage = Instance::ensure($this->storage);
     if ($this->storage instanceof Cookie) {
         $this->storage->httpOnly = true;
     }
 }
Exemple #6
0
 public function init()
 {
     $this->security = Instance::ensure($this->security, Security::className());
     $this->storage = Instance::ensure($this->storage, Session::className());
     if ($this->storage instanceof Cookie) {
         $this->storage->httpOnly = true;
     }
 }
Exemple #7
0
 public function init()
 {
     $this->connection = Instance::ensure($this->connection);
     if (!empty(static::$items)) {
         return;
     }
     $this->load();
 }
Exemple #8
0
 /**
  * Returns instance {@see \rock\template\Template}.
  * @return Template
  * @throws \rock\helpers\InstanceException
  */
 public function getTemplate()
 {
     if ($this->_template instanceof Template) {
         return $this->_template;
     }
     $this->_template = Instance::ensure($this->_template);
     $this->_template->context = $this;
     return $this->_template;
 }
 /**
  * Initializes the widget.
  */
 public function init()
 {
     parent::init();
     $this->captcha = Instance::ensure($this->captcha);
     $this->checkRequirements();
     if (!isset($this->imageOptions['id'])) {
         $this->imageOptions['id'] = $this->options['id'] . '-image';
     }
 }
Exemple #10
0
 public function init()
 {
     if (!($this->adapter = Instance::ensure($this->adapter, null, [], false))) {
         throw new ImageException(ImageException::NOT_INSTALL_FILE);
     }
     $this->adapterCache = Instance::ensure($this->adapterCache);
     $this->srcImage = Alias::getAlias($this->srcImage);
     $this->srcCache = Alias::getAlias($this->srcCache);
 }
 /**
  * @throws \rock\helpers\InstanceException
  */
 public function init()
 {
     parent::init();
     $this->csrf = Instance::ensure($this->csrf, '\\rock\\csrf\\CSRF');
     $this->csrf->enableCsrfValidation = $this->validate;
     $this->verbs = (array) $this->verbs;
     if ($this->verbs === ['*']) {
         $this->verbs = ['GET', 'POST', 'PUT', 'HEAD', 'OPTIONS', 'PATH'];
     }
 }
Exemple #12
0
 /**
  * @throws \rock\helpers\InstanceException
  */
 public function init()
 {
     $this->csrf = Instance::ensure($this->csrf, '\\rock\\csrf\\CSRF');
     $this->csrf->enableCsrfValidation = $this->validate;
     $this->response = Instance::ensure($this->response, '\\rock\\response\\Response');
     $this->request = Instance::ensure($this->request, '\\rock\\request\\Request');
     $this->verbs = (array) $this->verbs;
     if ($this->verbs === ['*']) {
         $this->verbs = ['GET', 'POST', 'PUT', 'HEAD', 'OPTIONS', 'PATH'];
     }
 }
Exemple #13
0
 public function before()
 {
     $config = ['class' => Access::className(), 'owner' => $this->owner, 'rules' => $this->rules];
     $this->access = Instance::ensure($config);
     if (!$this->access->checkAccess()) {
         if ($this->event instanceof RouteEvent) {
             $this->event->errors |= $this->access->errors;
         }
         return false;
     }
     return parent::before();
 }
Exemple #14
0
 /**
  * Serializes the specified data.
  * The default implementation will create a serializer based on the configuration given by {@see \rock\rest\Serializer}.
  * It then uses the serializer to serialize the given data.
  * @param mixed $data the data to be serialized
  * @return mixed the serialized data.
  */
 protected function serializeData($data)
 {
     if (is_string($this->serializer)) {
         $this->serializer = ['class' => $this->serializer, 'response' => $this->response];
     }
     if (is_array($this->serializer)) {
         $this->serializer['extend'] = $this->extend;
     }
     /** @var Serializer $serializer */
     $serializer = Instance::ensure($this->serializer);
     return $serializer->serialize($data);
 }
Exemple #15
0
 /**
  * Creates a widget instance and runs it.
  * The widget rendering result is returned by this method.
  * @param array $config name-value pairs that will be used to initialize the object properties
  * @return string the rendering result of the widget.
  */
 public static function widget(array $config = [])
 {
     ob_start();
     ob_implicit_flush(false);
     /** @var Widget $widget */
     $config['class'] = get_called_class();
     $widget = Instance::ensure($config);
     $out = '';
     if ($widget->beforeWidget()) {
         $out = $widget->run();
         $widget->afterWidget(null);
     }
     $out = ob_get_clean() . $out;
     return $out;
 }
 /**
  * @inheritdoc
  */
 public function get()
 {
     $this->model = Instance::ensure($this->model);
     if (!$this->model->isLoad()) {
         $this->validate = false;
     }
     if ($this->validate === true) {
         $this->prepareAttributes();
         if (!$this->model->validate()) {
             $this->errorsToPlaceholders($this->model);
         }
     }
     $this->config['model'] = $this->model;
     ob_start();
     $form = \rock\widgets\ActiveForm::begin($this->config);
     $output = ob_get_clean();
     $fields = [];
     $fields[] = $output;
     if (!empty($this->fields)) {
         $this->prepareFields($form, (array) $this->fields, $fields);
     }
     $fields[] = $this->prepareSubmitButton($this->submitButton);
     ob_start();
     ob_implicit_flush(false);
     \rock\widgets\ActiveForm::end();
     $output = ob_get_clean();
     $fields[] = $output;
     $result = implode("\n", $fields);
     // Inserting content into wrapper template (optional)
     if (!empty($this->wrapperTpl)) {
         $result = $this->parseWrapperTpl($result, $this->wrapperTpl);
     }
     // To placeholder
     if (!empty($this->toPlaceholder)) {
         $this->template->addPlaceholder($this->toPlaceholder, $result, true);
         $this->template->cachePlaceholders[$this->toPlaceholder] = $result;
         return '';
     }
     return $result;
 }
Exemple #17
0
 protected function getRequest($url, array $params)
 {
     $config = array_merge(parse_url($url), $params);
     $config['method'] = isset($config['method']) ? $config['method'] : Route::GET;
     $config['url'] = isset($config['path']) ? $config['path'] : null;
     unset($config['path']);
     if ($config['method'] !== Route::GET) {
         if (isset($config['query']) && is_array($config['query'])) {
             $config['bodyParams'] = $config['query'];
         }
     } elseif (isset($config['query'])) {
         if (is_array($config['query'])) {
             $config['query'] = http_build_query($config['query']);
         }
         $config['queryString'] = $config['query'];
         if (isset($config['url'])) {
             $config['url'] .= "?{$config['query']}";
         }
     }
     unset($config['query']);
     Instance::configure($this->request, $config);
     return $this->request;
 }
Exemple #18
0
 /**
  * Selects GridFS collection with given prefix.
  * @param string $prefix file collection prefix.
  * @return file\Collection file collection instance.
  */
 protected function selectFileCollection($prefix)
 {
     return Instance::ensure(['class' => \rock\mongodb\file\Collection::className(), 'mongoCollection' => $this->mongoDb->getGridFS($prefix), 'connection' => $this->connection]);
 }
Exemple #19
0
 /**
  * @param $snippet
  * @param array $params
  * @return Snippet
  * @throws TemplateException
  * @throws \rock\helpers\InstanceException
  */
 protected function getInstanceSnippet($snippet, array $params = [])
 {
     if ($snippet instanceof Snippet) {
         if (!empty($params)) {
             Instance::configure($snippet, $params);
         }
         return $snippet;
     }
     if (!isset($this->snippets[$snippet])) {
         throw new TemplateException(TemplateException::UNKNOWN_SNIPPET, ['name' => $snippet]);
     }
     $config = $this->snippets[$snippet];
     if (is_callable($config)) {
         if (($config = call_user_func($this->snippets[$snippet], $params)) instanceof Snippet) {
             return $config;
         }
     }
     if (!isset($config['class'])) {
         throw new TemplateException(TemplateException::UNKNOWN_SNIPPET, ['name' => $snippet]);
     }
     $config = array_merge($config, $params);
     /** @var \rock\snippets\Snippet $snippet */
     $snippet = Instance::ensure($config);
     if (!$snippet instanceof Snippet) {
         throw new TemplateException(TemplateException::UNKNOWN_SNIPPET, ['name' => $snippet::className()]);
     }
     return $snippet;
 }
 public function init()
 {
     $this->request = Instance::ensure($this->request, '\\rock\\request\\Request', [], false);
 }
Exemple #21
0
 public function init()
 {
     $this->session = Instance::ensure($this->session, '\\rock\\session\\Session', [], false);
 }
Exemple #22
0
 /**
  * Initializes the application component.
  */
 public function init()
 {
     $this->cache = Instance::ensure($this->cache);
 }
Exemple #23
0
 /**
  * Opens the connection to a server in the pool.
  *
  * This method implements the load balancing among the given list of the servers.
  *
  * @param array $pool the list of connection configurations in the server pool
  * @param array $sharedConfig the configuration common to those given in `$pool`.
  * @return Connection the opened DB connection, or null if no server is available
  * @throws DbException if a configuration does not specify "dsn"
  */
 protected function openFromPool(array $pool, array $sharedConfig)
 {
     if (empty($pool)) {
         return null;
     }
     if (!isset($sharedConfig['class'])) {
         $sharedConfig['class'] = get_class($this);
     }
     $cache = Instance::ensure($this->serverStatusCache, null, [], false);
     shuffle($pool);
     foreach ($pool as $config) {
         $config = array_merge($sharedConfig, $config);
         if (empty($config['dsn'])) {
             throw new DbException('The "dsn" option must be specified.');
         }
         $key = [__METHOD__, $config['dsn']];
         if ($cache instanceof CacheInterface && $cache->get($key)) {
             // should not try this dead server now
             continue;
         }
         /* @var $connection Connection */
         $connection = Instance::ensure($config);
         try {
             $connection->open();
             return $connection;
         } catch (\Exception $e) {
             if (class_exists('\\rock\\log\\Log')) {
                 Log::warn(BaseException::convertExceptionToString($e));
             }
             if ($cache instanceof CacheInterface) {
                 // mark this server as dead and only retry it after the specified interval
                 $cache->set($key, 1, $this->serverRetryInterval);
             }
         }
     }
     return null;
 }
Exemple #24
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;
 }
Exemple #25
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);
 }
Exemple #26
0
 public function init()
 {
     parent::init();
     $this->imageProvider = Instance::ensure($this->imageProvider);
 }
Exemple #27
0
 protected function getCache($rawQuery, $token, $all, $indexBy, &$cache, &$cacheKey, &$lock = true)
 {
     /** @var $cache CacheInterface */
     if ($this->connection->enableQueryCache) {
         $cache = Instance::ensure($this->connection->queryCache, null, [], false);
     }
     if ($cache instanceof CacheInterface) {
         $cacheKey = json_encode([__METHOD__, $this->connection->dsn, $rawQuery]);
         if (($result = $cache->get($cacheKey)) !== false) {
             Trace::increment('cache.mongodb', 'Cache query MongoDB connection: ' . $this->connection->dsn);
             Trace::endProfile('mongodb.query', $token);
             $token['cache'] = true;
             Trace::trace('mongodb.query', $token);
             return is_array($result) ? $this->fetchRowsAsArrayInternal($result, $all, $indexBy) : $result;
         }
         $lock = $cache->lock($cacheKey);
     }
     return false;
 }
 /**
  * Sets the sort definition for this data provider.
  * @param array|Sort|boolean $value the sort definition to be used by this data provider.
  * This can be one of the following:
  *
  * - a configuration array for creating the sort definition object. The "class" element defaults
  *   to 'rock\data\Sort'
  * - an instance of {@see \rock\data\Sort} or its subclass
  * - false, if sorting needs to be disabled.
  *
  * @throws DataProviderException
  */
 public function setSort($value)
 {
     if (is_array($value)) {
         $config = ['class' => Sort::className()];
         $this->_sort = Instance::ensure(array_merge($config, $value));
     } elseif ($value instanceof Sort || $value === false) {
         $this->_sort = $value;
     } else {
         throw new DataProviderException('Only Sort instance, configuration array or false is allowed.');
     }
 }
Exemple #29
0
 public function init()
 {
     $this->request = Instance::ensure($this->request, '\\rock\\request\\Request');
     $this->response = Instance::ensure($this->response, '\\rock\\response\\Response', [], false);
     $this->user = Instance::ensure($this->user, '\\rock\\user\\user', [], false);
 }
Exemple #30
0
 /**
  * Registers session handler.
  *
  * @throws SessionException
  */
 protected function registerSessionHandler()
 {
     if ($this->handler !== null) {
         $this->handler = Instance::ensure($this->handler);
         if (!$this->handler instanceof \SessionHandlerInterface) {
             throw new SessionException('"' . get_class($this) . '::handler" must implement the SessionHandlerInterface.');
         }
         @session_set_save_handler($this->handler, false);
     } elseif ($this->getUseCustomStorage()) {
         @session_set_save_handler([$this, 'openSession'], [$this, 'closeSession'], [$this, 'readSession'], [$this, 'writeSession'], [$this, 'destroySession'], [$this, 'gcSession']);
     }
 }