/**
  * @inheritdoc
  */
 public function apply($model)
 {
     if ($this->isDue() && in_array($model->ClassID, [6, 12])) {
         $userID = $model->contractor->id;
         \Yii::info('Проверка и применение акции "' . self::$name . '"' . "({$this->getModel()->id})" . ' для пользователя ' . Html::a($userID, ['/user/admin/update', 'id' => $userID]), 'info');
         $settings = $this->getModel()->parseSettings();
         if (empty($settings['attributes'])) {
             return false;
         }
         ArrayHelper::multisort($settings['attributes'], 'payment', SORT_DESC);
         $account = $model->contractor->account;
         foreach ($settings['attributes'] as $attributes) {
             $discount = $this->getModel()->getDiscount();
             $discount->setAttributes($attributes);
             if ($model->CashSum >= $discount->payment) {
                 \Yii::info('Применение акции с атрибутами: ' . Json::encode($attributes), 'info');
                 $account->BonusGames = $account->BonusGames + $discount->bonusGamesCount;
                 if ($account->save(false, ['BonusGames'])) {
                     $finance = new FinanceRecord();
                     $finance->CashSum = 0;
                     $finance->ClassID = 21;
                     //Начисление бонусов
                     $finance->ContractorID = $model->ContractorID;
                     $finance->Comment = $this->getDescription();
                     $finance->save();
                     return true;
                 }
             }
         }
     } else {
         //            var_export(in_array($model->ClassID, [6, 12]));
     }
     return false;
 }
Esempio n. 2
0
 /**
  * Applies sort for given data.
  * @param array $data raw data.
  * @param array|null $orderBy order by.
  * @return array sorted data.
  */
 public function applyOrderBy(array $data, $orderBy)
 {
     if (!empty($orderBy)) {
         ArrayHelper::multisort($data, array_keys($orderBy), array_values($orderBy));
     }
     return $data;
 }
Esempio n. 3
0
 public function getMergedConfig($modNames)
 {
     $result = ['menus' => [], 'mods' => []];
     if (!empty($modNames)) {
         $modulesDIR = Yii::getAlias('@backend') . DIRECTORY_SEPARATOR . 'modules';
         $modulesPath = realpath($modulesDIR);
         foreach ($modNames as $modName) {
             $configPath = $modulesPath . DIRECTORY_SEPARATOR . $modName . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'main.php';
             if (is_file($configPath)) {
                 $moduleConfig = (require $configPath);
                 if (isset($moduleConfig['menusConfig']) && !empty($moduleConfig['menusConfig'])) {
                     foreach ($moduleConfig['menusConfig'] as $moduleName => $moduleItems) {
                         if (!isset($result['menus'][$moduleName])) {
                             $result['menus'][$moduleName] = [];
                         }
                         $result['menus'][$moduleName] = ArrayHelper::merge($result['menus'][$moduleName], $moduleItems);
                     }
                 }
                 if (isset($moduleConfig['isInTopNav']) && $moduleConfig['isInTopNav']) {
                     $result['mods'][] = ['name' => $moduleConfig['name'], 'isCore' => $moduleConfig['isCore'], 'order' => $moduleConfig['order']];
                 }
             }
         }
         foreach ($result['menus'] as &$moduleItems) {
             ArrayHelper::multisort($moduleItems, 'order', SORT_ASC);
         }
         ArrayHelper::multisort($result['mods'], 'order', SORT_ASC);
     }
     return $result;
 }
 public function up()
 {
     $users = \bubasuma\simplechat\db\demo\User::find()->select(['id'])->asArray()->all();
     $data = (require __DIR__ . '/data/messages.php');
     $count = count($data);
     $messages = [];
     try {
         for ($i = 1; $i <= 10000; $i++) {
             shuffle($users);
             $sender = $users[0];
             $receiver = $users[1];
             $messages[] = ['sender_id' => $sender['id'], 'receiver_id' => $receiver['id'], 'created_at' => (new \DateTime())->sub(new \DateInterval('P' . mt_rand() % 500 . 'DT' . mt_rand() % 86400 . 'S'))->getTimestamp(), 'text' => $data[mt_rand(0, $count - 1)]];
         }
         ArrayHelper::multisort($messages, 'created_at', SORT_ASC, SORT_NUMERIC);
         foreach ($messages as $message) {
             $new = new \bubasuma\simplechat\db\demo\Message();
             $new->sender_id = $message['sender_id'];
             $new->receiver_id = $message['receiver_id'];
             $new->text = $message['text'];
             $new->is_new = 0;
             $new->created_at = date('Y-m-d H:i:s', $message['created_at']);
             $new->save();
         }
         return true;
     } catch (\yii\base\Exception $e) {
         return false;
     }
 }
