Passed
Push — master ( 14a327...e5b44f )
by Paul
20:18 queued 10:35
created

Application   A

Complexity

Total Complexity 38

Size/Duplication

Total Lines 233
Duplicated Lines 0 %

Test Coverage

Coverage 5.49%

Importance

Changes 3
Bugs 0 Features 2
Metric Value
wmc 38
eloc 95
c 3
b 0
f 2
dl 0
loc 233
ccs 5
cts 91
cp 0.0549
rs 9.36

12 Methods

Rating   Name   Duplication   Size   Complexity  
A isAdmin() 0 3 3
A getPermission() 0 11 4
A deactivate() 0 3 1
A addon() 0 6 2
A hasPermission() 0 4 2
A can() 0 3 1
A init() 0 14 4
A license() 0 24 4
A storeDefaults() 0 8 3
A settings() 0 10 3
A register() 0 11 2
B update() 0 21 9
1
<?php
2
3
namespace GeminiLabs\SiteReviews;
4
5
use GeminiLabs\SiteReviews\Addons\Updater;
6
use GeminiLabs\SiteReviews\Database\DefaultsManager;
7
use GeminiLabs\SiteReviews\Database\OptionManager;
8
use GeminiLabs\SiteReviews\Database\SqlSchema;
9
use GeminiLabs\SiteReviews\Defaults\PermissionDefaults;
10
use GeminiLabs\SiteReviews\Helpers\Arr;
11
use GeminiLabs\SiteReviews\Modules\Migrate;
12
13
/**
14
 * @property array $addons
15
 * @property string $capability
16
 * @property string $cron_event
17
 * @property array $db_version
18
 * @property array $defaults
19
 * @property string $export_key
20
 * @property string $file
21
 * @property string $id
22
 * @property string $languages
23
 * @property string $name
24
 * @property string $paged_handle
25
 * @property string $paged_query_var
26
 * @property string $post_type
27
 * @property string $prefix
28
 * @property array $session
29
 * @property \GeminiLabs\SiteReviews\Arguments $storage
30
 * @property string $taxonomy
31
 * @property array $updated
32
 * @property string $version
33
 * @property string $testedTo;
34
 */
