TipQuery.php 2.28 KB
<?php

namespace FootyRoom\Queries\Tip;

use FootyRoom\Support\AutoMapper;
use FootyRoom\Support\MongoClient;

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

    /** @var array */
    protected $query;

    public function __construct(MongoClient $mongo)
    {
        $this->mongo = $mongo;
        $this->query = [
            ['$lookup' => [
                'from' => 'matches',
                'localField' => 'matchId',
                'foreignField' => 'matchId',
                'as' => 'match',
            ]],
            ['$unwind' => '$match'],
            ['$project' => [
                'id' => '$_id',
                'match.homeTeam' => 1,
                'match.awayTeam' => 1,
                'match.homeScore' => 1,
                'match.awayScore' => 1,
                'match.statusType' => 1,
                'match.stage' => 1,
                'match.datetime' => 1,
                'match.posts' => 1,
                'match.id' => '$match.matchId',
                'prediction' => '$prediction',
                'odds' => '$odds',
                'status' => '$status',
                'result' => '$result',
            ]],
            ['$sort' => ['match.datetime' => -1]],
        ];
    }

    /**
     * @return \FootyRoom\Queries\Tip\Tip[]
     */
    public function find(int $limit): array
    {
        $query = array_merge(
            $this->query,
            [['$limit' => $limit]]
        );

        $tips = $this->search($query);

        return $tips;
    }

    /**
     * @return \FootyRoom\Queries\Tip\Tip|null
     */
    public function findByMatchId(int $matchId): ?Tip
    {
        $query = array_merge(
            [['$match' => ['matchId' => $matchId]]],
            $this->query
        );

        $tips = $this->search($query);

        if ($tips) {
            return $tips[0];
        }

        return null;
    }

    /**
     * @return \FootyRoom\Queries\Tip\Tip[]
     */
    private function search(array $query): array
    {
        $cursor = $this->mongo->footyroom->tips->aggregate($query);

        $tips = [];
        foreach ($cursor as $tip) {
            $tip['match']['datetime'] = $tip['match']['datetime']->toDatetime();
            $tips[] = AutoMapper::map($tip, Tip::class);
        }

        return $tips;
    }
}