VoteQueryHandler.php 1.72 KB
<?php

namespace FootyRoom\Queries\Vote;

use FootyRoom\Support\MongoClient;
use MongoDB\BSON\UTCDateTime;

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

    /**
     * Constructor.
     *
     * @param \FootyRoom\Support\MongoClient $mongo
     */
    public function __construct(MongoClient $mongo)
    {
        $this->mongo = $mongo->footyroom;
    }

    /**
     * Query handler.
     *
     * @param \FootyRoom\Queries\Vote\VoteCountQuery $query
     *
     * @return int
     */
    public function voteCount(VoteCountQuery $query)
    {
        $queryParams = [
            'createdAt' => ['$gte' => new UTCDateTime($query->getSinceDate()->getTimestamp() * 1000)],
        ];

        if ($query->getGuestId()) {
            $queryParams['tracker'] = $query->getGuestId();
            $queryParams['userId'] = ['$exists' => false];
        } elseif ($query->getUserId()) {
            $queryParams['userId'] = $query->getUserId();
        }

        if ($query->getPollRef()) {
            $queryParams['pollRef'] = $query->getPollRef();
        }

        return $this->mongo->votes->count($queryParams);
    }

    /**
     * Query handler.
     *
     * @param \FootyRoom\Queries\Vote\HasVotedQuery $query
     *
     * @return int
     */
    public function hasVoted(HasVotedQuery $query)
    {
        $queryParams['pollRef'] = $query->getPollRef();

        if ($query->getGuestId()) {
            $queryParams['tracker'] = $query->getGuestId();
            $queryParams['userId'] = ['$exists' => false];
        } elseif ($query->getUserId()) {
            $queryParams['userId'] = $query->getUserId();
        }

        return $this->mongo->votes->count($queryParams) > 0;
    }
}