35
final class Application extends Container
36
{
37
    use Plugin;
38
    use Session;
39
    use Storage;
40
41
    const DB_VERSION = '1.1';
42
    const EXPORT_KEY = '_glsr_export';
43
    const ID = 'site-reviews';
44
    const PAGED_HANDLE = 'pagination_request';
45
    const PAGED_QUERY_VAR = 'reviews-page'; // filtered
46
    const POST_TYPE = 'site-review';
47
    const PREFIX = 'glsr_';
48
    const TAXONOMY = 'site-review-category';
49
50
    /**
51
     * @var array
52
     */
53
    protected $addons = [];
54
55
    /**
56
     * @var array
57
     */
58
    protected $defaults;
59
60
    /**
61
     * @var string
62
     */
63
    protected $name;
64
65
    /**
66
     * @var array
67
     */
68
    protected $settings;
69
70
    /**
71
     * @var array
72
     */
73
    protected $updated = [];
74
75
    /**
76
     * @param string $addonId
77
     * @return false|\GeminiLabs\SiteReviews\Addons\Addon
78
     */
79
    public function addon($addonId)
80
    {
81
        if (isset($this->addons[$addonId])) {
82
            return $this->addons[$addonId];
83
        }
84
        return false;
85
    }
86
87
    /**
88
     * @param string $capability
89
     * @param mixed ...$args
90
     * @return bool
91
     */
92
    public function can($capability, ...$args)
93
    {
94
        return $this->make(Role::class)->can($capability, ...$args);
95
    }
96
97
    /**
98
     * @param bool $networkDeactivating
99
     * @return void
100
     * @callback register_deactivation_hook
101
     */
102
    public function deactivate($networkDeactivating)
103
    {
104
        $this->make(Install::class)->deactivate($networkDeactivating);
105
    }
106
107
    /**
108
     * @param string $page
109
     * @param string $tab
110
     * @return string
111
     */
112
    public function getPermission($page = '', $tab = 'index')
113
    {
114
        $fallback = 'edit_posts';
115
        $permissions = $this->make(PermissionDefaults::class)->defaults();
116
        $permission = Arr::get($permissions, $page, $fallback);
117
        if (is_array($permission)) {
118
            $permission = Arr::get($permission, $tab, $fallback);
119
        }
120
        return empty($permission) || !is_string($permission)
121
            ? $fallback
122
            : $permission;
123
    }
124
125
    /**
126
     * @param string $page
127
     * @param string $tab
128
     * @return bool
129
     */
130
    public function hasPermission($page = '', $tab = 'index')
131
    {
132
        $isAdmin = $this->isAdmin();
133
        return !$isAdmin || $this->can($this->getPermission($page, $tab));
134
    }
135
136
    /**
137
     * @return void
138
     */
139
    public function init()
140
    {
141
        // Ensure the custom database tables exist, this is needed in cases
142
        // where the plugin has been updated instead of activated.
143
        $version = get_option(static::PREFIX.'db_version');
144
        if (empty($version)) {
145
            $this->make(Install::class)->run();
146
        } elseif ('1.1' === $version) { // @todo remove this in v5.12.0
147
            if (!$this->make(SqlSchema::class)->columnExists('ratings', 'terms')) {
148
                $this->make(Migrate::class)->reset();
149
                update_option(static::PREFIX.'db_version', '1.0');
150
            }
151
        }
152
        $this->make(Hooks::class)->run();
153
    }
154
155
    /**
156
     * @return bool
157
     */
158 18
    public function isAdmin()
159
    {
160 18
        return (is_admin() || is_network_admin()) && !wp_doing_ajax();
161
    }
162
163
    /**
164
     * @param object|string $addon
165
     * @return void
166
     */
167
    public function license($addon)
168
    {
169
        try {
170
            $settings = $this->settings(); // populate the initial settings
171
            $reflection = new \ReflectionClass($addon);
172
            $id = $reflection->getConstant('ID');
173
            $licensed = $reflection->getConstant('LICENSED');
174
            $name = $reflection->getConstant('NAME');
175
            if (true !== $licensed || 2 !== count(array_filter([$id, $name]))) {
176
                return;
177
            }
178
            $license = [
179
                'settings.licenses.'.$id => [
180
                    'class' => 'glsr-license-key regular-text',
181
                    'default' => '',
182
                    'label' => $name,
183
                    'tooltip' => sprintf(_x('Make sure to activate your website domain with your license before adding it here. You can do this by visiting the %s page on your Nifty Plugins account and clicking the "Manage Sites" button.', 'admin-text', 'site-reviews'),
184
                        sprintf('<a href="https://niftyplugins.com/account/license-keys/" target="_blank">%s</a>', _x('License Keys', 'admin-text', 'site-reviews'))
185
                    ),
186
                    'type' => 'text',
187
                ],
188
            ];
189
            $this->settings = array_merge($license, $settings);
190
        } catch (\ReflectionException $e) {
191
            // Fail silently
192
        }
193
    }
194
195
    /**
196
     * @param string|object $addon
197
     * @return void
198
     */
199
    public function register($addon)
200
    {
201
        try {
202
            $reflection = new \ReflectionClass($addon); // make sure that the class exists
203
            $addon = $reflection->getName();
204
            $this->addons[$addon::ID] = $addon;
205
            $this->singleton($addon); // this goes first!
206
            $this->alias($addon::ID, $this->make($addon)); // @todo for some reason we have to link an alias to an instantiated class
207
            $this->make($addon)->init();
208
        } catch (\ReflectionException $e) {
209
            glsr_log()->error('Attempted to register an invalid addon.');
210
        }
211
    }
212
213
    /**
214
     * @return array
215
     */
216 10
    public function settings()
217
    {
218 10
        if (empty($this->settings)) {
219
            $settings = $this->filterArray('addon/settings', $this->config('settings'));
220
            array_walk($settings, function (&$setting) {
221
                isset($setting['default']) ?: $setting['default'] = '';
222
            });
223
            $this->settings = $settings;
224
        }
225 10
        return $this->settings;
226
    }
227
228
    /**
229
     * @return void
230
     */
231
    public function storeDefaults()
232
    {
233
        if (empty($this->defaults)) {
234
            $defaults = $this->make(DefaultsManager::class)->get();
235
            $this->defaults = $this->filterArray('get/defaults', $defaults);
236
        }
237
        if (empty(get_option(OptionManager::databaseKey()))) {
238
            update_option(OptionManager::databaseKey(), $this->defaults);
239
        }
240
    }
241
242
    /**
243
     * @param object|string $addon
244
     * @param string $file
245
     * @return void
246
     */
247
    public function update($addon, $file)
248
    {
249
        if (!current_user_can('manage_options') && !(defined('DOING_CRON') && DOING_CRON)) {
250
            return;
251
        }
252
        if (!file_exists($file)) {
253
            glsr_log()->error("Add-on does not exist: $file")->debug($addon);
254
        }
255
        try {
256
            $reflection = new \ReflectionClass($addon);
257
            $addonId = $reflection->getConstant('ID');
258
            $licensed = $reflection->getConstant('LICENSED');
259
            $updateUrl = $reflection->getConstant('UPDATE_URL');
260
            if ($addonId && $updateUrl && !array_key_exists($addonId, $this->updated)) {
261
                $this->license($addon);
262
                $license = glsr_get_option('licenses.'.$addonId);
263
                $updater = new Updater($updateUrl, $file, $addonId, compact('license'));
264
                $updater->init();
265
                $this->updated[$addonId] = compact('file', 'licensed', 'updateUrl'); // store details for license verification in settings
266
            }
267
        } catch (\ReflectionException $e) {
268
            // We don't need to log an error here.
269
        }
270
    }
271
}
272