Passed
Push — master ( 6b35fa...ccb079 )
by Paul
10:24 queued 05:13
created

Application::render()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2.0438

Importance

Changes 0
Metric Value
cc 2
eloc 8
nc 2
nop 2
dl 0
loc 11
ccs 7
cts 9
cp 0.7778
crap 2.0438
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace GeminiLabs\SiteReviews;
4
5
use GeminiLabs\SiteReviews\Database\DefaultsManager;
6
use GeminiLabs\SiteReviews\Helpers\Arr;
7
use GeminiLabs\SiteReviews\Helpers\Str;
8
9
/**
10
 * @property string $capability
11
 * @property string $cron_event
12
 * @property string $id
13
 * @property string $paged_query_var
14
 * @property string $post_type
15
 * @property string $prefix
16
 * @property string $taxonomy
17
 */
18
final class Application extends Container
19
{
20
    const CAPABILITY = 'edit_others_posts';
21
    const CRON_EVENT = 'site-reviews/schedule/session/purge';
22
    const ID = 'site-reviews';
23
    const PAGED_QUERY_VAR = 'reviews-page';
24
    const POST_TYPE = 'site-review';
25
    const PREFIX = 'glsr_';
26
    const TAXONOMY = 'site-review-category';
27
28
    public $addons = [];
29
    public $defaults;
30
    public $deprecated = [];
31
    public $file;
32
    public $languages;
33
    public $mceShortcodes = []; //defined elsewhere
34
    public $name;
35
    public $postTypeColumns = []; // defined elsewhere
36
    public $reviewTypes;
37
    public $schemas = []; //defined elsewhere
38
    public $version;
39
40
    public function __construct()
41
    {
42
        static::$instance = $this;
43
        $this->file = realpath(trailingslashit(dirname(__DIR__)).static::ID.'.php');
44
        $plugin = get_file_data($this->file, [
45
            'languages' => 'Domain Path',
46
            'name' => 'Plugin Name',
47
            'version' => 'Version',
48
        ], 'plugin');
49
        array_walk($plugin, function ($value, $key) {
50
            $this->$key = $value;
51
        });
52
    }
53
54
    /**
55
     * @return void
56
     */
57 7
    public function activate()
58
    {
59 7
        $this->scheduleCronJob();
60 7
        add_option(static::PREFIX.'activated', true);
61 7
    }
62
63
    /**
64
     * @param string $view
65
     * @return string
66
     */
67 7
    public function build($view, array $data = [])
68
    {
69 7
        ob_start();
70 7
        $this->render($view, $data);
71 7
        return ob_get_clean();
72
    }
73
74
    /**
75
     * @param string $capability
76
     * @return bool
77
     */
78 1
    public function can($capability)
79
    {
80 1
        return $this->make(Role::class)->can($capability);
81
    }
82
83
    /**
84
     * @return void
85
     */
86
    public function catchFatalError()
87
    {
88
        $error = error_get_last();
89
        if (E_ERROR !== $error['type'] || !Str::contains($error['message'], $this->path())) {
90
            return;
91
        }
92
        glsr_log()->error($error['message']);
93
    }
94
95
    /**
96
     * @param string $name
97
     * @return array
98
     */
99 7
    public function config($name)
100
    {
101 7
        $configFile = $this->path('config/'.$name.'.php');
102 7
        $config = file_exists($configFile)
103 7
            ? include $configFile
104 7
            : [];
105 7
        return apply_filters('site-reviews/config/'.$name, $config);
106
    }
107
108
    /**
109
     * @param string $property
110
     * @return string
111
     */
112 7
    public function constant($property, $className = 'static')
113
    {
114 7
        $constant = $className.'::'.$property;
115 7
        return defined($constant)
116 7
            ? apply_filters('site-reviews/const/'.$property, constant($constant))
117 7
            : '';
118
    }
119
120
    /**
121
     * @return void
122
     */
123
    public function deactivate()
124
    {
125
        $this->unscheduleCronJob();
126
    }
127
128
    /**
129
     * @param string $view
130
     * @return void|string
131
     */
132 7
    public function file($view)
133
    {
134 7
        $view.= '.php';
135 7
        $filePaths = [];
136 7
        if (Str::startsWith('templates/', $view)) {
137 7
            $filePaths[] = $this->themePath(Str::removePrefix('templates/', $view));
138
        }
139 7
        $filePaths[] = $this->path($view);
140 7
        $filePaths[] = $this->path('views/'.$view);
141 7
        foreach ($filePaths as $file) {
142 7
            if (!file_exists($file)) {
143 7
                continue;
144
            }
145 7
            return $file;
146
        }
147
    }
148
149
    /**
150
     * @return array
151
     */
152
    public function getDefaults()
153
    {
154
        if (empty($this->defaults)) {
155
            $this->defaults = $this->make(DefaultsManager::class)->get();
156
        }
157
        return apply_filters('site-reviews/get/defaults', $this->defaults);
158
    }
159
160
    /**
161
     * @param string $page
162
     * @param string $tab
163
     * @return string
164
     */
165
    public function getPermission($page = '', $tab = 'index')
166
    {
167
        $fallback = 'edit_posts';
168
        $permissions = [
169
            'addons' => 'install_plugins',
170
            'documentation' => [
171
                'faq' => 'edit_others_posts',
172
                'functions' => 'manage_options',
173
                'hooks' => 'edit_others_posts',
174
                'index' => 'edit_posts',
175
                'support' => 'edit_others_posts',
176
            ],
177
            'settings' => 'manage_options',
178
            'tools' => [
179
                'console' => 'edit_others_posts',
180
                'general' => 'edit_others_posts',
181
                'index' => 'edit_others_posts',
182
                'sync' => 'manage_options',
183
                'system-info' => 'edit_others_posts',
184
            ]
185
        ];
186
        $permission = Arr::get($permissions, $page, $fallback);
187
        if (is_array($permission)) {
188
            $permission = Arr::get($permission, $tab, $fallback);
189
        }
190
        return empty($permission) || !is_string($permission)
191
            ? $fallback
192
            : $permission;
193
    }
194
195
    /**
196
     * @param string $page
197
     * @param string $tab
198
     * @return bool
199
     */
200
    public function hasPermission($page = '', $tab = 'index')
201
    {
202
        $isAdmin = $this->isAdmin();
203
        return !$isAdmin || ($isAdmin && $this->can($this->getPermission($page, $tab)));
204
    }
205
206
    /**
207
     * @return void
208
     */
209
    public function init()
210
    {
211
        $this->make(Actions::class)->run();
212
        $this->make(Filters::class)->run();
213
    }
214
215
    /**
216
     * @return bool
217
     */
218
    public function isAdmin()
219
    {
220
        return is_admin() && !wp_doing_ajax();
221
    }
222
223
    /**
224
     * @param string $file
225
     * @return string
226
     */
227 7
    public function path($file = '', $realpath = true)
228
    {
229 7
        $path = plugin_dir_path($this->file);
230 7
        if (!$realpath) {
231
            $path = trailingslashit(WP_PLUGIN_DIR).basename(dirname($this->file));
232
        }
233 7
        $path = trailingslashit($path).ltrim(trim($file), '/');
234 7
        return apply_filters('site-reviews/path', $path, $file);
235
    }
236
237
    /**
238
     * @param object $addon
239
     * @return void
240
     */
241
    public function register($addon)
242
    {
243
        try {
244
            $reflection = new \ReflectionClass($addon);
245
            if ($id = $reflection->getConstant('ID')) {
246
                $this->addons[] = $id;
247
                $this->bind($id, $addon);
248
                $addon->init();
249
            }
250
        } catch(\ReflectionException $e) {
251
            glsr_log()->error('Attempted to register an invalid addon.');
252
        }
253
    }
254
255
    /**
256
     * @return void
257
     */
258
    public function registerAddons()
259
    {
260
        do_action('site-reviews/addon/register', $this);
261
    }
262
263
    /**
264
     * @return void
265
     */
266
    public function registerLanguages()
267
    {
268
        load_plugin_textdomain(static::ID, false,
269
            trailingslashit(plugin_basename($this->path()).'/'.$this->languages)
270
        );
271
    }
272
273
    /**
274
     * @return void
275
     */
276
    public function registerReviewTypes()
277
    {
278
        $types = apply_filters('site-reviews/addon/types', []);
279
        $this->reviewTypes = wp_parse_args($types, [
280
            'local' => __('Local', 'site-reviews'),
281
        ]);
282
    }
283
284
    /**
285
     * @param string $view
286
     * @return void
287
     */
288 7
    public function render($view, array $data = [])
289
    {
290 7
        $view = apply_filters('site-reviews/render/view', $view, $data);
291 7
        $file = apply_filters('site-reviews/views/file', $this->file($view), $view, $data);
292 7
        if (!file_exists($file)) {
293
            glsr_log()->error('File not found: '.$file);
294
            return;
295
        }
296 7
        $data = apply_filters('site-reviews/views/data', $data, $view);
297 7
        extract($data);
298 7
        include $file;
299 7
    }
300
301
    /**
302
     * @return void
303
     */
304 7
    public function scheduleCronJob()
305
    {
306 7
        if (false === wp_next_scheduled(static::CRON_EVENT)) {
307 7
            wp_schedule_event(time(), 'twicedaily', static::CRON_EVENT);
308
        }
309 7
    }
310
311
    /**
312
     * @return void
313
     */
314 1
    public function setDefaults()
315
    {
316 1
        if (get_option(static::PREFIX.'activated')) {
317 1
            $this->make(DefaultsManager::class)->set();
318 1
            delete_option(static::PREFIX.'activated');
319
        }
320 1
    }
321
322
    /**
323
     * @param string $file
324
     * @return string
325
     */
326 7
    public function themePath($file = '')
327
    {
328 7
        return get_stylesheet_directory().'/'.static::ID.'/'.ltrim(trim($file), '/');
329
    }
330
331
    /**
332
     * @return void
333
     */
334
    public function unscheduleCronJob()
335
    {
336
        wp_unschedule_event(intval(wp_next_scheduled(static::CRON_EVENT)), static::CRON_EVENT);
337
    }
338
339
    /**
340
     * @param string $path
341
     * @return string
342
     */
343
    public function url($path = '')
344
    {
345
        $url = esc_url(plugin_dir_url($this->file).ltrim(trim($path), '/'));
346
        return apply_filters('site-reviews/url', $url, $path);
347
    }
348
349
    /**
350
     * @param string $versionLevel
351
     * @return string
352
     */
353
    public function version($versionLevel = '')
354
    {
355
        $pattern = '/^v?(\d{1,5})(\.\d++)?(\.\d++)?(.+)?$/i';
356
        preg_match($pattern, $this->version, $matches);
357
        switch ($versionLevel) {
358
            case 'major':
359
                $version = Arr::get($matches, 1);
360
                break;
361
            case 'minor':
362
                $version = Arr::get($matches, 1).Arr::get($matches, 2);
363
                break;
364
            case 'patch':
365
                $version = Arr::get($matches, 1).Arr::get($matches, 2).Arr::get($matches, 3);
366
                break;
367
        }
368
        return empty($version)
369
            ? $this->version
370
            : $version;
371
    }
372
}
373