Test Failed
Push — develop ( 33b521...cdbd76 )
by Paul
10:16 queued 21s
created

Plugin::request()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
namespace GeminiLabs\SiteReviews;
4
5
use GeminiLabs\SiteReviews\Helper;
6
use GeminiLabs\SiteReviews\Helpers\Arr;
7
use GeminiLabs\SiteReviews\Helpers\Cast;
8
use GeminiLabs\SiteReviews\Helpers\Str;
9
10
/**
11
 * @property string $id
12
 * @property string $name
13
 *
14
 * @method array  filterArray($hook, ...$args)
15
 * @method bool   filterBool($hook, ...$args)
16
 * @method float  filterFloat($hook, ...$args)
17
 * @method int    filterInt($hook, ...$args)
18
 * @method object filterObject($hook, ...$args)
19
 * @method string filterString($hook, ...$args)
20
 */
21
trait Plugin
22
{
23
    /**
24
     * @var static|null
25
     */
26
    protected static $instance;
27
28
    protected $basename;
29
    protected $file;
30
    protected $languages;
31
    protected $testedTo;
32
    protected $updateUrl;
33 209
    protected $uri;
34
    protected $version;
35 209
36 209
    public function __call($method, $args)
37 209
    {
38 209
        $isFilter = str_starts_with($method, 'filter');
39 209
        $cast = Str::removePrefix($method, 'filter');
40 209
        $to = Helper::buildMethodName('to', $cast);
41
        if ($isFilter && method_exists(Cast::class, $to)) {
42
            $filtered = call_user_func_array([$this, 'filter'], $args);
43
            return Cast::$to($filtered);
44
        }
45
        throw new \BadMethodCallException("Method [$method] does not exist.");
46
    }
47
48
    public function __construct()
49
    {
50
        $file = wp_normalize_path((new \ReflectionClass($this))->getFileName());
51
        $this->file = str_replace('plugin/Application', $this->id, $file);
52
        $this->basename = plugin_basename($this->file);
53
        $plugin = get_file_data($this->file, [
54
            'languages' => 'Domain Path',
55
            'name' => 'Plugin Name',
56
            'testedTo' => 'Tested up to',
57
            'uri' => 'Plugin URI',
58
            'updateUrl' => 'Update URI',
59
            'version' => 'Version',
60
        ], 'plugin');
61
        array_walk($plugin, function ($value, $key) {
62
            if (property_exists($this, $key)) {
63 209
                $this->$key = $value;
64
            }
65 209
        });
66 209
    }
67 44
68 44
    public function __get($property)
69 44
    {
70
        $instance = new \ReflectionClass($this);
71
        if ($instance->hasProperty($property)) {
72 209
            $prop = $instance->getProperty($property);
73 209
            if ($prop->isPublic() || $prop->isProtected()) {
74 209
                return $this->$property;
75
            }
76
        }
77
        $constant = strtoupper($property);
78
        if ($instance->hasConstant($constant)) {
79
            return $instance->getConstant($constant);
80
        }
81 175
    }
82
83 175
    /**
84 175
     * @param mixed ...$args
85
     */
86
    public function action(string $hook, ...$args): void
87
    {
88
        do_action("{$this->id}/action", $hook, $args);
89
        do_action_ref_array("{$this->id}/{$hook}", $args);
90 55
    }
91
92 55
    /**
93
     * @param mixed $args
94
     */
95 106
    public function args($args = []): Arguments
96
    {
97 106
        return new Arguments($args);
98 106
    }
99 106
100
    public function build(string $view, array $data = []): string
101
    {
102
        ob_start();
103
        $this->render($view, $data);
104
        return trim(ob_get_clean());
105
    }
106
107
    public function catchFatalError(): void
108
    {
109
        $error = error_get_last();
110 16
        if (E_ERROR === Arr::get($error, 'type') && str_contains(Arr::get($error, 'message'), $this->path())) {
111
            glsr_log()->error($error['message']);
112 16
        }
113 16
    }
114 16
115 16
    public function config(string $name, bool $filtered = true): array
116 16
    {
117 16
        $path = $this->filterString('config', "config/{$name}.php");
118
        $configFile = $this->path($path);
119
        $config = file_exists($configFile)
120 16
            ? include $configFile
121 16
            : [];
122
        $config = Arr::consolidate($config);
123 16
        // Don't filter the settings config!
124
        // They can be filtered with the "site-reviews/settings" filter hook
125
        if ($filtered && !Str::contains($name, ['integrations', 'settings'])) {
126
            $config = $this->filterArray("config/{$name}", $config);
127
        }
128
        return $config;
129 51
    }
130
131 51
    /**
132 51
     * @return mixed
133 51
     */
134 51
    public function constant(string $property, string $className = 'static')
135 51
    {
136
        $property = strtoupper($property);
137
        $constant = "{$className}::{$property}";
138 106
        return defined($constant)
139
            ? $this->filterString("const/{$property}", constant($constant))
140 106
            : '';
141 106
    }
142 106
143 27
    public function file(string $view): string
144
    {
145 106
        $view .= '.php';
146 106
        $filePaths = [];
147 106
        if (str_starts_with($view, 'templates/')) {
148 106
            $filePaths[] = $this->themePath(Str::removePrefix($view, 'templates/'));
149 106
        }
150
        $filePaths[] = $this->path($view);
151
        $filePaths[] = $this->path("views/{$view}");
152 18
        foreach ($filePaths as $file) {
153
            if (file_exists($file)) {
154
                return $file;
155
            }
156
        }
157
        return '';
158
    }
159
160 209
    /**
161
     * @param mixed ...$args
162 209
     *
163 209
     * @return mixed
164
     */
165
    public function filter(string $hook, ...$args)
166
    {
167
        do_action("{$this->id}/filter", $hook, $args);
168
        return apply_filters_ref_array("{$this->id}/{$hook}", $args);
169 26
    }
170
171 26
    /**
172 26
     * @param mixed ...$args
173
     */
174
    public function filterArrayUnique(string $hook, ...$args): array
175
    {
176
        $filtered = apply_filters_ref_array("{$this->id}/{$hook}", $args);
177
        return array_unique(array_filter(Cast::toArray($filtered)));
178 209
    }
179
180 209
    /**
181
     * @return static
182
     */
183 209
    public static function load()
184
    {
185
        if (empty(static::$instance)) {
186
            static::$instance = new static();
187
        }
188
        return static::$instance;
189
    }
190
191
    /**
192
     * @param mixed $fallback
193
     *
194
     * @return mixed
195
     */
196 143
    public function option(string $path = '', $fallback = '', string $cast = '')
197
    {
198 143
        return glsr_get_option($path, $fallback, $cast);
199 143
    }
200 3
201
    public function path(string $file = '', bool $realpath = true): string
202 143
    {
203 143
        $basedir = plugin_dir_path($this->file);
204
        if (!$realpath) {
205
            $basedir = trailingslashit(WP_PLUGIN_DIR).basename(dirname($this->file));
206 106
        }
207
        $basedir = trailingslashit($basedir);
208 106
        if (str_starts_with($file, $basedir)) {
209 106
            $file = substr($file, strlen($basedir));
210 106
        }
211
        $path = $basedir.ltrim(trim($file), '/');
212
        return $this->filterString('path', $path, $file);
213
    }
214 106
215 106
    public function render(string $view, array $data = []): void
216 106
    {
217
        $view = $this->filterString('render/view', $view, $data);
218
        $file = $this->filterString('views/file', $this->file($view), $view, $data);
219
        if (!file_exists($file)) {
220
            glsr_log()->error(sprintf('File not found: (%s) %s', $view, $file));
221
            return;
222
        }
223
        $data = $this->filterArray('views/data', $data, $view, $file);
224
        extract($data);
225
        include $file;
226
    }
227
228
    /**
229
     * @param mixed $args
230
     */
231
    public function request($args = []): Request
232
    {
233
        return new Request($args);
234
    }
235
236
    /**
237 27
     * @return mixed|false
238
     */
239 27
    public function runIf(string $className, ...$args)
240
    {
241
        return class_exists($className)
242
            ? call_user_func_array([glsr($className), 'handle'], $args)
243
            : false;
244
    }
245
246
    public function themePath(string $file = ''): string
247
    {
248 123
        return get_stylesheet_directory().'/'.$this->id.'/'.ltrim(trim($file), '/');
249
    }
250 123
251 123
    public function url(string $path = ''): string
252
    {
253 123
        $basedir = plugin_dir_path($this->file);
254 123
        if (str_starts_with($path, $basedir)) {
255 123
            $path = substr($path, strlen($basedir));
256
        }
257
        $url = esc_url(plugin_dir_url($this->file).ltrim(trim($path), '/'));
258
        return $this->filterString('url', $url, $path);
259
    }
260
261
    public function version(string $versionLevel = ''): string
262
    {
263 123
        return Helper::version($this->version, $versionLevel);
264
    }
265
}
266