Esempio n. 1
0
 /**
  * @inheritdoc
  */
 public function validateAttribute($model, $attribute)
 {
     if (!is_array($model->{$attribute}) || !ArrayHelper::isIndexed($model->{$attribute}, true)) {
         $model->addError($attribute, 'invalid data.');
         return;
     }
     $config = [];
     if (is_string($this->embedded)) {
         $config['class'] = $this->embedded;
     } else {
         $config = $this->embedded;
     }
     $items = [];
     foreach ($model->{$attribute} as $i => $data) {
         /* @var $embedded \yii\base\Model */
         $embedded = Yii::createObject($config);
         $embedded->scenario = $model->scenario;
         $embedded->setAttributes($data);
         if (!$embedded->validate()) {
             $items[] = $data;
             foreach ($embedded->getErrors() as $key => $errors) {
                 $errorKey = "{$attribute}.{$i}.{$key}";
                 foreach ($errors as $error) {
                     $model->addError($errorKey, $error);
                 }
             }
             return;
         } else {
             $items[] = $embedded->toArray();
         }
         $embedded = null;
     }
     $model->{$attribute} = $items;
 }
 /**
  * Parses POST data into array of JSON-PRC batch requests
  * @return array
  * @throws \yii\web\BadRequestHttpException
  */
 protected function getRequestArray()
 {
     $requestArray = Yii::$app->request->getBodyParams();
     if (!is_array($requestArray)) {
         throw new \yii\web\BadRequestHttpException('Invalid JSON-RPC request.');
     }
     if (!ArrayHelper::isIndexed($requestArray)) {
         $requestArray = array($requestArray);
     }
     return $requestArray;
 }
 public static function modsClass($bem, $mods)
 {
     $classes = [];
     $mods = ArrayHelper::getValue($mods, '__monster__mods__', []);
     $isIndexed = ArrayHelper::isIndexed($mods);
     foreach ($mods as $key => $value) {
         if ($value === true) {
             $classes[] = "{$bem}_{$key}";
         } elseif ($isIndexed) {
             $classes[] = "{$bem}_{$value}";
         } else {
             $classes[] = "{$bem}_{$key}_{$value}";
         }
     }
     return implode(' ', $classes);
 }
 /**
  * Initialize the queue.
  * @return void
  */
 public function init()
 {
     parent::init();
     $this->queue = \yii\di\Instance::ensure($this->queue, Queue::className());
     $this->_hasEventHandlers = !\yii\helpers\ArrayHelper::isIndexed($this->events, true);
     if ($this->_hasEventHandlers) {
         foreach ($this->events as $attr => $handler) {
             if (is_callable($handler)) {
                 if (!isset($this->_serializer)) {
                     $this->_serializer = new \SuperClosure\Serializer();
                 }
                 $this->events[$attr] = $this->_serializer->serialize($handler);
             }
         }
     }
 }
