-
Notifications
You must be signed in to change notification settings - Fork 3
/
votes.php
137 lines (124 loc) · 3.47 KB
/
votes.php
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
<?php
class com_meego_planet_votes
{
public static function vote(com_meego_planet_item $item, $vote)
{
midgardmvc_core::get_instance()->authorization->require_user();
$valid_votes = array
(
-1,
1
);
if (!in_array($vote, $valid_votes))
{
throw new InvalidArgumentException("Invalid vote value");
}
$vote_obj = self::get_user_vote($item);
if ($vote_obj->vote != $vote)
{
$vote_obj->vote = $vote;
if ($vote_obj->guid)
{
$stat = $vote_obj->update();
}
else
{
$vote_obj->create();
}
}
return $vote_obj;
}
public static function get(com_meego_planet_item $item)
{
$votes = array
(
'1' => 0,
'-1' => 0,
'user' => 0,
);
$q = new midgard_query_select
(
new midgard_query_storage('com_meego_planet_item_vote')
);
$q->set_constraint
(
new midgard_query_constraint
(
new midgard_query_property('item'),
'=',
new midgard_query_value($item->id)
)
);
$q->execute();
$vote_objs = $q->list_objects();
$votes['1'] = array_reduce
(
$vote_objs,
function ($current, $vote)
{
if ($vote->vote == 1)
{
return $current + 1;
}
return $current;
},
0
);
$votes['-1'] = array_reduce
(
$vote_objs,
function ($current, $vote)
{
if ($vote->vote == -1)
{
return $current + 1;
}
return $current;
},
0
);
if (midgardmvc_core::get_instance()->authentication->is_user())
{
$votes['user'] = self::get_user_vote($item)->vote;
}
return $votes;
}
public static function get_user_vote(com_meego_planet_item $item)
{
midgardmvc_core::get_instance()->authorization->require_user();
$q = new midgard_query_select
(
new midgard_query_storage('com_meego_planet_item_vote')
);
$qc = new midgard_query_constraint_group('AND');
$qc->add_constraint
(
new midgard_query_constraint
(
new midgard_query_property('item'),
'=',
new midgard_query_value($item->id)
)
);
$qc->add_constraint
(
new midgard_query_constraint
(
new midgard_query_property('user'),
'=',
new midgard_query_value(midgardmvc_core::get_instance()->authentication->get_person()->id)
)
);
$q->set_constraint($qc);
$q->execute();
$objects = $q->list_objects();
if (count($objects) > 0)
{
return new com_meego_planet_item_vote($objects[0]->guid);
}
$vote = new com_meego_planet_item_vote();
$vote->item = $item->id;
$vote->user = midgardmvc_core::get_instance()->authentication->get_person()->id;
return $vote;
}
}