Passed
Push — master ( ea4f63...197c27 )
by Paul
20:35 queued 09:52
created

ReviewManager::assignTerm()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 8
c 0
b 0
f 0
dl 0
loc 13
ccs 8
cts 8
cp 1
rs 10
cc 3
nc 3
nop 2
crap 3
1
<?php
2
3
namespace GeminiLabs\SiteReviews\Database;
4
5
use GeminiLabs\SiteReviews\Commands\CreateReview;
6
use GeminiLabs\SiteReviews\Database;
7
use GeminiLabs\SiteReviews\Defaults\CustomFieldsDefaults;
8
use GeminiLabs\SiteReviews\Defaults\RatingDefaults;
9
use GeminiLabs\SiteReviews\Defaults\UpdateReviewDefaults;
10
use GeminiLabs\SiteReviews\Helper;
11
use GeminiLabs\SiteReviews\Helpers\Arr;
12
use GeminiLabs\SiteReviews\Helpers\Cast;
13
use GeminiLabs\SiteReviews\Modules\Sanitizer;
14
use GeminiLabs\SiteReviews\Request;
15
use GeminiLabs\SiteReviews\Review;
16
use GeminiLabs\SiteReviews\Reviews;
17
18
class ReviewManager
19
{
20
    /**
21
     * @param int $postId
22
     * @return int|false
23
     */
24 2
    public function assignPost(Review $review, $postId)
25
    {
26
        $where = [
27 2
            'is_published' => 'publish' === get_post_status($postId),
28 2
            'post_id' => $postId,
29 2
            'rating_id' => $review->rating_id,
30
        ];
31 2
        if ($result = glsr(Database::class)->insert('assigned_posts', $where)) {
32 2
            glsr(Cache::class)->delete($review->ID, 'reviews');
33 2
            if (!defined('WP_IMPORTING')) {
34 2
                glsr(CountManager::class)->posts($postId);
35
            }
36
        }
37 2
        return $result;
38
    }
39
40
    /**
41
     * @param int $termId
42
     * @return int|false
43
     */
44 2
    public function assignTerm(Review $review, $termId)
45
    {
46
        $where = [
47 2
            'rating_id' => $review->rating_id,
48 2
            'term_id' => $termId,
49
        ];
50 2
        if ($result = glsr(Database::class)->insert('assigned_terms', $where)) {
51 2
            glsr(Cache::class)->delete($review->ID, 'reviews');
52 2
            if (!defined('WP_IMPORTING')) {
53 2
                glsr(CountManager::class)->terms($termId);
54
            }
55
        }
56 2
        return $result;
57
    }
58
59
    /**
60
     * @param int $userId
61
     * @return int|false
62
     */
63 2
    public function assignUser(Review $review, $userId)
64
    {
65
        $where = [
66 2
            'rating_id' => $review->rating_id,
67 2
            'user_id' => $userId,
68
        ];
69 2
        if ($result = glsr(Database::class)->insert('assigned_users', $where)) {
70 2
            glsr(Cache::class)->delete($review->ID, 'reviews');
71 2
            if (!defined('WP_IMPORTING')) {
72 2
                glsr(CountManager::class)->users($userId);
73
            }
74
        }
75 2
        return $result;
76
    }
77
78
    /**
79
     * @return false|Review
80
     */
81 14
    public function create(CreateReview $command, $postId = null)
82
    {
83 14
        if (empty($postId)) {
84 14
            $postId = $this->createRaw($command);
85
        }
86 14
        $review = $this->get($postId);
87 14
        if ($review->isValid()) {
88 14
            glsr()->action('review/created', $review, $command);
89 14
            return $this->get($review->ID); // return a fresh copy of the review
90
        }
91
        return false;
92
    }
93
94
    /**
95
     * @param int $postId
96
     * @return false|Review
97
     */
98
    public function createFromPost($postId)
99
    {
100
        if (!Review::isReview($postId)) {
101
            return false;
102
        }
103
        $command = new CreateReview(new Request([]));
104
        glsr()->action('review/create', $postId, $command);
105
        return $this->create($command, $postId);
106
    }
107
108
    /**
109
     * @return false|int
110
     */
111 14
    public function createRaw(CreateReview $command)
112
    {
113 14
        $values = glsr()->args($command->toArray()); // this filters the values
114
        $postValues = [
115 14
            'comment_status' => 'closed',
116 14
            'meta_input' => ['_submitted' => $command->request->toArray()], // save the original submitted request in metadata
117 14
            'ping_status' => 'closed',
118 14
            'post_author' => $values->author_id,
119 14
            'post_content' => $values->content,
120 14
            'post_date' => $values->date,
121 14
            'post_date_gmt' => $values->date_gmt,
122 14
            'post_name' => uniqid($values->type),
123 14
            'post_status' => $this->postStatus($command),
124 14
            'post_title' => $values->title,
125 14
            'post_type' => glsr()->post_type,
126
        ];
127 14
        $postId = wp_insert_post($postValues, true);
128 14
        if (is_wp_error($postId)) {
129
            glsr_log()->error($postId->get_error_message())->debug($postValues);
130
            return false;
131
        }
132 14
        glsr()->action('review/create', $postId, $command);
133 14
        return $postId;
134
    }
135
136
    /**
137
     * This only deletes the entry in the ratings table!
138
     * @param int $reviewId
139
     * @return int|false
140
     */
141
    public function delete($reviewId)
142
    {
143
        $result = glsr(Database::class)->delete('ratings', ['review_id' => $reviewId]);
144
        if ($result) {
145
            glsr(Cache::class)->delete($reviewId, 'reviews');
146
        }
147
        return $result;
148
    }
149
150
    /**
151
     * @param int $reviewId
152
     * @return void
153
     */
154
    public function deleteRevisions($reviewId)
155
    {
156
        $revisionIds = glsr(Query::class)->revisionIds($reviewId);
157
        foreach ($revisionIds as $revisionId) {
158
            wp_delete_post_revision($revisionId);
159
        }
160
    }
161
162
    /**
163
     * @param int $reviewId
164
     * @return Review
165
     */
166 14
    public function get($reviewId)
167
    {
168 14
        $reviewId = Helper::getPostId($reviewId);
169 14
        $review = glsr(Query::class)->review($reviewId);
170 14
        glsr()->action('get/review', $review, $reviewId);
171 14
        return $review;
172
    }
173
174
    /**
175
     * @return Reviews
176
     */
177 1
    public function reviews(array $args = [])
178
    {
179 1
        $args = (new NormalizePaginationArgs($args))->toArray();
180 1
        $results = glsr(Query::class)->reviews($args);
181 1
        $total = $this->total($args, $results);
182 1
        $reviews = new Reviews($results, $total, $args);
183 1
        glsr()->action('get/reviews', $reviews, $args);
184 1
        return $reviews;
185
    }
186
187
    /**
188
     * @return int
189
     */
190 1
    public function total(array $args = [], array $reviews = [])
191
    {
192 1
        return glsr(Query::class)->totalReviews($args, $reviews);
193
    }
194
195
    /**
196
     * @param int $postId
197
     * @return int|false
198
     */
199 1
    public function unassignPost(Review $review, $postId)
200
    {
201
        $where = [
202 1
            'post_id' => $postId,
203 1
            'rating_id' => $review->rating_id,
204
        ];
205 1
        if ($result = glsr(Database::class)->delete('assigned_posts', $where)) {
206 1
            glsr(Cache::class)->delete($review->ID, 'reviews');
207 1
            glsr(CountManager::class)->posts($postId);
208
        }
209 1
        return $result;
210
    }
211
212
    /**
213
     * @param int $termId
214
     * @return int|false
215
     */
216 1
    public function unassignTerm(Review $review, $termId)
217
    {
218
        $where = [
219 1
            'rating_id' => $review->rating_id,
220 1
            'term_id' => $termId,
221
        ];
222 1
        if ($result = glsr(Database::class)->delete('assigned_terms', $where)) {
223 1
            glsr(Cache::class)->delete($review->ID, 'reviews');
224 1
            glsr(CountManager::class)->terms($termId);
225
        }
226 1
        return $result;
227
    }
228
229
    /**
230
     * @param int $userId
231
     * @return int|false
232
     */
233 1
    public function unassignUser(Review $review, $userId)
234
    {
235
        $where = [
236 1
            'rating_id' => $review->rating_id,
237 1
            'user_id' => $userId,
238
        ];
239 1
        if ($result = glsr(Database::class)->delete('assigned_users', $where)) {
240 1
            glsr(Cache::class)->delete($review->ID, 'reviews');
241 1
            glsr(CountManager::class)->users($userId);
242
        }
243 1
        return $result;
244
    }
245
246
    /**
247
     * @param int $reviewId
248
     * @return Review|false  Return false on failure
249
     */
250
    public function update($reviewId, array $data = [])
251
    {
252
        if (false === $this->updateRating($reviewId, $data)) {
253
            return false;
254
        }
255
        if (false === $this->updateReview($reviewId, $data)) {
256
            return false;
257
        }
258
        $this->updateCustom($reviewId, $data);
259
        $this->updateResponse($reviewId, Arr::get($data, 'response'));
260
        $review = glsr(Query::class)->review($reviewId);
261
        if ($assignedPosts = Arr::uniqueInt(Arr::get($data, 'assigned_posts'))) {
262
            glsr()->action('review/updated/post_ids', $review, $assignedPosts); // trigger a recount of assigned posts
263
        }
264
        if ($assignedUsers = Arr::uniqueInt(Arr::get($data, 'assigned_users'))) {
265
            glsr()->action('review/updated/user_ids', $review, $assignedUsers); // trigger a recount of assigned posts
266
        }
267
        $review = glsr(Query::class)->review($reviewId); // get a fresh copy of the review
268
        glsr()->action('review/saved', $review, $data);
269
        return $review;
270
    }
271
272
    /**
273
     * @param int $postId
274
     * @param bool $isPublished
275
     * @return int|bool
276
     */
277
    public function updateAssignedPost($postId, $isPublished)
278
    {
279
        $isPublished = wp_validate_boolean($isPublished);
280
        $postId = Cast::toInt($postId);
281
        return glsr(Database::class)->update('assigned_posts',
282
            ['is_published' => $isPublished],
283
            ['post_id' => $postId]
284
        );
285
    }
286
287
    /**
288
     * @param int $reviewId
289
     * @return array
290
     */
291
    public function updateCustom($reviewId, array $data = [])
292
    {
293
        $data = glsr(CustomFieldsDefaults::class)->merge($data);
294
        $data = Arr::prefixKeys($data, 'custom_');
295
        foreach ($data as $metaKey => $metaValue) {
296
            glsr(Database::class)->metaSet($reviewId, $metaKey, $metaValue);
297
        }
298
        return $data;
299
    }
300
301
    /**
302
     * @param int $reviewId
303
     * @return int|false  Returns false on error
304
     */
305
    public function updateRating($reviewId, array $data = [])
306
    {
307
        glsr(Cache::class)->delete($reviewId, 'reviews');
308
        $sanitized = glsr(RatingDefaults::class)->restrict($data);
309
        if ($data = array_intersect_key($sanitized, $data)) {
310
            return glsr(Database::class)->update('ratings', $data, [
311
                'review_id' => $reviewId,
312
            ]);
313
        }
314
        return 0;
315
    }
316
317
    /**
318
     * @param int $reviewId
319
     * @param string $response
320
     * @return int|bool
321
     */
322
    public function updateResponse($reviewId, $response = '')
323
    {
324
        $response = Cast::toString($response);
325
        $response = glsr(Sanitizer::class)->sanitizeTextHtml($response);
326
        $userId = Helper::ifTrue(empty($response), 0, get_current_user_id());
327
        $review = glsr_get_review($reviewId);
328
        glsr()->action('review/responded', $review, $response, $userId);
329
        glsr(Database::class)->metaSet($reviewId, 'response_by', $userId); // prefixed metakey
330
        $result = glsr(Database::class)->metaSet($reviewId, 'response', $response); // prefixed metakey
331
        glsr(Cache::class)->delete($review->ID, 'reviews');
332
        return $result;
333
    }
334
335
    /**
336
     * @param int $reviewId
337
     * @return int|false  Returns false on failure
338
     */
339
    public function updateReview($reviewId, array $data = [])
340
    {
341
        if (glsr()->post_type !== get_post_type($reviewId)) {
342
            return 0;
343
        }
344
        glsr(Cache::class)->delete($reviewId, 'reviews');
345
        $sanitized = glsr(UpdateReviewDefaults::class)->restrict($data);
346
        if ($data = array_intersect_key($sanitized, $data)) {
347
            $data = array_filter([
348
                'post_content' => Arr::get($data, 'content'),
349
                'post_date' => Arr::get($data, 'date'),
350
                'post_date_gmt' => Arr::get($data, 'date_gmt'),
351
                'post_status' => Arr::get($data, 'status'),
352
                'post_title' => Arr::get($data, 'title'),
353
            ]);
354
        }
355
        if (!empty($data)) {
356
            $data = wp_parse_args(['ID' => $reviewId], $data);
357
            $result = wp_update_post($data, true);
358
            if (is_wp_error($result)) {
359
                glsr_log()->error($result->get_error_message())->debug($data);
360
                return false;
361
            }
362
        }
363
        return 0;
364
    }
365
366
    /**
367
     * @return string
368
     */
369 14
    protected function postStatus(CreateReview $command)
370
    {
371 14
        $isApproved = $command->is_approved;
372 14
        if (!defined('WP_IMPORTING')) {
373 14
            $requireApproval = glsr(OptionManager::class)->getBool('settings.general.require.approval');
374 14
            $requireApprovalForRating = glsr(OptionManager::class)->getInt('settings.general.require.approval_for', 5);
375 14
            $isApproved = !$requireApproval || $command->rating > $requireApprovalForRating;
376
        }
377 14
        return !$isApproved || ('local' === $command->type && $command->blacklisted)
378 1
            ? 'pending'
379 14
            : 'publish';
380
    }
381
}
382