Esempio n. 5
0
 public static function normalizeListItem($items = [])
 {
     if (ArrayHelper::isIndexed($items, true)) {
         return $items;
     }
     $data = [];
     foreach ($items as $key => $value) {
         if (is_array($value)) {
             foreach ($value as $_k => $_v) {
                 $data[] = ['value' => $_k, 'text' => $_v, 'group' => $key];
             }
         } else {
             $data[] = ['value' => $key, 'text' => $value];
         }
     }
     return $data;
 }
 public function registerClientPlugins($clientPlugins, $excludedPlugins)
 {
     if (is_array($clientPlugins)) {
         if (ArrayHelper::isIndexed($clientPlugins, true)) {
             // sequential array = list of plugins to be included
             // use default configurations for every plugin
             $this->registerPlugins($clientPlugins);
         } else {
             // associative array = custom plugins and options included
             foreach ($clientPlugins as $key => $value) {
                 if (is_numeric($key)) {
                     $pluginName = $value;
                     if (!$this->isPluginExcluded($pluginName, $excludedPlugins)) {
                         $this->registerPlugin($pluginName);
                     }
                 } else {
                     $pluginName = $key;
                     if (!$this->isPluginExcluded($pluginName, $excludedPlugins)) {
                         $pluginOptions = $value;
                         $issetJs = isset($pluginOptions['js']);
                         $issetCss = isset($pluginOptions['css']);
                         if ($issetJs) {
                             $this->addJs($pluginOptions['js']);
                         } else {
                             if ($this->isPluginJsFileExist($pluginName)) {
                                 $this->addJs($this->getDefaultJsUrl($pluginName));
                             } else {
                                 throw new Exception("you must set 'js' [and 'css'] for plugin '{$pluginName}'");
                             }
                         }
                         if ($issetCss) {
                             $this->addCss($pluginOptions['css']);
                         } else {
                             if ($this->isPluginCssFileExist($pluginName)) {
                                 $this->addCss($this->getDefaultCssUrl($pluginName));
                             }
                         }
                     }
                 }
             }
         }
     } else {
         $this->registerPlugins(array_diff($this->froalaPlugins, $excludedPlugins ?: []), false, true);
     }
 }
 /**
  * @param array $variationConfig
  * @return array
  */
 public static function normalizeVariationConfig($variationConfig)
 {
     $config = array();
     $arrayIndexed = ArrayHelper::isIndexed($variationConfig);
     $argumentCount = count($variationConfig);
     $defaultResizeMode = self::default_resize_mod();
     if ($arrayIndexed) {
         $config['width'] = $variationConfig[0];
         $config['height'] = $variationConfig[1];
         if ($argumentCount > 2) {
             $config['mode'] = in_array($variationConfig[2], array('inset', 'outbound')) ? $variationConfig[2] : $defaultResizeMode;
         }
         if ($argumentCount > 3) {
             $config['quality'] = is_numeric($variationConfig[3]) ? $variationConfig[3] : self::default_quality();
         }
     } else {
         $config['width'] = $variationConfig['width'];
         $config['height'] = $variationConfig['height'];
         $config['mode'] = in_array($variationConfig['mode'], array('inset', 'outbound')) ? $variationConfig['mode'] : $defaultResizeMode;
         if (isset($variationConfig['quality'])) {
             $config['quality'] = is_numeric($variationConfig['quality']) ? $variationConfig['quality'] : self::default_quality();
         }
         if (isset($variationConfig['watermark'])) {
             $default_watermark_config = array('position' => WatermarkFilter::WM_POSITION_BOTTOM_RIGHT, 'margin' => 5);
             if (is_array($variationConfig['watermark'])) {
                 if (isset($variationConfig['watermark']['path'])) {
                     $config['watermark'] = ArrayHelper::merge($default_watermark_config, $variationConfig['watermark']);
                 }
             } else {
                 $config['watermark'] = ArrayHelper::merge($default_watermark_config, ['path' => $variationConfig['watermark']]);
             }
         }
         // fill color for resize mode fill in (inset variation)
         // crop
         // rotate
         // etc
     }
     if (!isset($config['mode'])) {
         $config['mode'] = $defaultResizeMode;
     }
     if (!isset($config['quality'])) {
         $config['quality'] = self::default_quality();
     }
     return $config;
 }
Esempio n. 8
0
 public function actionRouteToUrl()
 {
     \Yii::$app->response->format = Response::FORMAT_JSON;
     $route = \Yii::$app->request->get('route');
     if ($route === null) {
         throw new NotAcceptableHttpException();
     }
     if (is_string($route)) {
         switch ($route) {
             case 'home':
                 return ['success' => true, 'url' => Url::home()];
             default:
                 throw new NotSupportedException();
         }
     } else {
         if (ArrayHelper::isIndexed($route)) {
             $url = Url::to($route);
         } else {
             $url = Url::to(array_merge([ArrayHelper::getValue($route, 'route', '')], ArrayHelper::getValue($route, 'params', [])));
         }
         return ['success' => true, 'url' => $url];
     }
 }
