/** * Получение меню * @return array */ public function getData($active) { if ($active != null) { self::$data['menu']['active'] = $active; } // Берем список проектов пользователя if (\Yii::$app->cache->exists('project:user:'******'project:user:'******'staff_id' => \Yii::$app->user->id])->all(); \Yii::$app->cache->set('project:user:'******'id'); // Получение списка профайлеров по проектам $command = new ListProfiler\command\GetProfilerList(); $command->setClassModel('app\\models\\amop\\models\\ListProfiler'); $profiler = $command->setData($idProject)->execute(); // Формирование списка профайлеров для меню foreach ($profiler as $valueProfiler) { $profilerMenu = ['label' => $valueProfiler['message'], 'name' => "profiler_" . $valueProfiler['id'], 'class' => "profiler_" . $valueProfiler['id'], 'icon_class' => 'fa fa-cube', 'badges' => ['class' => "label pull-right bg-red"], 'url' => '/profiler/detail/' . $valueProfiler['id']]; self::$data['menu']['item'][1]['item'][] = $profilerMenu; } // Формирование списка проектов для меню foreach ($project as $value) { self::$data['menu']['item'][0]['item'][] = ['label' => $value->title, 'name' => "project_" . $value->id, 'icon_class' => 'fa fa-cube', 'url' => '/project/detail/' . $value->id]; } self::$data['user']['data']['avatar'] = \Yii::$app->user->getIdentity()->avatar; self::$data['user']['data']['name'] = \Yii::$app->user->getIdentity()->name; self::$data['user']['data']['surname'] = \Yii::$app->user->getIdentity()->surname; return self::$data; }
public function getHotlinkTo(Model $model, $action = null, $options = []) { if (!ArrayHelper::isIn($this->className(), ArrayHelper::getColumn($model->behaviors(), 'class'))) { throw new InvalidRouteException('The "LinkableBehavior" is not attached to the specified model'); } return $this->getHotlink(strtr('{route}/{action}', ['{route}' => $model->route, '{action}' => $action ?? $model->defaultAction]), $model->linkableParams, $options); }
public function afterFind() { parent::afterFind(); $empresasUsuarios = EmpresasUsuarios::findAll(['usuario_id' => $this->id]); $this->empresa_id = \yii\helpers\ArrayHelper::getColumn($empresasUsuarios, 'empresa_id'); $this->user_role = \yii\helpers\ArrayHelper::getColumn(Yii::$app->authManager->getRolesByUser($this->id), 'name'); }
/** * @param string $relation * * @return array */ protected function getLinkedIds($relation) { $models = (array) $this->owner->{$relation}; $ids = ArrayHelper::getColumn($models, 'primaryKey', false); $ids = array_filter($ids); return $ids; }
public function attach($owner) { parent::attach($owner); if (!$this->owner->isNewRecord) { $this->owner->values['category'] = \yii\helpers\ArrayHelper::getColumn($this->owner->categories, 'id'); } }
public function getCategoryIds() { if ($this->_categoryIds) { return $this->_categoryIds; } return ArrayHelper::getColumn($this->itemCategories, 'category_id'); }
public function actionSearch() { $get = Yii::$app->getRequest()->get(); $val = null; if (isset($get['so'])) { $soarr = explode('_', $get['so']); $val = $soarr[1]; } $query = AvRel::find()->where(['status' => AvRel::STATUS_ACTIVE]); $query->andFilterWhere(['category_id' => $get['cate']])->andFilterWhere(['av_id' => $val]); $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count()]); $avs = $query->offset($pages->offset)->limit($pages->limit)->select('goods_id')->asArray()->all(); $avs = ArrayHelper::getColumn($avs, 'goods_id'); $goods = Goods::find()->where(['status' => Goods::STATUS_ACTIVE])->andWhere(['id' => $avs])->asArray()->all(); $covers = ArrayHelper::getColumn($goods, 'cover'); $covers = Attachment::find()->where(['id' => $covers])->indexBy('id')->asArray()->all(); foreach ($goods as &$v) { if (empty($v['cover'])) { continue; } $co = $covers[$v['cover']]; $v['img'] = $co['path'] . '/tiny_' . $co['name']; } return $this->ajaxReturn(['list' => $goods]); }
public static function getActiveUsers() { $array_ids = static::find()->select(['user_id'])->where('user_id > 0')->asArray()->all(); $ids = \yii\helpers\ArrayHelper::getColumn($array_ids, 'user_id'); $users = User::find()->select(['id', 'username'])->where(['IN', 'id', $ids])->asArray()->all(); return $users; }
public function getElementsTypes() { if ($this->elements_types === null) { $this->elements_types = array_unique(ArrayHelper::getColumn($this->app->elements, 'type')); } return $this->elements_types; }
public function getOrderOfGalleryImagesForSortableWidget() { $galleryImages = $this->getGalleryImages()->select('id')->orderBy(['sort_order' => SORT_ASC])->all(); $galleryImageIds = ArrayHelper::getColumn($galleryImages, 'id'); $galleryImageIdsAsString = implode(',', $galleryImageIds); return $galleryImageIdsAsString; }
public function afterSave($insert, $changedAttributes) { //$oldCategorias = array("0"=>1); $actualItens = []; if (($actualItens = AuthItemChild::find()->andWhere("parent = '{$this->name}'")->asArray()->all()) !== null) { $actualItens = ArrayHelper::getColumn($actualItens, 'child'); } //verifica se é um array $this->itemIds = is_array($this->itemIds) ? $this->itemIds : [$this->itemIds]; $inserirItens = array_diff($this->itemIds, $actualItens); if (!empty($inserirItens)) { //save the relations foreach ($inserirItens as $id) { $r = new AuthItemChild(); $r->parent = $this->name; $r->child = $id; $r->save(); } } $delItens = array_diff($actualItens, $this->itemIds); if (!empty($delItens)) { foreach ($delItens as $remove) { $r = AuthItemChild::findOne(['child' => $remove, 'parent' => $this->name]); $r->delete(); } } parent::afterSave($insert, $changedAttributes); //don't forget this }
/** * Updates an existing Task model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); $projectId = $model->project_id; $studentIds = Yii::$app->db->createCommand('SELECT * FROM student_evidence WHERE task_id=' . $model->id)->queryAll(); //$ids = $model->students = ArrayHelper::getColumn($studentIds, 'student_id'); $status = Yii::$app->db->createCommand('SELECT * FROM student_evidence WHERE task_id=' . $model->id)->queryOne(); if ($model->load(Yii::$app->request->post())) { if (strtotime($model->delivery_date) >= strtotime(Yii::$app->formatter->asDate('now', 'yyyy-MM-dd'))) { $students = $_POST['Task']['students']; $model->save(); foreach ($students as $value) { if (!($status = StudentEvidence::findOne(['task_id' => $model->id, 'student_id' => $value]))) { Yii::$app->db->createCommand()->insert('student_evidence', ['task_id' => $model->id, 'project_id' => $model->project_id, 'evidence_id' => null, 'student_id' => $value, 'status' => Task::NEW_TASK])->execute(); } $this->setNotification($value, $model->id, $model->project_id, Notification::EDITED_TASK); } Yii::$app->getSession()->setFlash('success', 'Petición actualizada exitosamente'); return $this->redirect(['student-evidence/index']); } else { Yii::$app->getSession()->setFlash('danger', 'La fecha de entrega no puede ser anterior a la fecha actual'); return $this->render('update', ['model' => $model, 'projectId' => $projectId]); } } else { return $this->render('update', ['model' => $model, 'projectId' => $projectId]); } }
/** * @inheritdoc */ public function extraFields() { $fields = parent::extraFields(); $fields['meta'] = function (Model $Model) { return $Model->meta(); }; $fields['picture_300'] = function (Model $Model) { $result = null; $Media = $Model->pictureMedia; if (!empty($Media)) { $result = $Media->image()->resizeByWidth(300)->export(); } return $result; }; $fields['sections'] = function (Model $Model) { $result = []; $item_sections = $Model->getItemSections()->asArray()->all(); if (!empty($item_sections)) { $result = ArrayHelper::getColumn($item_sections, 'section_id'); $result = array_map('intval', $result); } return $result; }; ApiAttribute::datetimeFormat($fields, 'created_at'); ApiAttribute::datetimeFormat($fields, 'updated_at'); ApiAttribute::datetimeFormat($fields, 'published_at'); ApiAttribute::datetimeFormat($fields, 'archived_at'); ApiAttribute::datetimeFormat($fields, 'deleted_at'); ApiAttribute::datetimeFormat($fields, 'activated_at'); return $fields; }
/** * Добавляет записи для рассылки в таблицу рассылки * * @param SiteContentInterface | \app\models\SubscribeItem $item тема письма */ public static function add($item) { if ($item instanceof SiteContentInterface) { $subscribeItem = $item->getMailContent(); } else { $subscribeItem = $item; } switch ($subscribeItem->type) { case self::TYPE_NEWS: $where = ['subscribe_is_news' => 1]; break; case self::TYPE_SITE_UPDATE: $where = ['subscribe_is_site_update' => 1]; break; case self::TYPE_MANUAL: $where = ['subscribe_is_manual' => 1]; break; } $emailList = User::query($where)->select('email')->andWhere(['not', ['email' => null]])->andWhere(['is_active' => 1, 'is_confirm' => 1])->column(); $rows = []; foreach ($emailList as $email) { $urlUnSubscribe = Url::to(['subscribe/unsubscribe', 'mail' => $email, 'type' => $subscribeItem->type, 'hash' => self::hashGenerate($email, $subscribeItem->type)], true); $rows[] = [str_replace('{linkUnsubscribe}', $urlUnSubscribe, $subscribeItem->text), str_replace('{linkUnsubscribe}', $urlUnSubscribe, $subscribeItem->html), $subscribeItem->subject, $email, time()]; } \Yii::info(ArrayHelper::getColumn($rows, 3), 'gs\\subscribe'); if (count($rows) > 0) { SubscribeMailItem::batchInsert(['text', 'html', 'subject', 'mail', 'date_insert'], $rows); } }
public function afterSave($insert, $changedAttributes) { //$oldCategorias = array("0"=>1); $actualAssignments = []; if (($actualAssignments = AuthAssignment::find()->andWhere("user_id = {$this->id}")->asArray()->all()) !== null) { $actualAssignments = ArrayHelper::getColumn($actualAssignments, 'item_name'); } //verifica se é um array $this->assignmentIds = is_array($this->assignmentIds) ? $this->assignmentIds : [$this->assignmentIds]; $inserirAssignments = array_diff($this->assignmentIds, $actualAssignments); if (!empty($inserirAssignments)) { //save the relations foreach ($inserirAssignments as $id) { $r = new AuthAssignment(); $r->user_id = $this->id; $r->item_name = $id; $r->save(); } } $delAssignments = array_diff($actualAssignments, $this->assignmentIds); if (!empty($delAssignments)) { foreach ($delAssignments as $remove) { $r = AuthAssignment::findOne(['item_name' => $remove, 'user_id' => $this->id]); $r->delete(); } } parent::afterSave($insert, $changedAttributes); //don't forget this }
/** * case: * * $data = [ * 'grantIdentifier1' => 'scopeIdentifier1', * 'grantIdentifier2' => 'scopeIdentifier2' * ] * * @param array $data * @return boolean */ public function bindGrantScope(array $data) { $grantIdentifiers = array_keys($data); $scopeIdentifiers = array_values($data); $grantsInDb = ArrayHelper::getColumn(GrantsModel::findByGrantId($grantIdentifiers)->all(), 'id'); $scopesInDb = ArrayHelper::getColumn(ScopesModel::findByScopeId($scopeIdentifiers)->all(), 'id'); if (count(array_diff($grantIdentifiers, $grantsInDb)) !== 0 or count(array_diff($scopeIdentifiers, $scopesInDb)) !== 0) { return false; } $db = CommonModel::getDb(); $transaction = $db->beginTransaction(); try { foreach ($data as $grant => $scope) { $clientGrantModel = new GrantScopesModel(); $clientGrantModel->grant_id = $grant; $clientGrantModel->scope_id = $scope; $clientGrantModel->save(); } $transaction->commit(); return true; } catch (\Exception $e) { $transaction->rollBack(); return false; } }
/** * @return string */ public function actionIndex() { /* @var $postType PostType */ /* @var $post Post */ /* @var $taxonomies Taxonomy[] */ /* @var $taxonomy Taxonomy */ /* @var $lastMedia Media */ $response = Yii::$app->response; $response->headers->set('Content-Type', 'text/xml; charset=UTF-8'); $response->format = $response::FORMAT_RAW; $postTypes = PostType::find()->select(['id', 'post_type_slug'])->all(); $taxonomies = Taxonomy::find()->select(['id', 'taxonomy_slug'])->all(); $items = []; foreach ($postTypes as $postType) { if (!isset($this->_option['post_type'][$postType->id]['enable']) || !$this->_option['post_type'][$postType->id]['enable']) { continue; } if ($post = $postType->getPosts()->andWhere(['post_status' => 'publish'])->orderBy(['id' => SORT_DESC])->one()) { $lastmod = new \DateTime($post->post_modified, new \DateTimeZone(Option::get('time_zone'))); $query = $postType->getPosts()->andWhere(['post_status' => 'publish']); $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count(), 'pageSize' => $this->_option['entries_per_page']]); for ($i = 1; $i <= $pages->pageCount; $i++) { $items[] = ['loc' => Yii::$app->urlManager->hostInfo . Url::to(['view', 'type' => 'p', 'slug' => $postType->post_type_slug, 'page' => $i]), 'lastmod' => $lastmod->format('r')]; } } } foreach ($taxonomies as $taxonomy) { if (!isset($this->_option['taxonomy'][$taxonomy->id]['enable']) || !$this->_option['taxonomy'][$taxonomy->id]['enable']) { continue; } if ($terms = $taxonomy->terms) { $post = Post::find()->from(['post' => Post::tableName()])->innerJoinWith(['terms' => function ($query) { /* @var $query \yii\db\ActiveQuery */ $query->from(['term' => Term::tableName()]); }])->where(['IN', 'term.id', ArrayHelper::getColumn($terms, 'id')])->andWhere(['post.post_status' => 'publish'])->orderBy(['post.id' => SORT_DESC])->one(); if ($post) { $query = $taxonomy->getTerms(); $lastmod = new \DateTime($post->post_modified, new \DateTimeZone(Option::get('time_zone'))); $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count(), 'pageSize' => $this->_option['entries_per_page']]); for ($i = 1; $i <= $pages->pageCount; $i++) { $items[] = ['loc' => Yii::$app->urlManager->hostInfo . Url::to(['view', 'type' => 'c', 'slug' => $taxonomy->taxonomy_slug, 'page' => $i]), 'lastmod' => $lastmod->format('r')]; } } } } if (isset($this->_option['media']['enable']) && $this->_option['media']['enable']) { $query = Media::find(); $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count(), 'pageSize' => $this->_option['entries_per_page']]); if ($lastMedia = $query->orderBy(['id' => SORT_DESC])->one()) { $lastmod = new \DateTime($lastMedia->media_modified, new \DateTimeZone(Option::get('time_zone'))); for ($i = 1; $i <= $pages->pageCount; $i++) { $items[] = ['loc' => Yii::$app->urlManager->hostInfo . Url::to(['view', 'type' => 'm', 'slug' => 'media', 'page' => $i]), 'lastmod' => $lastmod->format('r')]; } } } return $this->renderPartial('index', ['items' => $items]); }
/** * Делает рассылку писем из списка рассылки */ public function actionSend() { $time = microtime(true); $list = SubscribeMailItem::query()->limit(10)->orderBy(['date_insert' => SORT_DESC])->all(); if (count($list) > 0) { // \Yii::info('Всего писем для рассылки: ' . count($list), 'gs\\app\\commands\\SubscribeController::actionSend'); // \Yii::info('Список писем: ' . VarDumper::dumpAsString(ArrayHelper::getColumn($list, 'mail')), 'gs\\app\\commands\\SubscribeController::actionSend'); foreach ($list as $mailItem) { $mail = \Yii::$app->mailer->compose()->setFrom(\Yii::$app->params['mailer']['from'])->setTo($mailItem['mail'])->setSubject($mailItem['subject'])->setHtmlBody($mailItem['html']); if (isset($mailItem['text'])) { if ($mailItem['text'] != '') { $mail->setTextBody($mailItem['text']); } } $result = $mail->send(); if ($result == false) { \Yii::info('Не удалось доствить: ' . VarDumper::dumpAsString($mailItem), 'gs\\app\\commands\\SubscribeController::actionSend'); } } // \Yii::info('Список писем для удаления: ' . VarDumper::dumpAsString(ArrayHelper::getColumn($list, 'id')), 'gs\\app\\commands\\SubscribeController::actionSend'); SubscribeMailItem::deleteByCondition(['in', 'id', ArrayHelper::getColumn($list, 'id')]); // \Yii::info('Осталось после рассылки: ' . SubscribeMailItem::query()->count(), 'gs\\app\\commands\\SubscribeController::actionSend'); $time = microtime(true) - $time; // \Yii::info('Затраченное время на расылку: ' . $time, 'gs\\app\\commands\\SubscribeController::actionSend'); } \Yii::$app->end(); }
public static function InsertRecord($data) { if ($data) { $array = []; foreach ($data as $k => $v) { $array[$v['idvisit']] = [$v['idvisit'], $v['idvisitor'], $v['user_id'], $v['custom_var_v2'], IP::binaryToStringIP($v['location_ip']), 0, $v['custom_var_v1']]; } // \yii::error(var_export($array,1)); //查找所有已经存在的记录 $batchInsert = []; if ($array) { $findAll = ApiVisitorDetail::find()->where(['in', 'idvisit', array_keys($array)])->asArray()->all(); if ($findAll) { $findAll = ArrayHelper::index($findAll, 'idvisit'); $batchInsert = array_diff_key($array, $findAll); } else { $batchInsert = $array; } $idvisits = ArrayHelper::getColumn($batchInsert, 0, false); StatLogVisit::updateAll(['status' => 1], ['idvisit' => $idvisits]); ApiVisitorDetail::xBatchInsert($batchInsert); } return count($batchInsert); } }
/** * Updates an existing Exercise model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { if (Yii::$app->request->post()['Exercise']['test'] && isset(Yii::$app->request->post()['Exercise']['exerciseTests'])) { // echo json_encode(Yii::$app->request->post()['Exercise']['exerciseTests']); $new_id = \yii\helpers\ArrayHelper::getColumn(Yii::$app->request->post()['Exercise']['exerciseTests'], 'id'); $old_tests = \common\models\ExerciseTest::find()->where(['exercise_id' => $model->id])->andWhere(['not in', 'id', $new_id])->all(); foreach ($old_tests as $ot) { $ot->delete(); } foreach (Yii::$app->request->post()['Exercise']['exerciseTests'] as $exts) { if (\common\models\ExerciseTest::findOne($exts['id'])) { $modelET = \common\models\ExerciseTest::findOne($exts['id']); $modelET->value = $exts['value']; $modelET->istrue = $exts['istrue']; $modelET->save(); } else { $modelET = new \common\models\ExerciseTest(); $modelET->value = $exts['value']; $modelET->istrue = $exts['istrue']; $modelET->exercise_id = $model->id; $modelET->save(); } } } elseif (!isset(Yii::$app->request->post()['Exercise']['exerciseTests'])) { \common\models\ExerciseTest::deleteAll(['exercise_id' => $model->id]); } return $this->redirect(['control']); } else { return $this->render('update', ['model' => $model]); } }
public static function activeRoleAssignmentsField($model, $attribute, $options = []) { $authManager = \Yii::$app->authManager; $items = ArrayHelper::map($authManager->getItems(1), 'name', 'name'); $values = $model->isNewRecord ? [] : ArrayHelper::getColumn($authManager->getItemsByUser($model->getId()), 'name'); $options["values"] = $values; if (!empty($_POST['RoleAssignments'])) { $options["values"] = $_POST['RoleAssignments']; } $options["name"] = 'RoleAssignments'; $options['id'] = self::getInputId($model, $attribute); $prompt = 'Select ' . $model->getAttributeLabel($attribute); if (isset($options['prompt'])) { $prompt = $options['prompt']; unset($options['prompt']); } $retFields = '<div class="role-assigments">'; foreach ($authManager->getItems(1) as $item) { if (empty($item->children)) { $retFields .= self::wrapCheckbox($options["name"], $item->name, null, $options["values"]); } else { $retFields .= self::wrapCheckbox($options["name"], $item->name, null, $options["values"]); foreach ($item->children as $child) { $retFields .= self::wrapCheckbox($options["name"], $child->name, $item->name, $options["values"], 1); } } } $retFields .= '</div>'; \Yii::$app->view->registerJs("\n\n\t\t\t\$('.role-assigments input:checkbox').change(function() {\n\t\t\t\tvar isChecked = \$(this).attr('checked') !== undefined,\n\t\t\t\tparentItem = \$(this).attr('data-parent');\n\n\t\t\t\tif(isChecked && parentItem != null) {\n\t\t\t\t\tvar parentCheckedOnInit = \$('input[value=\"' + parentItem + '\"]').attr('data-checked') !== undefined;\n\n\t\t\t\t\tif(!parentCheckedOnInit)\n\t\t\t\t\t\t\$('input[value=\"' + parentItem + '\"]').prop('checked', false).removeAttr('checked').removeAttr('data-checked');\n\n\t\t\t\t\t\$(this).prop('checked', false).removeAttr('checked').removeAttr('data-checked');\n\t\t\t\t}\n\n\t\t\t\tif(!isChecked && parentItem != null) {\n\t\t\t\t\tvar parentCheckedOnInit = \$('input[value=\"' + parentItem + '\"]').attr('data-checked') !== undefined;\n\t\t\t\t\tif(!parentCheckedOnInit)\n\t\t\t\t\t\t\$('input[value=\"' + parentItem + '\"]').prop('checked', true).attr('checked', 'checked');\n\t\t\t\t\t\$(this).prop('checked', true).attr('checked', 'checked').attr('data-checked', 'true');\n\t\t\t\t}\n\n\t\t\t\tif(!isChecked && parentItem == null) {\n\t\t\t\t\t\$(this).attr('checked', 'checked');\n\t\t\t\t}\n\n\t\t\t\tif(isChecked && parentItem == null) {\n\t\t\t\t\t\$(this).removeAttr('checked').removeAttr('data-checked');\n\t\t\t\t\t\$('input[data-parent=\"' + \$(this).val() + '\"]').prop('checked', false).removeAttr('checked').removeAttr('data-checked');\n\t\t\t\t}\n\t\t\t});\n\t\t", View::POS_READY); return $retFields; }
public function actionRename() { $name = $this->getParams('name'); $newName = $this->getParams('newName'); if (empty($name) || empty($newName)) { throw new BadRequestHttpException(Yii::t('common', 'parameters_missing')); } if ($name === $newName) { throw new InvalidParameterException(['newTagName' => Yii::t('common', 'tag_never_changed')]); } $accountId = $this->getAccountId(); $account = Account::findByPk($accountId); $channels = Channel::getEnableChannelIds($accountId); $tags = empty($account->tags) ? [] : $account->tags; $tags = ArrayHelper::getColumn($tags, 'name', false); if (in_array($newName, $tags)) { throw new InvalidParameterException(['newTagName' => Yii::t('common', 'unique_filed')]); } if (!defined('KLP') || !KLP) { if (!empty($channels)) { $followerTags = Yii::$app->weConnect->renameTag($channels, $name, $newName); } } $this->attachBehavior('TagBehavior', new TagBehavior()); $this->renameTag($accountId, $name, $newName); return ['message' => 'OK', 'data' => null]; }
/** * @inheritdoc */ public function extraFields() { $fields = parent::extraFields(); $fields['roles'] = function (Model $Model) { $result = []; $roles = AuthManager()->getRolesByUser($Model->id); foreach ($roles as $role => $conf) { $result[$role] = true; } return $result; }; $fields['permissions'] = function (Model $Model) { $result = []; $permissions = AuthManager()->getPermissionsByUser($Model->id); foreach ($permissions as $permission => $conf) { $result[$permission] = true; } return $result; }; $fields['properties'] = function (Model $Model) { return $Model->properties(); }; $fields['alerts'] = function (Model $Model) { $Alerts = $this->alerts; return empty($Alerts) ? [] : ArrayHelper::getColumn($Alerts, function (AccountAlertModel $Model) { return $Model->toArray(); }); }; ApiAttribute::datetimeFormat($fields, 'created_at'); ApiAttribute::datetimeFormat($fields, 'updated_at'); ApiAttribute::datetimeFormat($fields, 'activated_at'); ApiAttribute::datetimeFormat($fields, 'deleted_at'); return $fields; }
/** * Импортирует курсы сразу для всех индексов */ public function actionCandels() { $rows = Stock::query()->all(); foreach ($rows as $row) { $stock_id = $row['id']; $this->log('Попытка получить данные для: ' . $row['name']); $importer = ['params' => ['market' => $row['finam_market'], 'em' => $row['finam_em'], 'code' => $row['finam_code']]]; $class = new \app\service\DadaImporter\Finam($importer); $date = new \DateTime(); $date->sub(new \DateInterval('P7D')); $data = $class->importCandels($date->format('Y-m-d')); // стратегия: Если данные есть то, они не трогаются $dateArray = ArrayHelper::getColumn($data, 'date'); sort($dateArray); $rows2 = StockKurs::query(['between', 'date', $dateArray[0], $dateArray[count($dateArray) - 1]])->andWhere(['stock_id' => $stock_id])->all(); $dateArrayRows = ArrayHelper::getColumn($rows2, 'date'); $new = []; foreach ($data as $row) { if (!in_array($row['date'], $dateArrayRows)) { $new[] = [$stock_id, $row['date'], $row['open'], $row['high'], $row['low'], $row['close'], $row['volume'], $row['close']]; } } if (count($new) > 0) { \Yii::info('Импортированы данные: ' . VarDumper::dumpAsString($new), 'cap\\importer\\index'); $this->log('Импортированы данные: ' . VarDumper::dumpAsString($new)); StockKurs::batchInsert(['stock_id', 'date', 'open', 'high', 'low', 'close', 'volume', 'kurs'], $new); } else { $this->log('Нечего импортировать'); } } }
/** * @param string $modelType * @param int $modelId * @param int $version * @return \yii\base\Event[] */ public function readEvents($modelType, $modelId, $version = null) { $q = call_user_func([$this->recordClass, 'find'])->where(['model_type' => $modelType, 'model_id' => $modelId]); if ($version !== null) { $q->andWhere(['<=', 'revision', $version]); } return ArrayHelper::getColumn($q->all(), 'unwrap.payload'); }
/** * @param string $language * @return bool */ public static function isLanguage($language) { if (in_array($language, ArrayHelper::getColumn(self::listing(), 'iso'))) { return true; } else { return false; } }
public function getNotChildren() { $query = AuthItem::find()->where(['not in', 'name', ArrayHelper::getColumn($this->children, 'name')])->andWhere(['<>', 'name', $this->name]); if ($this->type == Item::TYPE_PERMISSION) { $query->andWhere(['type' => Item::TYPE_PERMISSION]); } return $query->all(); }
/** * @inheritdoc */ public function getLanguages() { $query = new Query(); $result = $query->select([$this->localeField])->addSelect($this->languageField)->from($this->table)->andFilterWhere($this->languageCondition)->all(\Yii::$app->get($this->db)); // $data = ArrayHelper::map($result, $this->localeField, $this->languageField); return ArrayHelper::getColumn($result, $this->localeField); return $data; }
public function actionCityList() { if (Yii::$app->request->isAjax) { Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $city_list = ArrayHelper::getColumn(GeobaseCity::find()->where(['like', 'name', Yii::$app->request->get('q')])->all(), 'name'); return $city_list; } }
private function execDeploy($form, $model) { $models = Tasks::find()->byId($form->tasks_id)->all(); $hashItem = ArrayHelper::getColumn($models, 'hash'); $messageItem = ArrayHelper::getColumn($models, 'title'); $website = $model->website; DepControl::run(['deployScript' => $website->deploy_script, 'deployProject' => $website->deploy_project])->deploy(implode(';', $hashItem), implode(';', $messageItem)); }