Passed
Push — feature/rebusify ( 289185...639d49 )
by Paul
04:02
created

ReviewManager   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 200
Duplicated Lines 0 %

Test Coverage

Coverage 37.38%

Importance

Changes 3
Bugs 0 Features 3
Metric Value
eloc 99
c 3
b 0
f 3
dl 0
loc 200
ccs 40
cts 107
cp 0.3738
rs 10
wmc 24

11 Methods

Rating   Name   Duplication   Size   Complexity  
A normalizeTerms() 0 15 4
A get() 0 33 1
A getRatingCounts() 0 10 1
A delete() 0 4 2
A normalizeTermIds() 0 4 1
A getPostId() 0 3 1
A create() 0 27 2
A setTerms() 0 9 3
A getNewPostStatus() 0 6 4
A single() 0 7 2
A revert() 0 17 3
1
<?php
2
3
namespace GeminiLabs\SiteReviews\Database;
4
5
use GeminiLabs\SiteReviews\Application;
6
use GeminiLabs\SiteReviews\Database;
7
use GeminiLabs\SiteReviews\Commands\CreateReview;
8
use GeminiLabs\SiteReviews\Defaults\CreateReviewDefaults;
9
use GeminiLabs\SiteReviews\Defaults\ReviewsDefaults;
10
use GeminiLabs\SiteReviews\Defaults\SiteReviewsSummaryDefaults;
11
use GeminiLabs\SiteReviews\Helper;
12
use GeminiLabs\SiteReviews\Review;
13
use GeminiLabs\SiteReviews\Reviews;
14
use WP_Post;
15
use WP_Query;
16
17
class ReviewManager
18
{
19
    /**
20
     * @return false|Review
21
     */
22 1
    public function create(CreateReview $command)
23
    {
24 1
        $reviewValues = glsr(CreateReviewDefaults::class)->restrict((array) $command);
25 1
        $reviewValues = apply_filters('site-reviews/create/review-values', $reviewValues, $command);
26 1
        $reviewValues = glsr(Helper::class)->prefixArrayKeys($reviewValues);
27 1
        unset($reviewValues['json']); // @todo remove the need for this
28
        $postValues = [
29 1
            'comment_status' => 'closed',
30 1
            'meta_input' => $reviewValues,
31 1
            'ping_status' => 'closed',
32 1
            'post_content' => $reviewValues['_content'],
33 1
            'post_date' => $reviewValues['_date'],
34 1
            'post_date_gmt' => get_gmt_from_date($reviewValues['_date']),
35 1
            'post_name' => $reviewValues['_review_type'].'-'.$reviewValues['_review_id'],
36 1
            'post_status' => $this->getNewPostStatus($reviewValues, $command->blacklisted),
37 1
            'post_title' => $reviewValues['_title'],
38
            'post_type' => Application::POST_TYPE,
39
        ];
40 1
        $postId = wp_insert_post($postValues, true);
41 1
        if (is_wp_error($postId)) {
42
            glsr_log()->error($postId->get_error_message())->debug($postValues);
43
            return false;
44
        }
45 1
        $this->setTerms($postId, $command->category);
46 1
        $review = $this->single(get_post($postId));
47 1
        do_action('site-reviews/review/created', $review, $command);
48 1
        return $review;
49
    }
50
51
    /**
52
     * @param string $metaReviewId
53
     * @return void
54
     */
55
    public function delete($metaReviewId)
56
    {
57
        if ($postId = $this->getPostId($metaReviewId)) {
58
            wp_delete_post($postId, true);
59
        }
60
    }
61
62
    /**
63
     * @return object
64
     */
65
    public function get(array $args = [])
66
    {
67
        $args = glsr(ReviewsDefaults::class)->merge($args);
68
        $metaQuery = glsr(QueryBuilder::class)->buildQuery(
69
            ['assigned_to', 'type', 'rating'],
70
            $args
71
        );
72
        $taxQuery = glsr(QueryBuilder::class)->buildQuery(
73
            ['category'],
74
            ['category' => $this->normalizeTermIds($args['category'])]
75
        );
76
        $paged = glsr(QueryBuilder::class)->getPaged(
77
            wp_validate_boolean($args['pagination'])
78
        );
79
        $parameters = [
80
            'meta_key' => '_pinned',
81
            'meta_query' => $metaQuery,
82
            'offset' => $args['offset'],
83
            'order' => $args['order'],
84
            'orderby' => 'meta_value '.$args['orderby'],
85
            'paged' => glsr_get($args, 'paged', $paged),
86
            'post__in' => $args['post__in'],
87
            'post__not_in' => $args['post__not_in'],
88
            'post_status' => 'publish',
89
            'post_type' => Application::POST_TYPE,
90
            'posts_per_page' => $args['count'],
91
            'tax_query' => $taxQuery,
92
        ];
93
        $parameters = apply_filters('site-reviews/get/reviews/query', $parameters, $args);
94
        $query = new WP_Query($parameters);
95
        $results = array_map([$this, 'single'], $query->posts);
96
        $reviews = new Reviews($results, $query->max_num_pages, $args);
97
        return apply_filters('site-reviews/get/reviews', $reviews, $query);
98
    }
99
100
    /**
101
     * @param string $metaReviewId
102
     * @return int
103
     */
104
    public function getPostId($metaReviewId)
105
    {
106
        return glsr(SqlQueries::class)->getPostIdFromReviewId($metaReviewId);
107
    }
108
109
    /**
110
     * @return array
111
     */
112
    public function getRatingCounts(array $args = [])
113
    {
114
        $args = glsr(SiteReviewsSummaryDefaults::class)->filter($args);
115
        $counts = glsr(CountsManager::class)->get([
116
            'post_ids' => glsr(Helper::class)->convertStringToArray($args['assigned_to']),
117
            'term_ids' => $this->normalizeTermIds($args['category']),
118
            'type' => $args['type'],
119
        ]);
120
        return glsr(CountsManager::class)->flatten($counts, [
121
            'min' => $args['rating'],
122
        ]);
123
    }
124
125
    /**
126
     * @param string $commaSeparatedTermIds
127
     * @return array
128
     */
129 1
    public function normalizeTermIds($commaSeparatedTermIds)
130
    {
131 1
        $termIds = glsr_array_column($this->normalizeTerms($commaSeparatedTermIds), 'term_id');
132 1
        return array_unique(array_map('intval', $termIds));
133
    }
134
135
    /**
136
     * @param string $commaSeparatedTermIds
137
     * @return array
138
     */
139 1
    public function normalizeTerms($commaSeparatedTermIds)
140
    {
141 1
        $terms = [];
142 1
        $termIds = glsr(Helper::class)->convertStringToArray($commaSeparatedTermIds);
143 1
        foreach ($termIds as $termId) {
144
            if (is_numeric($termId)) {
145
                $termId = intval($termId);
146
            }
147
            $term = term_exists($termId, Application::TAXONOMY);
148
            if (!isset($term['term_id'])) {
149
                continue;
150
            }
151
            $terms[] = $term;
152
        }
153 1
        return $terms;
154
    }
155
156
    /**
157
     * @param int $postId
158
     * @return void
159
     */
160
    public function revert($postId)
161
    {
162
        if (Application::POST_TYPE != get_post_field('post_type', $postId)) {
163
            return;
164
        }
165
        delete_post_meta($postId, '_edit_last');
166
        $result = wp_update_post([
167
            'ID' => $postId,
168
            'post_content' => glsr(Database::class)->get($postId, 'content'),
169
            'post_date' => glsr(Database::class)->get($postId, 'date'),
170
            'post_title' => glsr(Database::class)->get($postId, 'title'),
171
        ]);
172
        if (is_wp_error($result)) {
173
            glsr_log()->error($result->get_error_message());
174
            return;
175
        }
176
        do_action('site-reviews/review/reverted', glsr_get_review($postId));
177
    }
178
179
    /**
180
     * @return Review
181
     */
182 1
    public function single(WP_Post $post)
183
    {
184 1
        if (Application::POST_TYPE != $post->post_type) {
185
            $post = new WP_Post((object) []);
186
        }
187 1
        $review = new Review($post);
188 1
        return apply_filters('site-reviews/get/review', $review, $post);
189
    }
190
191
    /**
192
     * @param bool $isBlacklisted
193
     * @return string
194
     */
195 1
    protected function getNewPostStatus(array $reviewValues, $isBlacklisted)
196
    {
197 1
        $requireApproval = glsr(OptionManager::class)->getBool('settings.general.require.approval');
198 1
        return 'local' == $reviewValues['_review_type'] && ($requireApproval || $isBlacklisted)
199
            ? 'pending'
200 1
            : 'publish';
201
    }
202
203
    /**
204
     * @param int $postId
205
     * @param string $termIds
206
     * @return void
207
     */
208 1
    protected function setTerms($postId, $termIds)
209
    {
210 1
        $termIds = $this->normalizeTermIds($termIds);
211 1
        if (empty($termIds)) {
212 1
            return;
213
        }
214
        $termTaxonomyIds = wp_set_object_terms($postId, $termIds, Application::TAXONOMY);
215
        if (is_wp_error($termTaxonomyIds)) {
216
            glsr_log()->error($termTaxonomyIds->get_error_message());
217
        }
218
    }
219
}
220