Esempio n. 5
0
File: Menu.php Progetto: Liv1020/cms
 public function getData()
 {
     \Yii::beginProfile('admin-menu');
     if ($this->isLoaded) {
         return (array) $this->groups;
     }
     $paths[] = \Yii::getAlias('@common/config/admin/menu.php');
     $paths[] = \Yii::getAlias('@app/config/admin/menu.php');
     foreach (\Yii::$app->extensions as $code => $data) {
         if ($data['alias']) {
             foreach ($data['alias'] as $code => $path) {
                 $adminMenuFile = $path . '/config/admin/menu.php';
                 if (file_exists($adminMenuFile)) {
                     $menuGroups = (array) (include_once $adminMenuFile);
                     $this->groups = ArrayHelper::merge($this->groups, $menuGroups);
                 }
             }
         }
     }
     foreach ($paths as $path) {
         if (file_exists($path)) {
             $menuGroups = (array) (include_once $path);
             $this->groups = ArrayHelper::merge($this->groups, $menuGroups);
         }
     }
     ArrayHelper::multisort($this->groups, 'priority');
     $this->isLoaded = true;
     \Yii::endProfile('admin-menu');
     return (array) $this->groups;
 }
Esempio n. 6
0
 /**
  * 设置菜单(如果菜单已存在则覆盖)
  * ~~~
  * Menu::set('user.name', [
  *     'label' => '用户列表',
  *     'url' => ['/user/admin/user/index'],
  *     'icon' => 'fa-user',
  *     'priority' => 9
  * ]);
  * ~~~
  * @param $menuKey 可以多级设置.最多设置二级
  * @param array $options 菜单设置
  * @return mixed
  * @throws \yii\base\InvalidConfigException
  */
 public static function set($menuKey, array $options)
 {
     $menuKeys = explode('.', $menuKey);
     if (count($menuKeys) > 2) {
         throw new InvalidConfigException("Can only support 2 levels of menus");
         // 最多只能支持二级菜单
     }
     $menus = static::get();
     $_menu =& $menus;
     while (count($menuKeys) > 1) {
         $menuKey = array_shift($menuKeys);
         if (!isset($_menu[$menuKey]) || !is_array($_menu[$menuKey])) {
             $_menu[$menuKey] = ['label' => $menuKey, 'priority' => 100];
         }
         if (!isset($_menu[$menuKey]['items'])) {
             $_menu[$menuKey]['items'] = [];
         }
         $_menu =& $_menu[$menuKey]['items'];
     }
     $menuKey = array_shift($menuKeys);
     $_menu[$menuKey] = array_merge(isset($_menu[$menuKey]) ? $_menu[$menuKey] : [], array_merge(['label' => ArrayHelper::remove($options, 'label', $menuKey), 'url' => ArrayHelper::remove($options, 'url'), 'priority' => ArrayHelper::remove($options, 'priority', 10)], $options));
     ArrayHelper::multisort($_menu, 'priority');
     // 排序
     return Yii::$app->get('config')->set(static::MENU_BASE_KEY, $menus);
 }
Esempio n. 7
0
 public static function getLanguagesArray()
 {
     $yiiLanguages = ['ar', 'az', 'bg', 'ca', 'cs', 'da', 'de', 'el', 'es', 'et', 'fa', 'fi', 'fr', 'he', 'hu', 'id', 'it', 'ja', 'kk', 'ko', 'lt', 'lv', 'ms', 'nl', 'pl', 'pt', 'pt-BR', 'ro', 'ru', 'sk', 'sl', 'sr', 'sr-Latn', 'sv', 'th', 'tj', 'tr', 'uk', 'vi', 'zh-CN', 'zh-TW', 'en-US'];
     $dotPlantLanguages = ['en-US', 'ru', 'zh-CN'];
     $result = [];
     foreach ($yiiLanguages as $lang) {
         $result[] = ['language' => $lang, 'translated' => in_array($lang, $dotPlantLanguages)];
     }
     ArrayHelper::multisort($result, 'translated', SORT_DESC);
     return $result;
 }
