/** * Search page and article by url(page: shortUrl, article: url) and name(page: title, article: name) * 1. Get data from page collection and article collection * 2. Merge page and article * 3. Sort by createdAt * 4. Format and return */ public function actionIndex() { $query = $this->getQuery(); $pageSize = $this->getQuery('per-page', 10); $accountId = $this->getAccountId(); $timeFrom = null; $searchKey = isset($query['searchKey']) && $query['searchKey'] !== '' ? $query['searchKey'] : null; $searchKey = urldecode($searchKey); if (isset($query['timeFrom']) && $query['timeFrom'] !== '') { $timeFrom = MongodbUtil::msTimetamp2MongoDate($query['timeFrom']); } //Get data from page collection and article collection $pages = Page::searchByTitleAndUrl($accountId, $pageSize, $searchKey, $timeFrom); $articles = Article::searchByNameAndUrl($accountId, $pageSize, $searchKey, $timeFrom); //Merge page and article and sort $pageAndArticle = array_merge($pages, $articles); usort($pageAndArticle, 'self::cmpCreatedAt'); $result = []; $items = []; $result['timeFrom'] = null; $rowIndex = 0; //format data foreach ($pageAndArticle as $item) { $items[] = ['id' => (string) $item['_id'], 'title' => !isset($item['title']) ? $item['name'] : $item['title'], 'url' => empty($item['shortUrl']) ? $item['url'] : $item['shortUrl'], 'type' => !isset($item['title']) ? 'article' : 'page']; $result['timeFrom'] = MongodbUtil::MongoDate2msTimeStamp($item['createdAt']); $rowIndex++; if ($rowIndex >= $pageSize) { break; } } $result['items'] = $items; return $result; }