Passed
Push — master ( ece31d...41b8a6 )
by Paul
10:20 queued 04:17
created

Application::file()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 4
eloc 10
c 1
b 1
f 0
nc 6
nop 1
dl 0
loc 14
ccs 11
cts 11
cp 1
crap 4
rs 9.9332
1
<?php
2
3
namespace GeminiLabs\SiteReviews;
4
5
use GeminiLabs\SiteReviews\Database\DefaultsManager;
6
use GeminiLabs\SiteReviews\Modules\Upgrader;
7
8
final class Application extends Container
9
{
10
    const CAPABILITY = 'edit_others_posts';
11
    const CRON_EVENT = 'site-reviews/schedule/session/purge';
12
    const ID = 'site-reviews';
13
    const PAGED_QUERY_VAR = 'reviews-page';
14
    const POST_TYPE = 'site-review';
15
    const PREFIX = 'glsr_';
16
    const TAXONOMY = 'site-review-category';
17
18
    public $defaults;
19
    public $deprecated = [];
20
    public $file;
21
    public $languages;
22
    public $mceShortcodes = []; //defined elsewhere
23
    public $name;
24
    public $reviewTypes;
25
    public $schemas = []; //defined elsewhere
26
    public $version;
27
28
    public function __construct()
29
    {
30
        static::$instance = $this;
31
        $this->file = realpath(trailingslashit(dirname(__DIR__)).static::ID.'.php');
32
        $plugin = get_file_data($this->file, [
33
            'languages' => 'Domain Path',
34
            'name' => 'Plugin Name',
35
            'version' => 'Version',
36
        ], 'plugin');
37
        array_walk($plugin, function ($value, $key) {
38
            $this->$key = $value;
39
        });
40
    }
41
42
    /**
43
     * @return void
44
     */
45 7
    public function activate()
46
    {
47 7
        $this->make(DefaultsManager::class)->set();
48 7
        $this->scheduleCronJob();
49 7
        $this->upgrade();
50 7
    }
51
52
    /**
53
     * @return void
54
     */
55
    public function catchFatalError()
56
    {
57
        $error = error_get_last();
58
        if (E_ERROR !== $error['type'] || false === strpos($error['message'], $this->path())) {
59
            return;
60
        }
61
        glsr_log()->error($error['message']);
62
    }
63
64
    /**
65
     * @param string $name
66
     * @return array
67
     */
68 7
    public function config($name)
69
    {
70 7
        $configFile = $this->path('config/'.$name.'.php');
71 7
        $config = file_exists($configFile)
72 7
            ? include $configFile
73 7
            : [];
74 7
        return apply_filters('site-reviews/config/'.$name, $config);
75
    }
76
77
    /**
78
     * @param string $property
79
     * @return string
80
     */
81 7
    public function constant($property, $className = 'static')
82
    {
83 7
        $constant = $className.'::'.$property;
84 7
        return defined($constant)
85 7
            ? apply_filters('site-reviews/const/'.$property, constant($constant))
86 7
            : '';
87
    }
88
89
    /**
90
     * @return void
91
     */
92
    public function deactivate()
93
    {
94
        $this->unscheduleCronJob();
95
    }
96
97
    /**
98
     * @param string $view
99
     * @return void|string
100
     */
101 7
    public function file($view)
102
    {
103 7
        $view.= '.php';
104 7
        $filePaths = [];
105 7
        if (glsr(Helper::class)->startsWith('templates/', $view)) {
106 7
            $filePaths[] = $this->themePath(glsr(Helper::class)->removePrefix('templates/', $view));
107
        }
108 7
        $filePaths[] = $this->path($view);
109 7
        $filePaths[] = $this->path('views/'.$view);
110 7
        foreach ($filePaths as $file) {
111 7
            if (!file_exists($file)) {
112 7
                continue;
113
            }
114 7
            return $file;
115
        }
116
    }
117
118
    /**
119
     * @return array
120
     */
121
    public function getDefaults()
122
    {
123
        if (empty($this->defaults)) {
124
            $this->defaults = $this->make(DefaultsManager::class)->get();
125
            $this->upgrade();
126
        }
127
        return apply_filters('site-reviews/get/defaults', $this->defaults);
128
    }
129
130
    /**
131
     * @return bool
132
     */
133
    public function getPermission($page = '')
134
    {
135
        $permissions = [
136
            'addons' => 'install_plugins',
137
            'settings' => 'manage_options',
138
            // 'welcome' => 'activate_plugins',
139
        ];
140
        return glsr_get($permissions, $page, $this->constant('CAPABILITY'));
141
    }
142
143
    /**
144
     * @return bool
145
     */
146
    public function hasPermission($page = '')
147
    {
148
        $isAdmin = $this->isAdmin();
149
        return !$isAdmin || ($isAdmin && current_user_can($this->getPermission($page)));
150
    }
151
152
    /**
153
     * @return void
154
     */
155
    public function init()
156
    {
157
        $this->make(Actions::class)->run();
158
        $this->make(Filters::class)->run();
159
    }
160
161
    /**
162
     * @return bool
163
     */
164
    public function isAdmin()
165
    {
166
        return is_admin() && !wp_doing_ajax();
167
    }
168
169
    /**
170
     * @param string $file
171
     * @return string
172
     */
173 7
    public function path($file = '', $realpath = true)
174
    {
175 7
        $path = plugin_dir_path($this->file);
176 7
        if (!$realpath) {
177 1
            $path = trailingslashit(WP_PLUGIN_DIR).basename(dirname($this->file));
178
        }
179 7
        $path = trailingslashit($path).ltrim(trim($file), '/');
180 7
        return apply_filters('site-reviews/path', $path, $file);
181
    }
182
183
    /**
184
     * @return void
185
     */
186
    public function registerAddons()
187
    {
188
        do_action('site-reviews/addon/register', $this);
189
    }
190
191
    /**
192
     * @return void
193
     */
194
    public function registerLanguages()
195
    {
196
        load_plugin_textdomain(static::ID, false,
197
            trailingslashit(plugin_basename($this->path()).'/'.$this->languages)
198
        );
199
    }
200
201
    /**
202
     * @return void
203
     */
204
    public function registerReviewTypes()
205
    {
206
        $types = apply_filters('site-reviews/addon/types', []);
207
        $this->reviewTypes = wp_parse_args($types, [
208
            'local' => __('Local', 'site-reviews'),
209
        ]);
210
    }
211
212
    /**
213
     * @param string $view
214
     * @return void
215
     */
216 7
    public function render($view, array $data = [])
217
    {
218 7
        $view = apply_filters('site-reviews/render/view', $view, $data);
219 7
        $file = apply_filters('site-reviews/views/file', $this->file($view), $view, $data);
220 7
        if (!file_exists($file)) {
221
            glsr_log()->error('File not found: '.$file);
222
            return;
223
        }
224 7
        $data = apply_filters('site-reviews/views/data', $data, $view);
225 7
        extract($data);
226 7
        include $file;
227 7
    }
228
229
    /**
230
     * @return void
231
     */
232 7
    public function scheduleCronJob()
233
    {
234 7
        if (wp_next_scheduled(static::CRON_EVENT)) {
235
            return;
236
        }
237 7
        wp_schedule_event(time(), 'twicedaily', static::CRON_EVENT);
238 7
    }
239
240
    /**
241
     * @param string $file
242
     * @return string
243
     */
244 7
    public function themePath($file = '')
245
    {
246 7
        return get_stylesheet_directory().'/'.static::ID.'/'.ltrim(trim($file), '/');
247
    }
248
249
    /**
250
     * @return void
251
     */
252
    public function unscheduleCronJob()
253
    {
254
        wp_unschedule_event(intval(wp_next_scheduled(static::CRON_EVENT)), static::CRON_EVENT);
255
    }
256
257
    /**
258
     * @return void
259
     */
260 7
    public function upgrade()
261
    {
262 7
        $this->make(Upgrader::class)->run();
263 7
    }
264
265
    /**
266
     * @param mixed $upgrader
267
     * @return void
268
     * @action upgrader_process_complete
269
     */
270
    public function upgraded($upgrader, array $data)
271
    {
272
        if (array_key_exists('plugins', $data)
273
            && in_array(plugin_basename($this->file), $data['plugins'])
274
            && 'update' === $data['action']
275
            && 'plugin' === $data['type']
276
        ) {
277
            $this->upgrade();
278
        }
279
    }
280
281
    /**
282
     * @param string $path
283
     * @return string
284
     */
285
    public function url($path = '')
286
    {
287
        $url = esc_url(plugin_dir_url($this->file).ltrim(trim($path), '/'));
288
        return apply_filters('site-reviews/url', $url, $path);
289
    }
290
291
    /**
292
     * @param string $versionLevel
293
     * @return string
294
     */
295
    public function version($versionLevel = '')
296
    {
297
        $pattern = '/^v?(\d{1,5})(\.\d++)?(\.\d++)?(.+)?$/i';
298
        preg_match($pattern, $this->version, $matches);
299
        switch ($versionLevel) {
300
            case 'major':
301
                $version = glsr_get($matches, 1);
302
                break;
303
            case 'minor':
304
                $version = glsr_get($matches, 1).glsr_get($matches, 2);
305
                break;
306
            case 'patch':
307
                $version = glsr_get($matches, 1).glsr_get($matches, 2).glsr_get($matches, 3);
308
                break;
309
        }
310
        return empty($version)
311
            ? $this->version
312
            : $version;
313
    }
314
}
315