Esempio n. 8
0
 public function actionProgram($id)
 {
     /* @var $model \common\models\Program */
     Yii::$app->response->format = Response::FORMAT_JSON;
     $programs = [];
     $models = Program::find()->where(['id_faculty' => $id])->all();
     foreach ($models as $model) {
         $programs[] = $model->toArray(['id'], ['fullName']);
     }
     ArrayHelper::multisort($programs, 'fullName');
     return $programs;
 }
Esempio n. 9
0
 /**
  * Get all of the time zones with the offsets sorted by their offset
  *
  * @return array
  */
 public static function getAll()
 {
     $timeZones = [];
     $timeZoneIdentifiers = \DateTimeZone::listIdentifiers();
     foreach ($timeZoneIdentifiers as $timeZone) {
         $date = new \DateTime('now', new \DateTimeZone($timeZone));
         $offset = $date->getOffset() / 60 / 60;
         $timeZones[] = ['timezone' => $timeZone, 'name' => "{$timeZone} (UTC " . ($offset > 0 ? '+' : '') . "{$offset})", 'offset' => $offset];
     }
     \yii\helpers\ArrayHelper::multisort($timeZones, 'offset', SORT_DESC, SORT_NUMERIC);
     return $timeZones;
 }
Esempio n. 10
0
 /**
  * Get all of the time zones with the offsets sorted by their offset
  * @return array
  */
 public static function getAll()
 {
     $timezones = [];
     $identifiers = DateTimeZone::listIdentifiers();
     foreach ($identifiers as $identifier) {
         $date = new DateTime("now", new DateTimeZone($identifier));
         $offsetText = $date->format("P");
         $offsetInHours = $date->getOffset() / 60 / 60;
         $timezones[] = ["identifier" => $identifier, "name" => "(GMT{$offsetText}) {$identifier}", "offset" => $offsetInHours];
     }
     ArrayHelper::multisort($timezones, "offset", SORT_ASC, SORT_NUMERIC);
     return $timezones;
 }
Esempio n. 11
0
 public static function getSoureListByNear(Town $town)
 {
     $rawSources = Source::find()->all();
     $sources = [];
     foreach ($rawSources as $source) {
         $source->distance = $source->totalDistance($town);
         $sources[] = $source;
     }
     ArrayHelper::multisort($sources, function ($source) {
         return $source->distance;
     });
     return $sources;
 }
Esempio n. 12
0
 public function run($logId, $tag)
 {
     $this->controller->loadData($tag);
     $timings = $this->panel->calculateTimings();
     ArrayHelper::multisort($timings, 3, SORT_DESC);
     if (!isset($timings[$logId])) {
         throw new HttpException(404, 'Log message not found.');
     }
     $message = $timings[$logId][1];
     if (($pos = mb_strpos($message, "#")) !== false) {
         $url = mb_substr($message, 0, $pos);
         $body = mb_substr($message, $pos + 1);
     } else {
         $url = $message;
         $body = null;
     }
     list($dbname, $action) = explode('.', $url);
     /* @var $db Database */
     $db = Yii::$app->get($this->com)->getDatabase($dbname);
     $time = microtime(true);
     switch ($action) {
         case 'findAll':
             $docs = $db->getSearch()->setLimit(3)->setQuery($body)->search();
             $result = '<strong>Estimated Matched: </strong>' . $db->getLastCount();
             foreach ($docs as $doc) {
                 $result .= '<br/>' . $doc->rank() . '. (' . $doc->percent() . '%)';
                 $result .= "<br/>" . Json::encode($doc->getFields(), 448) . "\n";
             }
             if ($db->getLastCount() > 3) {
                 $result .= '<br/> ... other ' . ($db->getLastCount() - 3) . ' results ...';
             }
             break;
         case 'findOne':
             $docs = $db->getSearch()->setLimit(1)->setQuery($body)->search();
             if (count($docs) === 0) {
                 $result = '<span class="label label-danger">no found</span>';
             } else {
                 $result = "<br/>\n" . Json::encode($docs[0]->getFields(), 448);
             }
             break;
         case 'count':
             $count = $db->getSearch()->setQuery($body)->count();
             $result = '<strong>Estimated Matched: </strong>' . $count;
             break;
         default:
             throw new NotSupportedException("Action '{$action}' is not supported by xunsearch.");
     }
     $result = '<strong>DB Total: </strong>' . $db->getDbTotal() . '<br/>' . '<strong>Parsed Query: </strong>' . $db->getQuery() . '<br/>' . $result;
     Yii::$app->response->format = Response::FORMAT_JSON;
     return ['time' => sprintf('%.1f ms', (microtime(true) - $time) * 1000), 'result' => $result];
 }
