VoteRepository.php 2.32 KB
<?php

namespace FootyRoom\Repositories;

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

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

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

    /**
     * Maps Vote object to array so that we can persist it.
     *
     * @param \FootyRoom\Core\Vote\Vote $vote
     *
     * @return array
     */
    protected function mapToArray($vote)
    {
        $voteDTO = [
            'pollRef' => $vote->getPollId(),
            'createdAt' => new UTCDateTime($vote->getDate()->getTimestamp() * 1000),
        ];

        if ($vote->getTracker()) {
            $voteDTO['tracker'] = $vote->getTracker();
        }

        if ($vote->getUserId()) {
            $voteDTO['userId'] = $vote->getUserId();
        }

        $voteDTO['value'] = $vote->getChoice()->getValue();

        if ($vote->getChoice()->getValueType()) {
            $voteDTO['valueType'] = $vote->getChoice()->getValueType();
        }

        if ($vote->getChoice()->getValueId()) {
            $voteDTO['valueRef'] = $vote->getChoice()->getValueId();
        }

        return $voteDTO;
    }

    /**
     * Create multiple votes.
     *
     * @param \FootyRoom\Core\Vote\Vote[] $votes
     *
     * @return mixed
     */
    public function createMany($votes)
    {
        $voteDTOs = [];

        foreach ($votes as $vote) {
            $voteDTOs[] = $this->mapToArray($vote);
        }

        return $this->mongo->votes->insertMany($voteDTOs);
    }

    /**
     * Deletes votes specified by parameters.
     *
     * @param string $pollId
     * @param string $tracker
     * @param int $userId
     *
     * @return mixed
     */
    public function deleteBy($pollId, $tracker = null, $userId = null)
    {
        // Protect against accidental deletion of all votes from poll.
        if (!$tracker && !$userId) {
            return;
        }

        $query = [
            'pollRef' => $pollId,
        ];

        if ($tracker) {
            $query['tracker'] = $tracker;
        }

        if ($userId) {
            $query['userId'] = $userId;
        }

        return $this->mongo->votes->deleteMany($query);
    }
}