public function actionList() { $limit = 10; $page = is_null(Yii::$app->request->get('page')) ? 1 : Yii::$app->request->get('page'); $offset = ((int) $page - 1) * $limit; $order = ['service.order' => SORT_ASC, 'id' => SORT_DESC]; if (is_null(Yii::$app->request->get('section'))) { $service = Service::find()->select(['service.id', 'service.sid', 'service.header'])->innerJoinWith('secs')->orderBy($order)->offset($offset)->limit($limit)->all(); $pagination = new Pagination(['totalCount' => Service::find()->count(), 'pageSize' => $limit]); } else { $service = Service::find()->select(['service.id', 'service.sid', 'service.header'])->innerJoinWith('secs')->where(['sec_service.sid' => Yii::$app->request->get('section')])->orderBy($order)->offset($offset)->limit($limit)->all(); $pagination = new Pagination(['totalCount' => Service::find()->innerJoinWith('secs')->where(['sec_service.sid' => Yii::$app->request->get('section')])->count(), 'pageSize' => $limit]); } $sections = SecService::find()->asArray()->all(); $pagination->pageSizeParam = false; $page = Page::find()->where(['sid' => Yii::$app->controller->id])->select(['id', 'pid', 'sid', 'header'])->one(); $pages = Page::find()->select(['id', 'pid', 'sid', 'header'])->asArray()->indexBy('id')->all(); $mode = $pages[$page->id]; $branch[] = $mode; while (!is_null($mode['pid'])) { $mode = $pages[$mode['pid']]; $branch[] = $mode; } krsort($branch); $sectionsBySid = ArrayHelper::index($sections, 'sid'); if (!is_null(Yii::$app->request->get('section'))) { $branch[] = ['header' => $sectionsBySid[Yii::$app->request->get('section')]['header']]; } return $this->render('list', ['service' => $service, 'sections' => $sections, 'pagination' => $pagination, 'branch' => $branch]); }
public function getFile() { $src = $this->owner->{$this->srcAttrName}; if (Yii::$app->fs->has($src) === false) { $src = Yii::$app->getModule('image')->noImageSrc; $errorImage = ErrorImage::findOne(['img_id' => $this->owner->id, 'class_name' => $this->owner->className()]); if ($errorImage === null) { $errorImage = new ErrorImage(); $errorImage->setAttributes(['img_id' => $this->owner->id, 'class_name' => $this->owner->className()]); $errorImage->save(); } } else { $fs = Yii::$app->fs; $components = ArrayHelper::index(Yii::$app->getModule('image')->components, 'necessary.class'); $adapterName = ArrayHelper::getValue($components, $fs::className() . '.necessary.srcAdapter', null); if ($adapterName === null) { throw new HttpException(Yii::t('app', 'Set src compiler adapter')); } if (class_exists($adapterName) === false) { throw new HttpException(Yii::t('app', "Class {$adapterName} not found")); } $adapter = new $adapterName(); if ($adapter instanceof CompileSrcInterface) { $src = $adapter->CompileSrc($src); } else { throw new HttpException(Yii::t('app', "Class {$adapterName} should implement CompileSrcInterface")); } } return $src; }
public function internalUpdateRelations() { $_this = $this; $modelsChecked = []; $updateChildren = function ($model) use($_this, &$modelsChecked, &$updateChildren) { if (in_array($model->id, $modelsChecked)) { return true; } $modelsChecked[] = $model->id; $currentChildRelations = $model->queryChildRelations()->all(); $currentChildRelations = ArrayHelper::index($currentChildRelations, function ($relation) { return $relation->child_object_id; }); $childModels = $model->dataObject->childModelsFromObjects(); $baseRelation = ['parent_object_id' => $model->id, 'active' => 1]; $childRelations = []; foreach ($childModels as $childModel) { $updateChildren($childModel); if (isset($currentChildRelations[$childModel->id])) { unset($currentChildRelations[$childModel->id]); continue; } $childRelation = $baseRelation; $childRelation['child_object_id'] = $childModel->id; $childRelations[] = $childRelation; } $model->setRelationModels($childRelations); $model->save(); foreach ($currentChildRelations as $childRelation) { $childRelation->delete(); } }; return $updateChildren($this->model); }
/** * Handler for Good Movement created. * It used to update stock * @param \biz\core\base\Event $event */ public function goodsMovementApplied($event) { /* @var $model MGoodsMovement */ $model = $event->params[0]; /* * 200 = Sales */ if (!in_array($model->reff_type, [200])) { return; } $sales = MSales::findOne($model->reff_id); $salesDtls = ArrayHelper::index($sales->salesDtls, 'product_id'); // change total qty for reff document /* @var $purcDtl \biz\core\sales\models\SalesDtl */ foreach ($model->goodsMovementDtls as $detail) { $salesDtl = $salesDtls[$detail->product_id]; $salesDtl->total_release += $detail->qty; $salesDtl->save(false); } $complete = true; foreach ($salesDtls as $salesDtl) { if ($salesDtl->total_release != $salesDtl->qty) { $complete = false; break; } } if ($complete) { $sales->status = MSales::STATUS_COMPLETE_RELEASE; $sales->save(false); } elseif ($sales->status == MSales::STATUS_DRAFT) { $sales->status = MSales::STATUS_PARTIAL_RELEASE; $sales->save(false); } }
/** * Handler for Good Movement created. * It used to update stock * @param \biz\core\base\Event $event */ public function goodsMovementApplied($event) { /* @var $model MGoodsMovement */ $model = $event->params[0]; /* * 100 = Purchase */ if (!in_array($model->reff_type, [100])) { return; } $purchase = MPurchase::findOne($model->reff_id); $purchaseDtls = ArrayHelper::index($purchase->purchaseDtls, 'product_id'); // change total qty for reff document /* @var $purcDtl \biz\core\purchase\models\PurchaseDtl */ foreach ($model->goodsMovementDtls as $detail) { $purcDtl = $purchaseDtls[$detail->product_id]; $purcDtl->total_receive += $detail->qty; $purcDtl->save(false); } $complete = true; foreach ($purchaseDtls as $purcDtl) { if ($purcDtl->total_receive != $purcDtl->qty) { $complete = false; break; } } if ($complete) { $purchase->status = MPurchase::STATUS_PROCESS; $purchase->save(false); } elseif ($purchase->status == MPurchase::STATUS_DRAFT) { $purchase->status = MPurchase::STATUS_PROCESS; $purchase->save(false); } }
private function performSearch($team_name, $player_mail) { $res = array_merge($this->performNameSearch($team_name), $this->performPlayerMailSearch($player_mail)); // remove dublicates with same key(id) $res = yii\helpers\ArrayHelper::index($res, 'id'); return array_values($res); }
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); } }
/** * @param string $id * @param array $data * @param \biz\core\inventory\models\StockOpname $model * @return \biz\core\inventory\models\StockOpname */ public function append($id, $data, $model = null) { /* @var $model MStockOpname */ $model = $model ?: $this->findModel($id); $success = true; $model->scenario = MStockOpname::SCENARIO_DEFAULT; $model->load($data, ''); $this->fire('_append', [$model]); $success = $model->save(); $stockOpnameDtls = ArrayHelper::index($model->stockOpnameDtls, 'product_id'); foreach ($data['details'] as $dataDetail) { $index = $dataDetail['product_id']; // product_id if (isset($stockOpnameDtls[$index])) { $detail = $stockOpnameDtls[$index]; } else { $detail = new StockOpnameDtl(['id_opname' => $model->id_opname, 'product_id' => $dataDetail['product_id'], 'uom_id' => $dataDetail['uom_id'], 'qty' => 0]); } $detail->qty += $dataDetail['qty']; $success = $success && $detail->save(); $stockOpnameDtls[$index] = $detail; $this->fire('_append_body', [$model, $detail]); } $model->populateRelation('stockOpnameDtls', array_values($stockOpnameDtls)); if ($success) { $this->fire('_appended', [$model]); } return $this->processOutput($success, $model); }
public function __construct(array $config = []) { parent::__construct($config); if (isset($config['fields']) == false) { $this->fields = \yii\helpers\ArrayHelper::index(\Yii::$app->getModule('comments')->fields, 'name'); } $this->fields_names = \yii\helpers\ArrayHelper::getColumn($this->fields, 'name'); }
/** * @inheritdoc */ public function run() { if (is_null($this->date)) { $this->date = date('Y-m'); } $rows = (new Query())->select('COUNT(*) as count, DAY(date) as day')->from('{{%post}}')->where("DATE_FORMAT( DATE, '%Y-%m' ) = :month", [':month' => $this->date])->groupBy("DAY( `date` )")->all(); $rows = ArrayHelper::index($rows, 'day'); return $this->renderFile('@app/views/site/calendar.php', ['posts' => $rows, 'date' => $this->date, 'noControls' => $this->noControls]); }
public static function getRoots() { if (sizeof(self::$_roots)) { return self::$_roots; } $roots = Category::find()->where(['parentid' => 0])->all(); self::$_roots = ArrayHelper::index($roots, 'name'); return self::$_roots; }
/** * @return ActiveRecord[] */ protected function getTranslateRelations() { $records = $this->owner->getRelatedRecords(); if (!isset($records['currentTranslate']) && isset($records[$this->translateRelation])) { $translations = ArrayHelper::index($this->owner->{$this->translateRelation}, $this->languageAttribute); $this->setTranslateRelations($translations); } return $this->owner['currentTranslate']; }
/** * Reloads the system states from the database */ public function loadStates() { $sql = "SELECT `key`, `value` FROM `{$this->tableName}`"; $items = $this->getDb()->createCommand($sql)->queryAll(); $items = ArrayHelper::index($items, 'key'); foreach ($items as $key => $value) { $value = unserialize($value['value']); $this->map[$key] = $value; } $this->updateCache(); }
public static function cache($forceUpdate = false) { $key = "api_visitor_config"; $return = \yii::$app->cache->get($key); if ($return == null || $forceUpdate) { $data = self::find()->where(['is_closed' => 0])->asArray()->all(); $return = ArrayHelper::index($data, "type"); \yii::$app->cache->set($key, $return); } return $return; }
/** * 将ERP数据转换成云客字段 * @param type $erpData * @param type $serviceName * @return type */ public function convertToMyFields($erpData, $serviceName) { //return AsyncFields::convertToMyFields($this->orgcode, $erpData, $serviceName); $fieldMappings = $this->getFields($serviceName); $fieldMappings = \yii\helpers\ArrayHelper::index($fieldMappings, 'ErpField'); $result = []; foreach ($erpData as $row) { $newRow = $this->convertRowToMyFields($fieldMappings, $row); $result[] = $newRow; } return $result; }
public static function makeTree($records) { $tree = []; $records = \yii\helpers\ArrayHelper::index($records, 'id'); foreach ($records as $record) { if ($record['pid'] != 0 && isset($records[$record['pid']])) { $records[$record['pid']]['children'][] =& $records[$record['id']]; } else { $tree[] =& $records[$record['id']]; } } return $tree; }
protected function isGuestCan($permissionName) { /** @var DbManager $auth */ $auth = Yii::$app->getAuthManager(); if ($this->defaultRolesPermissions == null) { foreach ($auth->defaultRoles as $roleName) { $this->defaultRolesPermissions[$roleName] = ArrayHelper::index($auth->getPermissionsByRole($roleName), 'name'); } } foreach ($auth->defaultRoles as $roleName) { return isset($this->defaultRolesPermissions[$roleName][$permissionName]); } return false; }
public function getMetaData($issueTypeName) { $data = $this->client->get('issue/createmeta', ['projectKeys' => $this->key, 'expand' => 'projects.issuetypes.fields']); if (isset($data['projects'][0])) { $data = ArrayHelper::index($data['projects'][0]['issuetypes'], 'name'); } else { return []; } if (isset($data[$issueTypeName])) { return $data[$issueTypeName]; } else { return []; } }
public function refresh() { $this->getAuthManager()->removeAllPermissions(); $this->getAuthManager()->removeAllRoles(); $this->getAuthManager()->removeAllRules(); $this->setPermissions(ArrayHelper::index($this->getAuthManager()->getPermissions(), 'name')); $this->setRoles(ArrayHelper::index($this->getAuthManager()->getRoles(), 'name')); /** @var DefinitionManager $manager */ $manager = $this->get('definitionManager'); foreach ($manager->getDefinitions() as $id => $definition) { $this->mergeRules($definition); } $this->processRules(); }
/** * Handler for Good Movement created. * It used to update stock * @param \biz\core\base\Event $event */ public function goodsMovementApplied($event) { /* @var $model MGoodsMovement */ $model = $event->params[0]; /* * 300 = Transfer Release * 400 = Transfer Receive */ if (!in_array($model->reff_type, [300, 400])) { return; } $type = $model->type; $transfer = MTransfer::findOne($model->reff_id); $transferDtls = ArrayHelper::index($transfer->transferDtls, 'product_id'); // change total qty for reff document /* @var $transferDtl \biz\core\inventory\models\TransferDtl */ foreach ($model->goodsMovementDtls as $detail) { $transferDtl = $transferDtls[$detail->product_id]; if ($type == MGoodsMovement::TYPE_ISSUE) { $transferDtl->total_release += $detail->qty; } else { $transferDtl->total_receive += $detail->qty; } $transferDtl->save(false); } $complete = true; switch ($model->reff_type) { case '300': foreach ($transferDtls as $transferDtl) { if ($transferDtl->total_release != $transferDtl->qty) { $complete = false; break; } } $transfer->status = $complete ? MTransfer::STATUS_ISSUED : MTransfer::STATUS_PARTIAL_ISSUED; break; case '400': foreach ($transferDtls as $transferDtl) { if ($transferDtl->total_receive != $transferDtl->qty) { $complete = false; break; } } $transfer->status = $complete ? MTransfer::STATUS_RECEIVED : MTransfer::STATUS_PARTIAL_RECEIVED; break; } $transfer->save(false); }
/** * Merges two arrays using specified $on values * * @param array $array1 * @param array $array2 * @param array $on * @return array */ public static function merge($array1, $array2, $on) { list($on1, $on2) = each($on); $array2 = \yii\helpers\ArrayHelper::index($array2, $on2); foreach ($array1 as $k1 => $v1) { if (!array_key_exists($on1, $v1)) { continue; } $k2 = $v1[$on1]; if (isset($array2[$k2])) { $v2 = $array2[$k2]; $array1[$k1] = array_merge($v1, $v2); unset($array2[$k2]); } } foreach ($array2 as $v2) { $array1[] = $v2; } return $array1; }
/** * @param string|\Closure|array $key * @param Tag $model * @param bool $fast * * @return \Closure */ public function getTagsParser($key, Tag $model, $fast = false) { /** * @param $array * * @return \romkaChev\yandexFotki\models\Tag[] */ return function ($array) use($key, $model, $fast) { $login = $model->getYandexFotki()->getLogin(); $entries = ArrayHelper::getValue($array, $key, []); $models = []; foreach ($entries as $id => $linkSelf) { $localModel = clone $model; $localModel->id = mb_strtolower($id); $localModel->loadWithData(['id' => "urn:yandex:fotki:{$login}:tag:{$id}", 'urn' => $localModel->defaultUrn(), 'title' => $localModel->defaultTitle(), 'authors' => $localModel->defaultAuthors(), 'links' => ['self' => $localModel->defaultLinkSelf(), 'edit' => $localModel->defaultLinkEdit(), 'photos' => $localModel->defaultLinkPhotos(), 'alternate' => $localModel->defaultLinkAlternate()]], $fast); $models[] = $localModel; } return ArrayHelper::index($models, 'id'); }; }
/** * @param string|\Closure|array $key * @param Album $model * @param bool $fast * * @return \Closure */ public function getAlbumsParser($key, Album $model, $fast = false) { /** * @param $array * * @return \romkaChev\yandexFotki\models\Album[] */ return function ($array) use($key, $model, $fast) { $entries = ArrayHelper::getValue($array, $key); $models = []; foreach ($entries as $entry) { if ($entry instanceof Album) { $models[] = $entry; continue; } $localModel = clone $model; $localModel->loadWithData($entry, $fast); $models[] = $localModel; } return ArrayHelper::index($models, 'id'); }; }
public function __construct($id, array $config = []) { parent::__construct($config); if (($model = Comments::findOne($id)) === null) { throw new \yii\web\NotFoundHttpException('The requested page does not exist.'); } foreach ($model->attributes as $key => $value) { $this->{$key} = $value; } if ($model->commentsFields != null) { $commentFields = $model->commentsFields; $commentFields = ArrayHelper::index($commentFields, 'field_name'); } foreach (\Yii::$app->controller->module->fields as $field) { if (isset($commentFields[$field['name']])) { $this->fields[$field['name']] = array_merge($commentFields[$field['name']]->attributes, ['label' => $field['label'], 'fieldType' => isset($field['fieldType']) ? $field['fieldType'] : 'textInput', 'items' => isset($field['items']) ? $field['items'] : null]); } else { $this->fields[$field['name']] = ['comments_id' => $model->id, 'field_name' => $field['name'], 'value' => '', 'label' => $field['label'], 'fieldType' => isset($field['fieldType']) ? $field['fieldType'] : 'textInput', 'items' => isset($field['items']) ? $field['items'] : null]; } } $this->link = $model->commentsLink; }
public function actionStatsCoupon() { $params = $this->getQuery(); if (empty($params['id']) || !isset($params['startTime']) || !isset($params['endTime'])) { throw new BadRequestHttpException(Yii::t('common', 'parameters_missing')); } $id = new MongoId($params['id']); $couponLog = Coupon::findOne(["_id" => $id]); if (empty($couponLog)) { throw new BadRequestHttpException(Yii::t('product', 'membershipDiscount_is_deleted')); } //turn unix timestamp to string $startTime = TimeUtil::msTime2String($params['startTime'], 'Y-m-d'); $endTime = TimeUtil::msTime2String($params['endTime'], 'Y-m-d'); $couponPeriodInfo = StatsCouponLogDaily::getCouponLogStats($id, $startTime, $endTime); ArrayHelper::multisort($couponPeriodInfo, 'date', SORT_ASC); $dateCouPonStats = ArrayHelper::index($couponPeriodInfo, 'date'); $item = $redeemedNum = $recievedNum = $date = []; $startDate = strtotime($startTime); $endDate = strtotime($endTime); if (!empty($couponPeriodInfo) && count($couponPeriodInfo) > 0) { while ($startDate <= $endDate) { $dateStr = date('Y-m-d', $startDate); if (!empty($dateCouPonStats[$dateStr])) { $date[] = $dateStr; $recievedNum[] = $dateCouPonStats[$dateStr]['recievedNum']; $redeemedNum[] = $dateCouPonStats[$dateStr]['redeemedNum']; } else { $date[] = $dateStr; $recievedNum[] = 0; $redeemedNum[] = 0; } $startDate = strtotime($dateStr . ' +1 day'); } } $item = ['date' => $date, 'count' => ['recievedNum' => $recievedNum, 'redeemedNum' => $redeemedNum]]; return $item; }
/** * @param string|\Closure|array $key * @param Image $model * @param bool $fast * * @return \Closure */ public function getImagesParser($key, Image $model, $fast = false) { /** * @param $array * * @return \romkaChev\yandexFotki\models\Image[] */ return function ($array) use($key, $model, $fast) { $entries = ArrayHelper::getValue($array, $key, []); $models = []; foreach ($entries as $size => $entry) { if ($entry instanceof Image) { $models[] = $entry; continue; } $entry['size'] = $size; $localModel = clone $model; $localModel->loadWithData($entry, $fast); $models[] = $localModel; } return ArrayHelper::index($models, 'size'); }; }
/** * @title 取出所有菜单列表 */ public static function getList() { $auth = Yii::$app->authManager; $items = $auth->getPermissionsByUser(Yii::$app->user->id); $menus = self::find()->where(['status' => self::STATUS_ACTIVE])->orderBy('sort desc')->asArray()->all(); foreach ($menus as $k => &$v) { if (empty($v['auth_name'])) { continue; } $code = explode('_', $v['auth_name']); $v['url'] = Url::toRoute(['/' . $code[1] . '/' . $code[2]]); if (strpos($code[0], '@')) { $arr = explode('@', $code[0]); $code[0] = $arr[1]; $v['url'] = Url::toRoute(['/' . $code[0] . '/' . $code[1] . '/' . $code[2]]); } } unset($v); $menus = \yii\helpers\ArrayHelper::index($menus, 'id'); $menus = \backend\components\helpers\ArrayHelper::recursion($menus, 0, 1); // p($menus); return $menus; }
public static function append($id, $data, $model = null) { /* @var $model MStockOpname */ $model = $model ?: static::findModel($id); $e_name = static::prefixEventName(); $success = true; $model->scenario = MStockOpname::SCENARIO_DEFAULT; $model->load($data, ''); try { $transaction = Yii::$app->db->beginTransaction(); Yii::$app->trigger($e_name . '_append', new Event([$model])); $stockOpnameDtls = ArrayHelper::index($model->stockOpnameDtls, 'id_product'); foreach ($data['details'] as $dataDetail) { $index = $dataDetail['id_product']; // id_product if (isset($stockOpnameDtls[$index])) { $detail = $stockOpnameDtls[$index]; } else { $detail = new StockOpnameDtl(['id_opname' => $model->id_opname, 'id_product' => $dataDetail['id_product'], 'id_uom' => $dataDetail['id_uom'], 'qty' => 0]); } $detail->qty += $dataDetail['qty']; $success = $success && $detail->save(); $stockOpnameDtls[$index] = $detail; Yii::$app->trigger($e_name . '_append_body', new Event([$model, $detail])); } if ($success) { Yii::$app->trigger($e_name . '_appended', new Event([$model])); $transaction->commit(); } else { $transaction->rollBack(); } } catch (\Exception $exc) { $transaction->rollBack(); throw $exc; } return [$success, $model]; }
public static function recursion($arr, $pid = 0, $type = 1, $fid = 0, $level = 0) { switch ($type) { case 1: //组合多维数组 $arr = \yii\helpers\ArrayHelper::index($arr, 'id'); foreach ($arr as $item) { $arr[$item['pid']]['child'][$item['id']] =& $arr[$item['id']]; } return isset($arr[0]['child']) ? $arr[0]['child'] : array(); case 2: //组合一维数组,菜单下拉选择形式 static $array = array(); static $i = -1; $i++; foreach ($arr as $v) { if ($v['pid'] == $pid) { $array[$i] = $v; $array[$i]['lv'] = $level; $array[$i]['html'] = str_repeat('--', $level); static::recursion($arr, $v['id'], $type, $fid, $level + 1); } } return $array; case 3: //传递分类ID返回所有父级 static $array = array(); foreach ($arr as $v) { if ($v['id'] == $fid) { $array[$v['id']] = $v; static::recursion($arr, $pid, $type, $v['pid']); } } return array_reverse($array); } }
/** * @param int $groupPosition * @return array */ public function getRows($groupPosition) { $rows = []; $columns = $this->getAllAggregationColumns(); if ($groupPosition == Group::GROUP_VERTICAL) { foreach ($this->arrayIterator as $current) { $cols = [$this->getRealEntityName((int) $current['key'])]; foreach ($columns as $aggrIndex => $aggrFieldNames) { $aggregationData = $this->extractDataFromAggregation($aggrIndex, $aggrFieldNames, $current); foreach ($aggregationData as $value) { array_push($cols, $value); } } $rows[] = $cols; } } else { $assocAggregationList = ArrayHelper::index($this->aggregationList, 'index'); foreach ($columns as $aggrIndex => $aggrFieldNames) { $rows[] = ['colspan' => $this->arrayIterator->count() + 1, 'value' => $assocAggregationList[$aggrIndex]['title']]; foreach ($aggrFieldNames as $fieldName) { $cols = [$fieldName]; foreach ($this->arrayIterator as $current) { $cols[] = $this->findValue($current[$aggrIndex], $fieldName); } $rows[] = $cols; } } } $this->arrayIterator->rewind(); return $rows; }