Esempio n. 9
0
 /**
  * (PHP 5 &gt;= 5.0.0)<br/>
  * Whether a offset exists
  * @link http://php.net/manual/en/arrayaccess.offsetexists.php
  *
  * @param mixed $offset <p>
  *                      An offset to check for.
  *                      </p>
  *
  * @return boolean true on success or false on failure.
  * </p>
  * <p>
  * The return value will be casted to boolean if non-boolean was returned.
  */
 public function offsetExists($offset)
 {
     return ArrayHelper::isIndexed($this->data) && count($this->data) > $offset;
 }
Esempio n. 10
0
 /**
  * Resolve the keys into `BatchGetItem` eligible argument.
  * @param string $table The name of the table.
  * @param array  $keys  The keys.
  * @return array
  */
 private function buildBatchKeyArgument($table, $keys)
 {
     $tableDescription = $this->db->createCommand()->describeTable($table)->execute();
     $keySchema = $tableDescription['Table']['KeySchema'];
     if (ArrayHelper::isIndexed($keys)) {
         $isScalar = is_string($keys[0]) || is_numeric($keys[0]);
         if ($isScalar) {
             return $this->buildBatchKeyArgumentFromIndexedArrayOfScalar($keySchema, $keys);
         } elseif (ArrayHelper::isIndexed($keys[0])) {
             return $this->buildBatchKeyArgumentFromIndexedArrayOfIndexedArray($keySchema, $keys);
         } else {
             return $this->buildBatchKeyArgumentFromIndexedArrayOfAssociativeArray($keySchema, $keys);
         }
     } else {
         return $this->buildBatchGetItemFromAssociativeArray($keySchema, $keys);
     }
 }
 /**
  * Initialize the queue.
  * @throws \Exception
  */
 public function init()
 {
     parent::init();
     $queueName = $this->queue;
     $this->queue = Yii::$app->get($queueName);
     if (!$this->queue instanceof \UrbanIndo\Yii2\Queue\Queue) {
         throw new \Exception("Can not found queue component named '{$queueName}'");
     }
     $this->_hasEventHandlers = !\yii\helpers\ArrayHelper::isIndexed($this->events, true);
     if ($this->_hasEventHandlers) {
         foreach ($this->events as $attr => $handler) {
             if (is_callable($handler)) {
                 if (!isset($this->_serializer)) {
                     $this->_serializer = new \SuperClosure\Serializer();
                 }
                 $this->events[$attr] = $this->_serializer->serialize($handler);
             }
         }
     }
 }
Esempio n. 12
0
 /**
  * @throws InvalidConfigException
  * @throws \yii\base\InvalidConfigException
  */
 public function init()
 {
     parent::init();
     if (!empty($this->dbList)) {
         if (!ArrayHelper::isIndexed($this->dbList)) {
             throw new InvalidConfigException('Property dbList must be as indexed array');
         }
         foreach ($this->dbList as $dbAlias) {
             /**
              * @var Connection $db
              */
             $db = Instance::ensure($dbAlias, Connection::className());
             $this->dbInfo[$dbAlias]['driverName'] = $db->driverName;
             $this->dbInfo[$dbAlias]['dsn'] = $db->dsn;
             $this->dbInfo[$dbAlias]['host'] = $this->getDsnAttribute('host', $db->dsn);
             $this->dbInfo[$dbAlias]['port'] = $this->getDsnAttribute('port', $db->dsn);
             $this->dbInfo[$dbAlias]['dbName'] = $this->getDsnAttribute('dbname', $db->dsn);
             $this->dbInfo[$dbAlias]['username'] = $db->username;
             $this->dbInfo[$dbAlias]['password'] = $db->password;
             $this->dbInfo[$dbAlias]['prefix'] = $db->tablePrefix;
         }
     }
     $this->path = Yii::getAlias($this->path);
     if (!StringHelper::endsWith($this->path, '/', false)) {
         $this->path .= '/';
     }
     if (!is_dir($this->path)) {
         throw new InvalidConfigException('Path is not directory');
     }
     if (!is_writable($this->path)) {
         throw new InvalidConfigException('Path is not writable! Check chmod!');
     }
     $this->fileList = FileHelper::findFiles($this->path, ['only' => ['*.sql', '*.gz']]);
 }
