ArticleQuery.php 1.66 KB
<?php

namespace FootyRoom\Queries\Article;

use MongoDB\BSON\ObjectId;
use FootyRoom\Support\AutoMapper;
use FootyRoom\Support\MongoClient;

class ArticleQuery
{
    /** @var \FootyRoom\Support\MongoClient */
    protected $mongo;

    public function __construct(MongoClient $mongo)
    {
        $this->mongo = $mongo;
    }

    /**
     * @return \FootyRoom\Queries\Article\Article[]
     */
    public function find(int $limit, int $offset = 0): array
    {
        return $this->findBy([], $limit, $offset);
    }

    /**
     * @return \FootyRoom\Queries\Article\Article[]
     */
    public function findPublished(int $limit, int $offset = 0): array
    {
        return $this->findBy(['status' => 'published'], $limit, $offset);
    }

    public function findOne(string $id): ?Article
    {
        $article = $this->mongo->footyroom->articles->findOne(['_id' => new ObjectId($id)]);

        if (!$article) {
            return null;
        }

        $article->id = (string) $article->_id;

        $article = AutoMapper::map($article, Article::class);

        return $article;
    }

    /**
     * @return \FootyRoom\Queries\Article\Article[]
     */
    private function findBy($query, int $limit, int $offset = 0): array
    {
        $entities = [];
        $articles = $this->mongo->footyroom->articles->find($query, [
            'limit' => $limit,
            'skip' => $offset,
            'sort' => ['isFeatured' => -1, 'createdAt' => -1, '_id' => -1],
        ]);

        foreach ($articles as $article) {
            $article->id = (string) $article->_id;
            $entities[] = AutoMapper::map($article, Article::class);
        }

        return $entities;
    }
}