Esempio n. 13
0
 public function run($logId, $tag)
 {
     $this->controller->loadData($tag);
     $timings = $this->panel->calculateTimings();
     ArrayHelper::multisort($timings, 3, SORT_DESC);
     if (!isset($timings[$logId])) {
         throw new HttpException(404, 'Log message not found.');
     }
     $message = $timings[$logId][1];
     if (($pos = mb_strpos($message, "#")) !== false) {
         $url = mb_substr($message, 0, $pos);
         $body = mb_substr($message, $pos + 1);
     } else {
         $url = $message;
         $body = null;
     }
     $method = mb_substr($url, 0, $pos = mb_strpos($url, ' '));
     $url = mb_substr($url, $pos + 1);
     $options = ['pretty' => true];
     /* @var $db Connection */
     $db = \Yii::$app->get($this->db);
     $time = microtime(true);
     switch ($method) {
         case 'GET':
             $result = $db->get($url, $options, $body, true);
             break;
         case 'POST':
             $result = $db->post($url, $options, $body, true);
             break;
         case 'PUT':
             $result = $db->put($url, $options, $body, true);
             break;
         case 'DELETE':
             $result = $db->delete($url, $options, $body, true);
             break;
         case 'HEAD':
             $result = $db->head($url, $options, $body);
             break;
         default:
             throw new NotSupportedException("Request method '{$method}' is not supported by elasticsearch.");
     }
     $time = microtime(true) - $time;
     if ($result === true) {
         $result = '<span class="label label-success">success</span>';
     } elseif ($result === false) {
         $result = '<span class="label label-danger">no success</span>';
     }
     Yii::$app->response->format = Response::FORMAT_JSON;
     return ['time' => sprintf('%.1f ms', $time * 1000), 'result' => $result];
 }
Esempio n. 14
0
 public function run()
 {
     $xml = @simplexml_load_file($this->channel);
     if ($xml === false) {
         die('Error parse Rss: ' . $rss);
     }
     $items = [];
     foreach ($xml->xpath('//item') as $item) {
         $items[] = $item;
     }
     ArrayHelper::multisort($items, function ($item) {
         return $item->pubDate;
     }, SORT_DESC);
     $provider = new ArrayDataProvider(['allModels' => $items, 'pagination' => ['pageSize' => $this->pageSize]]);
     return $this->render('wrap', ['provider' => $provider]);
 }
 /**
  * Fetches TOP-$count components from Bower ans saves to `config/bower.list`.
  *
  * @param int $count
  * @param bool $skipCache
  */
 public function actionFetchTop($count = 1000, $skipCache = false)
 {
     $result = [];
     $components = $this->getComponents($skipCache);
     ArrayHelper::multisort($components, 'stars', SORT_DESC, SORT_NUMERIC);
     foreach (array_slice($components, 0, $count) as $component) {
         $result[] = 'bower-asset/' . $component['name'];
         echo Console::renderColoredString("%R{$component['stars']}%N - %g{$component['name']}%N");
         Console::moveCursorTo(0);
         Console::clearLine();
     }
     $componentsListPath = Yii::getAlias('@hiqdev/assetpackagist/config/bower.list');
     file_put_contents($componentsListPath, implode("\n", $result));
     echo Console::renderColoredString('Fetched %YBower%N components list. Found %G' . count($components) . "%N components.\n");
     echo Console::renderColoredString('Only %bTOP-' . $count . "%N components were added to the packages list.\n");
     echo Console::renderColoredString('See %G' . $componentsListPath . "%N\n");
 }