Esempio n. 13
0
 /**
  * Deterime an array is on correct format or not that mentiond on `$marks`
  * definition section.
  * 
  * @param array $marks Array of points for check to be on correct format.
  * @return boolean Whether the array is on correct format
  */
 private function isCorrectFormat($marks)
 {
     if (!is_array($marks) || empty($marks)) {
         return false;
     } elseif (ArrayHelper::isIndexed($marks, true)) {
         if (count($marks) == 2 && isset($marks[0]) && isset($marks[1]) && is_numeric($marks[0]) && is_numeric($marks[1])) {
             return true;
         } else {
             foreach ($marks as $mark) {
                 if (!$this->isCorrectFormat($mark)) {
                     return false;
                 }
             }
             return true;
         }
     } elseif (count($marks) == 2 && isset($marks['latitude']) && isset($marks['longitude']) && is_numeric($marks['latitude']) && is_numeric($marks['longitude'])) {
         return true;
     }
     return false;
 }
Esempio n. 14
0
 /**
  * Builds a DynamoDB command for batch delete item.
  *
  * @param string $table   The name of the table to be created.
  * @param array  $keys    The keys of the row to get.
  * This can be
  * 1) indexed array of scalar value for table with single key,
  *
  * e.g. ['value1', 'value2', 'value3', 'value4']
  *
  * 2) indexed array of array of scalar value for table with multiple key,
  *
  * e.g. [
  *  ['value11', 'value12'],
  *  ['value21', 'value22'],
  *  ['value31', 'value32'],
  *  ['value41', 'value42'],
  * ]
  *
  * The first scalar will be the primary (or hash) key, the second will be the
  * secondary (or range) key.
  *
  * 3) indexed array of associative array
  *
  * e.g. [
  *  ['attribute1' => 'value11', 'attribute2' => 'value12'],
  *  ['attribute1' => 'value21', 'attribute2' => 'value22'],
  *  ['attribute1' => 'value31', 'attribute2' => 'value32'],
  *  ['attribute1' => 'value41', 'attribute2' => 'value42'],
  * ]
  *
  * 4) or associative of scalar values.
  *
  * e.g. [
  *  'attribute1' => ['value11', 'value21', 'value31', 'value41']
  *  'attribute2' => ['value12', 'value22', 'value32', 'value42']
  * ].
  *
  * @param array  $updates Update hash key-value of the model.
  * @param string $action  Action of the method, either 'PUT'|'ADD'|'DELETE'.
  * @param array  $options Additional options for the final argument.
  * @return array
  */
 public function updateItemSelectedAction($table, array $keys, array $updates, $action, array $options = [])
 {
     $name = 'UpdateItem';
     $argument['TableName'] = $table;
     if (ArrayHelper::isIndexed($keys)) {
         $argument['Key'] = $this->buildBatchKeyArgument($table, $keys);
     } else {
         $argument['Key'] = $this->paramToExpressionAttributeValues($keys);
     }
     $value_map = $this->paramToExpressionAttributeValues($updates);
     foreach ($value_map as $key => $value) {
         $argument['AttributeUpdates'][$key] = ['Value' => $value, 'Action' => $action];
     }
     $argument = array_merge($argument, $options);
     return [$name, $argument];
 }
