Test Failed
Push — main ( 4244ba...f56735 )
by Paul
10:05 queued 12s
created

SettingsController::hasMultilingualIntegration()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 15
nc 4
nop 1
dl 0
loc 21
ccs 0
cts 15
cp 0
crap 20
rs 9.7666
c 0
b 0
f 0
1
<?php
2
3
namespace GeminiLabs\SiteReviews\Controllers;
4
5
use GeminiLabs\SiteReviews\Addons\Updater;
6
use GeminiLabs\SiteReviews\Database\OptionManager;
7
use GeminiLabs\SiteReviews\Exceptions\LicenseException;
8
use GeminiLabs\SiteReviews\Helpers\Arr;
9
use GeminiLabs\SiteReviews\Modules\Multilingual;
10
use GeminiLabs\SiteReviews\Modules\Notice;
11
use GeminiLabs\SiteReviews\Modules\Sanitizer;
12
13
class SettingsController extends AbstractController
14
{
15
    /**
16
     * @action admin_init
17
     */
18 8
    public function registerSettings(): void
19
    {
20 8
        register_setting(glsr()->id, OptionManager::databaseKey(), [
21 8
            'default' => glsr()->defaults(),
22 8
            'sanitize_callback' => [$this, 'sanitizeSettingsCallback'],
23 8
            'type' => 'array',
24 8
        ]);
25
    }
26
27
    /**
28
     * @param mixed $input
29
     *
30
     * @see registerSettings
31 4
     */
32
    public function sanitizeSettingsCallback($input): array
33 4
    {
34 4
        OptionManager::flushSettingsCache(); // remove settings from object cache before updating
35 4
        $input = Arr::consolidate($input);
36
        if (!array_key_exists('settings', $input)) {
37
            return $input;
38
        }
39
        $options = array_replace_recursive(glsr(OptionManager::class)->all(), [
40
            'settings' => $input['settings'],
41
        ]);
42
        $options = $this->sanitizeForms($options, $input);
43
        $options = $this->sanitizeGeneral($options, $input);
44
        $options = $this->sanitizeStrings($options, $input);
45
        $options = $this->sanitizeAll($options);
46
        $options = glsr()->filterArray('settings/sanitize', $options, $input);
47
        glsr()->action('settings/updated', $options, $input);
48
        if (filter_input(INPUT_POST, 'option_page') === glsr()->id) {
49
            glsr(Notice::class)->addSuccess(_x('Settings updated.', 'admin-text', 'site-reviews'));
50 4
        }
51
        glsr(Notice::class)->store(); // store the notices before the page reloads
52
        return $options;
53
    }
54
55
    protected function sanitizeAll(array $options): array
56
    {
57
        $values = Arr::flatten($options);
58
        $sanitizers = wp_list_pluck(glsr()->settings(), 'sanitizer');
59
        $options = (new Sanitizer($values, $sanitizers))->run();
60
        return Arr::unflatten($options);
61
    }
62
63
    protected function sanitizeForms(array $options, array $input): array
64
    {
65
        $key = 'settings.forms';
66
        $inputForm = Arr::get($input, $key);
67
        $multiFields = ['limit_assignments', 'required'];
68
        foreach ($multiFields as $name) {
69
            $defaultValue = Arr::get($inputForm, $name, []);
70
            $options = Arr::set($options, "{$key}.{$name}", $defaultValue);
71
        }
72
        return $options;
73
    }
74
75
    protected function sanitizeGeneral(array $options, array $input): array
76
    {
77
        $key = 'settings.general';
78
        $inputForm = Arr::get($input, $key);
79
        if (!$this->hasMultilingualIntegration(Arr::getAs('string', $inputForm, 'multilingual'))) {
80
            $options = Arr::set($options, $key.'.multilingual', '');
81
        }
82
        if ('' === trim(Arr::get($inputForm, 'notification_message'))) {
83
            $defaultValue = Arr::get(glsr()->defaults(), $key.'.notification_message');
84
            $options = Arr::set($options, $key.'.notification_message', $defaultValue);
85
        }
86
        if ('' === trim(Arr::get($inputForm, 'request_verification_message'))) {
87
            $defaultValue = Arr::get(glsr()->defaults(), $key.'.request_verification_message');
88
            $options = Arr::set($options, $key.'.request_verification_message', $defaultValue);
89
        }
90
        $defaultValue = Arr::get($inputForm, 'notifications', []);
91
        $options = Arr::set($options, $key.'.notifications', $defaultValue);
92
        return $options;
93
    }
94
95
    protected function sanitizeStrings(array $options, array $input): array
96
    {
97
        $key = 'settings.strings';
98
        $inputForm = Arr::consolidate(Arr::get($input, $key));
99
        if (!empty($inputForm)) {
100
            $options = Arr::set($options, $key, array_values(array_filter($inputForm)));
101
            $allowedTags = [
102
                'a' => ['class' => [], 'href' => [], 'target' => []],
103
                'span' => ['class' => []],
104
            ];
105
            $errors = [
106
                '%d' => [],
107
                '%s' => [],
108
            ];
109
            array_walk($options['settings']['strings'], function (&$string) use ($allowedTags, &$errors) {
110
                $string = wp_parse_args($string, [
111
                    'p1' => '',
112
                    'p2' => '',
113
                    's1' => '',
114
                    's2' => '',
115
                ]);
116
                $string['s2'] = wp_kses($string['s2'], $allowedTags);
117
                $string['p2'] = wp_kses($string['p2'], $allowedTags);
118
                foreach ($errors as $needle => $values) {
119
                    if (str_contains($string['s1'], $needle) && !str_contains($string['s2'], $needle)) {
120
                        $errors[$needle][] = $string['s2'];
121
                    }
122
                    if (str_contains($string['p1'], $needle) && !str_contains($string['p2'], $needle)) {
123
                        $errors[$needle][] = $string['p2'];
124
                    }
125
                }
126
            });
127
            foreach ($errors as $needle => $values) {
128
                if (!empty($errors[$needle])) {
129
                    $notice = sprintf(_x('You forgot to include the %s placeholder tags in your Custom Text.', 'admin-text', 'site-reviews'),
130
                        "<code>{$needle}</code>"
131
                    );
132
                    glsr(Notice::class)->addError($notice, $errors[$needle]);
133
                }
134
            }
135
        }
136
        return $options;
137
    }
138
139
    protected function hasMultilingualIntegration(string $option): bool
140
    {
141
        $integration = glsr(Multilingual::class)->getIntegration($option);
142
        if (!$integration) {
143
            return false;
144
        }
145
        if (!$integration->isActive()) {
146
            glsr(Notice::class)->addError(sprintf(
147
                _x('Please install/activate the %s plugin to enable the integration.', 'admin-text', 'site-reviews'),
148
                $integration->pluginName
149
            ));
150
            return false;
151
        } elseif (!$integration->isSupported()) {
152
            glsr(Notice::class)->addError(sprintf(
153
                _x('Please update the %s plugin to v%s or greater to enable the integration.', 'admin-text', 'site-reviews'),
154
                $integration->pluginName,
155
                $integration->supportedVersion
156
            ));
157
            return false;
158
        }
159
        return true;
160
    }
161
}
162