Esempio n. 16
0
 /**
  * @param $logId
  * @param $tag
  * @return array
  * @throws HttpException
  * @throws NotSupportedException
  * @throws \yii\base\InvalidConfigException
  * @throws \yii\web\NotFoundHttpException
  */
 public function run($logId, $tag)
 {
     $this->controller->loadData($tag);
     $timings = $this->panel->calculateTimings();
     ArrayHelper::multisort($timings, 3, SORT_DESC);
     if (!isset($timings[$logId])) {
         throw new HttpException(404, 'Log message not found.');
     }
     $message = $timings[$logId][1];
     if (($pos = mb_strpos($message, '#')) !== false) {
         $url = mb_substr($message, 0, $pos);
         $body = mb_substr($message, $pos + 1);
     } else {
         $url = $message;
         $body = null;
     }
     $method = mb_substr($url, 0, $pos = mb_strpos($url, ' '));
     $url = mb_substr($url, $pos + 1);
     parse_str($body, $options);
     /* @var $db Connection */
     $db = \Yii::$app->get($this->db);
     $time = microtime(true);
     switch ($method) {
         case 'GET':
             $result = $db->get($url, $options, $body, true);
             break;
         case 'POST':
             $result = $db->post($url, $options, $body, true);
             break;
         case 'PUT':
             $result = $db->put($url, $options, $body, true);
             break;
         case 'DELETE':
             $result = $db->delete($url, $options, $body, true);
             break;
         case 'HEAD':
             $result = $db->head($url, $options, $body);
             break;
         default:
             throw new NotSupportedException("Request method '{$method}' is not supported by HiArt.");
     }
     $time = microtime(true) - $time;
     $now = microtime(true);
     Yii::$app->response->format = Response::FORMAT_JSON;
     return ['time' => date('H:i:s.', $now) . sprintf('%03d', (int) (($now - (int) $now) * 1000)), 'duration' => sprintf('%.1f ms', $time * 1000), 'result' => $result];
 }
Esempio n. 17
0
 public function filter($counties, $field)
 {
     $query = (new \yii\db\Query())->select(['company'])->from('job')->where(['county_id' => $counties]);
     if ($field) {
         $query->andWhere(['like', 'job_field_id', $field]);
     }
     $query = $query->all();
     $companies = ArrayHelper::getColumn($query, 'company');
     $companies = array_count_values($companies);
     $openCount = array();
     foreach ($companies as $comp => $count) {
         $temp = [['company' => $comp, 'openings' => $count]];
         $openCount = array_merge($openCount, $temp);
     }
     ArrayHelper::multisort($openCount, ['openings'], [SORT_DESC]);
     $dataProvider = new ArrayDataProvider(['allModels' => $openCount, 'pagination' => ['pageSize' => 5]]);
     return $dataProvider;
 }
Esempio n. 18
0
 /**
  * Displays a single Assignment model.
  * @param  integer $id
  * @return mixed
  */
 public function actionView($id)
 {
     $class = $this->module->userClassName;
     $model = $class::findIdentity($id);
     if ($model === null) {
         throw new NotFoundHttpException('The requested page does not exist.');
     }
     $manager = Yii::$app->getAuthManager();
     $usernameField = $this->module->usernameField;
     $items = array_filter(array_merge($manager->getRoles(), $manager->getPermissions()), function ($item) {
         return $item->name[0] !== '/';
     });
     $assignment = [];
     foreach ($manager->getAssignments($id) as $item) {
         $assignment[] = $items[$item->roleName];
         unset($items[$item->roleName]);
     }
     ArrayHelper::multisort($assignment, ['type', 'name']);
     return ['id' => $id, 'username' => $model->{$usernameField}, 'assignments' => $assignment, 'avaliables' => array_values($items)];
 }
Esempio n. 19
0
 public function init()
 {
     parent::init();
     $methodName = 'getAdminMenu';
     foreach (Yii::$app->modules as $id => $module) {
         if ($module instanceof IAdminModule) {
             $this->items[$id] = $module::getAdminMenu();
         } elseif (is_array($module) && isset($module['class']) && method_exists($module['class'], $methodName)) {
             $reflection = new \ReflectionMethod($module['class'], $methodName);
             if ($reflection->isStatic() && $reflection->isPublic()) {
                 $this->items[$id] = call_user_func(array($module['class'], $methodName));
             }
         }
     }
     ArrayHelper::multisort($this->items, 'order');
     /** @var $builder IMenuBuilder */
     if (($builder = Yii::$app->getModule('admin')->get('menuBuilder', false)) !== null) {
         $this->items = $builder->build($this->items);
     }
 }