Esempio n. 15
0
 /**
  * 批量插入
  *
  * @param array $stat 字段值必须跟数据库中的字段顺序完全一样
  * ~~
  * [field1val,field2val,field3val...]
  * ~~
  * @return int|false
  * @throws \yii\db\Exception
  */
 public function batchInsertStat($stat)
 {
     // 若不是索引数组返回false
     if (arr_null($stat) || !ArrayHelper::isIndexed($stat)) {
         return false;
     }
     try {
         $db = self::getDb();
         // 事物控制
         $transaction = $db->beginTransaction();
         // 已数组的形式返回表的字段(字段的默认顺序)
         $columns = $this->getColumns();
         $result = self::find()->createCommand($db)->batchInsert(self::tableName(), $columns, $stat)->execute();
     } catch (Exception $ex) {
         $transaction->rollBack();
         return false;
     }
     if ($result) {
         $transaction->commit();
         return $result;
     } else {
         $transaction->rollBack();
         return false;
     }
 }
 /**
  * Parses and returns addon content
  *
  * @param string|array $addon the addon parameter or the array of addon parameters
  *
  * @return string
  */
 public static function getAddonContent($addon)
 {
     if (!is_array($addon)) {
         return $addon;
     }
     if (!ArrayHelper::isIndexed($addon)) {
         $addon = [$addon];
         //pack existing array into indexed array
     }
     $html = "";
     foreach ($addon as $addonItem) {
         $content = ArrayHelper::getValue($addonItem, 'content', '');
         $options = ArrayHelper::getValue($addonItem, 'options', []);
         $suffix = ArrayHelper::getValue($addonItem, 'asButton', false) ? 'btn' : 'addon';
         Html::addCssClass($options, 'input-group-' . $suffix);
         $html .= Html::tag('span', $content, $options);
     }
     return $html;
 }
Esempio n. 17
0
 /**
  * Creates a condition based on column-value pairs.
  * @param array $condition the condition specification.
  * @return array the generated Mongo condition.
  */
 public function buildHashCondition($condition)
 {
     $result = [];
     foreach ($condition as $name => $value) {
         if (strncmp('$', $name, 1) === 0) {
             // Native Mongo condition:
             $result[$name] = $value;
         } else {
             if (is_array($value)) {
                 if (ArrayHelper::isIndexed($value)) {
                     // Quick IN condition:
                     $result = array_merge($result, $this->buildInCondition('IN', [$name, $value]));
                 } else {
                     // Mongo complex condition:
                     $result[$name] = $value;
                 }
             } else {
                 // Direct match:
                 if ($name == '_id') {
                     $value = $this->ensureMongoId($value);
                 }
                 $result[$name] = $value;
             }
         }
     }
     return $result;
 }
Esempio n. 18
0
 /**
  * @param $fieldMap
  *
  * @return mixed
  * @throws InvalidConfigException
  */
 protected function prepareFieldMap($fieldMap)
 {
     if (ArrayHelper::isIndexed($fieldMap)) {
         return array_combine($fieldMap, $fieldMap);
     }
     if (!ArrayHelper::isAssociative($fieldMap)) {
         throw new InvalidConfigException('Incorrect configuration for fieldMap property');
     }
     return $fieldMap;
 }
Esempio n. 19
0
 public function testIsIndexed()
 {
     $this->assertFalse(ArrayHelper::isIndexed('test'));
     $this->assertTrue(ArrayHelper::isIndexed([]));
     $this->assertTrue(ArrayHelper::isIndexed([1, 2, 3]));
     $this->assertTrue(ArrayHelper::isIndexed([2 => 'a', 3 => 'b']));
     $this->assertFalse(ArrayHelper::isIndexed([2 => 'a', 3 => 'b'], true));
 }
Esempio n. 20
0
 /**
  * Creating model using $model configuration property
  * @return bool true, if model was created, false if it has been already configured as object
  * @throws \yii\base\InvalidConfigException
  */
 protected function createModel()
 {
     if ($this->model instanceof \yii\base\Model) {
         Yii::info('Model already configured as instanceof ' . $this->model->className(), __METHOD__);
         return false;
     }
     if (is_array($this->model)) {
         if (!ArrayHelper::isIndexed($this->model) || !$this->model[0] instanceof \yii\base\Model) {
             throw new InvalidConfigException("Property 'model'" . ' must be configured as indexed array of \\yii\\base\\Model');
         }
         Yii::info('Model property configured as array of ' . $this->model[0]->className(), __METHOD__);
         return false;
     }
     if (is_string($this->model)) {
         $this->model = Yii::createObject($configuration = ['class' => $this->model]);
         Yii::info('Model initialized with configuration: ' . VarDumper::dumpAsString($configuration), __METHOD__);
     }
     return true;
 }