VoteRepository.php
2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?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);
}
}