Esempio n. 20
0
 /**
  * @inheritdoc
  */
 public function load()
 {
     $this->resetTable();
     $this->data = [];
     $table = $this->getTableSchema();
     $data = $this->getData();
     $users = User::find()->select(['id'])->column();
     if (count($users) >= 2) {
         ArrayHelper::multisort($data, 'timestamp', SORT_ASC, SORT_NUMERIC);
         foreach ($data as $alias => $row) {
             shuffle($users);
             $row['sender_id'] = $users[0];
             $row['receiver_id'] = $users[1];
             $row['created_at'] = date('Y-m-d H:i:s', $row['timestamp']);
             unset($row['timestamp']);
             $primaryKeys = $this->db->schema->insert($table->fullName, $row);
             $this->data[$alias] = array_merge($row, $primaryKeys);
         }
     }
 }
Esempio n. 21
0
 public function run()
 {
     try {
         $items = [];
         $xml = simplexml_load_file($this->channel);
         // suppress errors if feed is invalid
         if ($xml === false) {
             return 'Error parsing feed source: ' . $this->channel;
         }
         foreach ($xml->{$this->indexName} as $item) {
             $items[] = $item;
         }
         \yii\helpers\ArrayHelper::multisort($items, function ($item) {
             return $item->published;
         }, SORT_ASC);
         // return data to VW as dataProvider
         return $this->render('wrap', ['dataProvider' => new \yii\data\ArrayDataProvider(['allModels' => $items, 'pagination' => ['pageSize' => $this->pageSize]])]);
     } catch (\Exception $e) {
         return $e->getMessage();
     }
 }
Esempio n. 22
0
 public function actionIndex()
 {
     $path = $this->model->path;
     $dataArray = array();
     $list_files = glob($path . '*.sql');
     if ($list_files) {
         $list = array_map('basename', $list_files);
         sort($list);
         foreach ($list as $id => $filename) {
             $columns = array();
             $columns['id'] = $id;
             $columns['name'] = basename($filename);
             $columns['size'] = filesize($path . $filename);
             $columns['create_time'] = date('Y-m-d H:i:s', filectime($path . $filename));
             $columns['modified_time'] = date('Y-m-d H:i:s', filemtime($path . $filename));
             $dataArray[] = $columns;
         }
     }
     \yii\helpers\ArrayHelper::multisort($dataArray, ['create_time'], [SORT_DESC]);
     $dataProvider = new ArrayDataProvider(['allModels' => $dataArray]);
     return $this->render('index', ['dataProvider' => $dataProvider]);
 }
Esempio n. 23
0
 /**
  * 添加菜单(如果菜单已存在则覆盖)
  * @param $name 菜单键值
  * @param $link
  * @param array $options
  */
 public static function addMenu($menuKey, $link, $title = null, array $options = [])
 {
     $menus = static::getMenu();
     $menu = ['link' => $link, 'title' => $title ?: $menuKey, 'icon' => isset($options['icon']) ? $options['icon'] : 'fa-gear', 'priority' => isset($options['priority']) ? (int) $options['priority'] : 10];
     if (isset($options['parent'])) {
         //子菜单
         if (!array_key_exists($options['parent'], $menus)) {
             throw new InvalidConfigException("The menu {$options['parent']} is not exists, Can't set submenu.");
         }
         $menus[$options['parent']]['submenu'][$menuKey] = $menu;
         ArrayHelper::multisort($menus[$options['parent']]['submenu'], 'priority');
         // 子菜单排序
     } else {
         $menu['subShow'] = isset($options['subShow']) && $options['subShow'] !== false;
         // 是否在子菜单显示
         !isset($menus[$menuKey]) && ($menus[$menuKey] = []);
         $menus[$menuKey] = array_merge($menus[$menuKey], $menu);
         ArrayHelper::multisort($menus[$menuKey], 'priority');
         // 菜单排序
     }
     return static::setMenu($menus);
 }
Esempio n. 24
0
 public static function DialogList($user)
 {
     $query = Message::find()->where(['and', "sender_id={$user}", "recipient_id!={$user}"])->orWhere(['and', "sender_id!={$user}", "recipient_id={$user}"]);
     $message_list = new ActiveDataProvider(['query' => $query]);
     $message_list->query->orderBy(['datetime' => SORT_DESC, 'id' => SORT_DESC]);
     $count = $message_list->count;
     $messages = $message_list->getModels();
     $dialog_list = array();
     foreach ($messages as $message) {
         if ($message->sender_id == Yii::$app->user->id) {
             $dialog_list[$message->recipient_id][] = $message;
         } elseif ($message->recipient_id == Yii::$app->user->id) {
             $dialog_list[$message->sender_id][] = $message;
         }
     }
     ArrayHelper::multisort($dialog_list, ['id'], SORT_DESC);
     $result = array();
     foreach ($dialog_list as $dialog) {
         $result[] = $dialog[0];
     }
     return $result;
 }
 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;
 }
