Test Failed
Push — develop ( 48d1be...252e0d )
by Paul
10:21
created

MainController::filterRankmathSchema()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 19
ccs 0
cts 8
cp 0
rs 9.5222
c 0
b 0
f 0
cc 5
nc 5
nop 2
crap 30
1
<?php
2
3
namespace GeminiLabs\SiteReviews\Integrations\WooCommerce\Controllers;
4
5
use GeminiLabs\SiteReviews\Controllers\AbstractController;
6
use GeminiLabs\SiteReviews\Helpers\Arr;
7
use GeminiLabs\SiteReviews\Helpers\Cast;
8
use GeminiLabs\SiteReviews\Integrations\WooCommerce\Elementor\Widgets\ProductRating;
9
use GeminiLabs\SiteReviews\Integrations\WooCommerce\Widgets\WidgetRatingFilter;
10
use GeminiLabs\SiteReviews\Integrations\WooCommerce\Widgets\WidgetRecentReviews;
11
use GeminiLabs\SiteReviews\Modules\SchemaParser;
12
use GeminiLabs\SiteReviews\Review;
13
14
class MainController extends AbstractController
15
{
16
    public const VERIFIED_META_KEY = '_verified';
17
18
    /**
19
     * @action admin_enqueue_scripts
20
     */
21
    public function enqueueInlineAdminStyles(): void
22
    {
23
        $css = '.woocommerce-review-activity-card .woocommerce-activity-card__actions button.is-tertiary:not(.is-destructive) {display:none}';
24
        wp_add_inline_style('wc-admin-app', $css);
25
    }
26
27
    /**
28
     * @filter site-reviews/enqueue/public/inline-styles
29
     */
30
    public function filterInlineStyles(string $css): string
31
    {
32
        $css .= 'ul.glsr li a{display:flex;justify-content:space-between;}'; // fix rating filter widget
33
        $css .= '.glsr.woocommerce-product-rating{align-items:center;display:inline-flex;gap:.5em;}';
34
        $css .= '.glsr.woocommerce-product-rating .woocommerce-review-link{top:-1px!important;}'; // fix product title rating position
35
        $style = glsr_get_option('integrations.woocommerce.style');
36
        $colors = [
37
            'black' => '#212121',
38
            'woocommerce' => '#96588A',
39
        ];
40
        if (!array_key_exists($style, $colors)) {
41
            return $css;
42
        }
43
        $css = str_replace('assets/images/stars/default/', "assets/images/stars/{$style}/", $css);
44
        $css .= ".glsr:not([data-theme]) .glsr-bar-background-percent{--glsr-bar-bg:{$colors[$style]};}";
45
        return $css;
46
    }
47
48
    /**
49
     * @return int
50
     *
51
     * @filter woocommerce_product_reviews_pending_count
52
     */
53
    public function filterMenuPendingCount()
54
    {
55
        return 0;
56
    }
57
58
    /**
59
     * @param string $status
60
     * @param string $postType
61
     * @param string $commentType
62
     *
63
     * @return string
64
     *
65
     * @filter get_default_comment_status
66
     */
67
    public function filterProductCommentStatus($status, $postType, $commentType)
68
    {
69
        if ('product' === $postType && 'comment' === $commentType) {
70
            return 'open';
71
        }
72
        return $status;
73
    }
74
75
    /**
76
     * @param array  $settings
77
     * @param string $section
78
     *
79
     * @return array
80
     *
81
     * @filter woocommerce_get_settings_products
82
     */
83
    public function filterProductSettings($settings, $section)
84
    {
85
        if (!empty($section)) {
86
            return $settings;
87
        }
88
        $disabled = ['woocommerce_enable_review_rating', 'woocommerce_review_rating_required'];
89
        foreach ($settings as &$setting) {
90
            if (in_array(Arr::get($setting, 'id'), $disabled)) {
91
                $setting = Arr::set($setting, 'custom_attributes.disabled', true);
92
                $setting['desc'] = sprintf('%s <span class="required">(%s)</span>',
93
                    $setting['desc'],
94
                    _x('managed by Site Reviews', 'admin-text', 'site-reviews')
95
                );
96
            }
97
        }
98
        return $settings;
99
    }
100
101
    /**
102
     * @filter site-reviews/enqueue/public/inline-script/after
103
     */
104
    public function filterPublicInlineScript(string $script): string
105
    {
106
        $script .= '"undefined"!==typeof jQuery&&(jQuery(".wc-tabs .reviews_tab a").on("click",function(){setTimeout(function(){GLSR.Event.trigger("site-reviews-themes/swiper/resize")},25)}));';
107
        return $script;
108
    }
109
110
    /**
111
     * @filter site-reviews/schema/generate
112
     */
113
    public function filterRankmathSchema(array $data, SchemaParser $parser): array
0 ignored issues
show
Unused Code introduced by
The parameter $parser is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

113
    public function filterRankmathSchema(array $data, /** @scrutinizer ignore-unused */ SchemaParser $parser): array

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
114
    {
115
        if (!did_action('rank_math/json_ld/preview')) {
116
            return $data;
117
        }
118
        if (!$url = wp_get_referer()) {
119
            return $data;
120
        }
121
        $urlQuery = (string) wp_parse_url($url, \PHP_URL_QUERY);
122
        $query = wp_parse_args($urlQuery);
123
        $postId = Cast::toInt($query['post'] ?? 0);
124
        if (!$product = wc_get_product($postId)) {
125
            return $data;
126
        }
127
        if (!$product->get_reviews_allowed()) {
128
            return $data;
129
        }
130
        return glsr(SchemaParser::class)->buildReviewSchema([
131
            'assigned_posts' => $postId,
132
        ]);
133
    }
134
135
    /**
136
     * @return string
137
     *
138
     * @filter option_woocommerce_enable_review_rating
139
     * @filter option_woocommerce_review_rating_required
140
     */
141
    public function filterRatingOption()
142
    {
143
        return 'yes';
144
    }
145
146
    /**
147
     * @return \WC_Product|false
148
     *
149
     * @filter site-reviews/review/call/product
150
     */
151
    public function filterReviewProductMethod(Review $review)
152
    {
153
        if ($product = wc_get_product(Arr::get($review->assigned_posts, 0))) {
154
            return $product;
155
        }
156
        return false;
157
    }
158
159
    /**
160
     * @param \GeminiLabs\SiteReviews\Modules\Html\Tags\ReviewAuthorTag $tag
161
     *
162
     * @filter site-reviews/review/value/author
163
     */
164
    public function filterReviewAuthorTagValue(string $value, $tag): string
165
    {
166
        if ($tag->review->hasVerifiedOwner() && 'yes' === get_option('woocommerce_review_rating_verification_label')) { // @phpstan-ignore-line
167
            $text = esc_attr__('verified owner', 'site-reviews');
168
            $value = sprintf('%s <em class="woocommerce-review__verified verified">(%s)</em>', $value, $text);
169
        }
170
        return $value;
171
    }
172
173
    /**
174
     * @filter site-reviews/review/call/hasVerifiedOwner
175
     */
176
    public function hasVerifiedOwner(Review $review): bool
177
    {
178
        $verified = get_post_meta($review->ID, static::VERIFIED_META_KEY, true);
179
        return '' === $verified
180
            ? $this->verifyProductOwner($review)
181
            : (bool) $verified;
182
    }
183
184
    /**
185
     * @action admin_init
186
     */
187
    public function redirectProductReviews(): void
188
    {
189
        global $pagenow;
190
        if ('edit.php' === $pagenow
191
            && 'product' === filter_input(INPUT_GET, 'post_type')
192
            && 'product-reviews' === filter_input(INPUT_GET, 'page')) {
193
            wp_redirect(add_query_arg('notice', 'product-reviews', glsr_admin_url()), 301);
194
            exit;
1 ignored issue
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
195
        }
196
    }
197
198
    /**
199
     * @action elementor/widgets/register
200
     */
201
    public function registerElementorWidgets(): void
202
    {
203
        $widgets = \Elementor\Plugin::instance()->widgets_manager;
204
        $widgets->unregister('woocommerce-product-rating');
205
        if (class_exists('ElementorPro\Modules\Woocommerce\Widgets\Product_Rating')) {
206
            $widgets->register(new ProductRating());
207
        }
208
    }
209
210
    /**
211
     * @action widgets_init
212
     */
213
    public function registerWidgets(): void
214
    {
215
        unregister_widget('WC_Widget_Recent_Reviews');
216
        unregister_widget('WC_Widget_Rating_Filter');
217
        register_widget(WidgetRecentReviews::class);
218
        register_widget(WidgetRatingFilter::class);
219
    }
220
221
    /**
222
     * @param array $args
223
     *
224
     * @return array
225
     *
226
     * @action woocommerce_register_post_type_product
227
     */
228
    public function removeWoocommerceReviews($args)
229
    {
230
        if (array_key_exists('supports', $args)) {
231
            $args['supports'] = array_diff($args['supports'], ['comments']);
232
        }
233
        return $args;
234
    }
235
236
    /**
237
     * @action admin_notices
238
     */
239
    public function renderNotice(): void
240
    {
241
        $screen = glsr_current_screen();
242
        if ('edit' !== $screen->base || 'edit-site-review' !== $screen->id) {
243
            return;
244
        }
245
        if ('product-reviews' !== filter_input(INPUT_GET, 'notice')) {
246
            return;
247
        }
248
        glsr()->render('integrations/woocommerce/notices/reviews');
249
    }
250
251
    /**
252
     * @return void|bool
253
     *
254
     * @see $this->hasVerifiedOwner()
255
     *
256
     * @action site-reviews/review/created
257
     */
258
    public function verifyProductOwner(Review $review)
259
    {
260
        $review->refresh(); // refresh the review first!
261
        $verified = false;
262
        foreach ($review->assigned_posts as $postId) {
263
            if ('product' === get_post_type($postId)) {
264
                $verified = wc_customer_bought_product($review->email, $review->author_id, $postId);
265
                break;
266
            }
267
        }
268
        update_post_meta($review->ID, static::VERIFIED_META_KEY, (int) $verified);
269
        return $verified;
270
    }
271
}
272