Esempio n. 26
0
 public function testMultisortUseSort()
 {
     // single key
     $sort = new Sort(['attributes' => ['name', 'age'], 'defaultOrder' => ['name' => SORT_ASC]]);
     $orders = $sort->getOrders();
     $array = [['name' => 'b', 'age' => 3], ['name' => 'a', 'age' => 1], ['name' => 'c', 'age' => 2]];
     ArrayHelper::multisort($array, array_keys($orders), array_values($orders));
     $this->assertEquals(['name' => 'a', 'age' => 1], $array[0]);
     $this->assertEquals(['name' => 'b', 'age' => 3], $array[1]);
     $this->assertEquals(['name' => 'c', 'age' => 2], $array[2]);
     // multiple keys
     $sort = new Sort(['attributes' => ['name', 'age'], 'defaultOrder' => ['name' => SORT_ASC, 'age' => SORT_DESC]]);
     $orders = $sort->getOrders();
     $array = [['name' => 'b', 'age' => 3], ['name' => 'a', 'age' => 2], ['name' => 'a', 'age' => 1]];
     ArrayHelper::multisort($array, array_keys($orders), array_values($orders));
     $this->assertEquals(['name' => 'a', 'age' => 2], $array[0]);
     $this->assertEquals(['name' => 'a', 'age' => 1], $array[1]);
     $this->assertEquals(['name' => 'b', 'age' => 3], $array[2]);
 }
Esempio n. 27
0
 public function actionLearn()
 {
     $data = [['age' => 30, 'name' => 'Alexander'], ['age' => 30, 'name' => 'Brian'], ['age' => 19, 'name' => 'Barney']];
     ArrayHelper::multisort($data, ['age', 'name'], [SORT_ASC, SORT_DESC]);
     var_dump($data);
 }
 /**
  * Sorts the data models according to the given sort definition
  *
  * @param array $models the models to be sorted
  * @param \yii\data\Sort  $sort   the sort definition
  *
  * @return array the sorted data models
  */
 protected function sortModels($models, $sort)
 {
     $orders = $sort->getOrders();
     if (!empty($orders)) {
         ArrayHelper::multisort($models, array_keys($orders), array_values($orders));
     }
     return $models;
 }
Esempio n. 29
0
 /**
  * get coupon about store from mobile
  * note: mobile only get some special modules
  */
 public function actionCouponStore()
 {
     $params = $this->getQuery();
     if (empty($params['couponId'])) {
         throw new InvalidParameterException(Yii::t('common', 'parameters_missing'));
     }
     $couponId = new MongoId($params['couponId']);
     $coupon = Coupon::findByPk($couponId);
     if (!empty($coupon)) {
         if ($coupon->storeType == Coupon::COUPON_ALL_STORE) {
             $stores = Store::find()->where(['accountId' => $coupon->accountId, 'isDeleted' => Coupon::NOT_DELETED])->orderBy(['_id' => SORT_DESC])->all();
             $coupon->stores = Coupon::conver2couponStore($stores);
         } else {
             if (!empty($coupon->stores)) {
                 foreach ($stores = $coupon->stores as &$store) {
                     $store['id'] = (string) $store['id'];
                 }
                 ArrayHelper::multisort($stores, 'id', SORT_DESC);
                 $coupon->stores = $stores;
             }
         }
     }
     return $coupon;
 }
Esempio n. 30
0
<?php

use yii\apidoc\helpers\ApiMarkdown;
use yii\apidoc\models\ClassDoc;
use yii\helpers\ArrayHelper;
/**
 * @var ClassDoc $type
 * @var yii\web\View $this
 * @var \yii\apidoc\templates\html\ApiRenderer $renderer
 */
$renderer = $this->context;
if (empty($type->events)) {
    return;
}
$events = $type->events;
ArrayHelper::multisort($events, 'name');
?>
<div class="summary doc-event">
    <h2>Events</h2>

    <p><a href="#" class="toggle">Hide inherited events</a></p>

    <table class="summary-table table table-striped table-bordered table-hover">
    <colgroup>
        <col class="col-event" />
        <col class="col-type" />
        <col class="col-description" />
        <col class="col-defined" />
    </colgroup>
    <tr>
        <th>Event</th><th>Type</th><th>Description</th><th>Defined By</th>