Passed
Branch develop (5de766)
by Paul
13:18
created

helpers.php (3 issues)

1
<?php
2
3
use GeminiLabs\SiteReviews\Application;
4
use GeminiLabs\SiteReviews\Arguments;
5
use GeminiLabs\SiteReviews\BlackHole;
6
use GeminiLabs\SiteReviews\Commands\CreateReview;
7
use GeminiLabs\SiteReviews\Database\OptionManager;
8
use GeminiLabs\SiteReviews\Database\RatingManager;
9
use GeminiLabs\SiteReviews\Database\ReviewManager;
10
use GeminiLabs\SiteReviews\Exceptions\BindingResolutionException;
11
use GeminiLabs\SiteReviews\Helpers\Arr;
12
use GeminiLabs\SiteReviews\Helpers\Cast;
13
use GeminiLabs\SiteReviews\Helpers\Str;
14
use GeminiLabs\SiteReviews\Modules\Backtrace;
15
use GeminiLabs\SiteReviews\Modules\Console;
16
use GeminiLabs\SiteReviews\Modules\Dump;
17
use GeminiLabs\SiteReviews\Modules\Html\Builder;
18
use GeminiLabs\SiteReviews\Modules\Html\Partial;
19
use GeminiLabs\SiteReviews\Modules\Rating;
20
use GeminiLabs\SiteReviews\Request;
21
use GeminiLabs\SiteReviews\Review;
22
23
defined('ABSPATH') || exit;
24
25
/**
26
 * Alternate method of using the functions without having to use `function_exists()`
27
 * Example: apply_filters('glsr_get_reviews', [], ['assigned_posts' => 'post_id']);
28
 */
29
add_action('plugins_loaded', function () {
30
    $hooks = [
31
        'glsr_create_review' => 2,
32
        'glsr_debug' => 10,
33
        'glsr_get' => 4,
34
        'glsr_get_option' => 4,
35
        'glsr_get_options' => 1,
36
        'glsr_get_ratings' => 2,
37
        'glsr_get_review' => 2,
38
        'glsr_get_reviews' => 2,
39
        'glsr_log' => 3,
40
        'glsr_star_rating' => 4,
41
        'glsr_trace' => 2,
42
        'glsr_update_review' => 3,
43
    ];
44
    foreach ($hooks as $function => $acceptedArgs) {
45
        add_filter($function, function () use ($function) {
46
            $args = func_get_args();
47
            array_shift($args); // remove the fallback value
48
            return call_user_func_array($function, $args);
49
        }, 10, $acceptedArgs);
50
    }
51
});
52
53
/**
54
 * @return mixed
55
 */
56
function glsr($alias = null, array $parameters = [])
57
{
58
    if (is_null($alias)) {
59
        return Application::load();
60
    }
61
    try {
62
        return Application::load()->make($alias, $parameters);
63
    } catch (BindingResolutionException $e) {
64
        glsr_log()->error($e->getMessage());
65
        return Application::load()->make(BlackHole::class, compact('alias'));
66
    }
67
}
68
69
/**
70
 * @param string $page
71
 * @param string $tab
72
 * @param string $sub
73
 *
74
 * @return string
75
 */
76
function glsr_admin_url($page = '', $tab = '', $sub = '')
77
{
78
    if ('welcome' === $page) {
79
        $page = glsr()->id.'-welcome';
80
        $args = array_filter(compact('page', 'tab'));
81
        return add_query_arg($args, admin_url('index.php'));
82
    }
83
    if (!empty($page)) {
84
        $page = Str::dashCase(glsr()->prefix.$page);
85
    }
86
    $post_type = glsr()->post_type;
87
    $args = array_filter(compact('post_type', 'page', 'tab', 'sub'));
88
    return add_query_arg($args, admin_url('edit.php'));
89
}
90
91
/**
92
 * @param string|array $attrs
93
 */
94
function glsr_admin_link(string $path = '', $attrs = [], string $expand = ''): string
95
{
96
    $parts = explode('.', $path);
97
    $parts = array_slice(array_pad(array_filter($parts, 'is_string'), 3, ''), 0, 3);
98
    $text = trim(is_string($attrs) ? $attrs : ($attrs['text'] ?? ''));
99
    if (empty($text)) {
100
        $texts = [
101
            'addons' => _x('Addons', 'admin-text', 'site-reviews'),
102
            'api' => _x('API', 'admin-text', 'site-reviews'),
103
            'console' => _x('Console', 'admin-text', 'site-reviews'),
104
            'documentation' => _x('Help & Support', 'admin-text', 'site-reviews'),
105
            'faq' => _x('FAQ', 'admin-text', 'site-reviews'),
106
            'forms' => _x('Forms', 'admin-text', 'site-reviews'),
107
            'functions' => _x('Functions', 'admin-text', 'site-reviews'),
108
            'general' => _x('General', 'admin-text', 'site-reviews'),
109
            'hooks' => _x('Hooks', 'admin-text', 'site-reviews'),
110
            'integrations' => _x('Integrations', 'admin-text', 'site-reviews'),
111
            'licenses' => _x('Licenses', 'admin-text', 'site-reviews'),
112
            'profilepress' => 'ProfilePress',
113
            'reviews' => _x('Reviews', 'admin-text', 'site-reviews'),
114
            'scheduled' => _x('Scheduled Actions', 'admin-text', 'site-reviews'),
115
            'schema' => _x('Schema', 'admin-text', 'site-reviews'),
116
            'settings' => _x('Settings', 'admin-text', 'site-reviews'),
117
            'shortcodes' => _x('Shortcodes', 'admin-text', 'site-reviews'),
118
            'strings' => _x('Strings', 'admin-text', 'site-reviews'),
119
            'support' => _x('Support', 'admin-text', 'site-reviews'),
120
            'surecart' => 'SureCart',
121
            'system-info' => _x('System Info', 'admin-text', 'site-reviews'),
122
            'tools' => _x('Tools', 'admin-text', 'site-reviews'),
123
            'ultimatemember' => 'Ultimate Member',
124
            'woocommerce' => 'WooCommerce',
125
        ];
126
        $textParts = array_filter([
127
            $texts[$parts[0]] ?? ucfirst($parts[0]),
128
            $texts[$parts[1]] ?? ucfirst($parts[1]),
129
            $texts[$parts[2]] ?? ucfirst($parts[2]),
130
        ]);
131
        $text = implode(' &rarr; ', $textParts);
132
    }
133
    $url = call_user_func_array('glsr_admin_url', $parts);
134
    $attrs = Arr::consolidate($attrs);
135
    $attrs['href'] = $url;
136
    $attrs['text'] = $text ?: _x('All Reviews', 'admin-text', 'site-reviews');
137
    return glsr(Builder::class)->a(wp_parse_args($attrs, [
138
        'data-expand' => $expand,
139
    ]));
140
}
141
142
/**
143
 * @return Review|false
144
 */
145
function glsr_create_review($values = [])
146
{
147
    $values = Arr::removeEmptyValues(Arr::consolidate($values));
148
    $request = new Request($values);
149
    $review = false;
150
    glsr()->store('glsr_create_review', true);
151
    $command = new CreateReview($request);
152
    if ($command->isRequestValid()) {
153
        $review = glsr(ReviewManager::class)->create($command);
154
    }
155
    glsr()->discard('glsr_create_review');
156
    return $review;
157
}
158
159
/**
160
 * @return WP_Screen|object
161
 */
162
function glsr_current_screen()
163
{
164
    if (function_exists('get_current_screen')) {
165
        $screen = get_current_screen();
1 ignored issue
show
Are you sure the assignment to $screen is correct as get_current_screen() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
166
    }
167
    return empty($screen)
168
        ? (object) array_fill_keys(['action', 'base', 'id', 'post_type'], '')
169
        : $screen;
170
}
171
172
/**
173
 * @param mixed ...$vars
174
 */
175
function glsr_debug(...$vars): void
176
{
177
    if (1 === count($vars)) {
178
        $dump = glsr(Dump::class)->dump($vars[0]);
179
        $value = htmlspecialchars($dump, ENT_QUOTES, 'UTF-8');
180
        printf('<div class="glsr-debug"><pre>%s</pre></div>', $value);
181
    } else {
182
        echo '<div class="glsr-debug-group">';
183
        foreach ($vars as $var) {
184
            glsr_debug($var);
185
        }
186
        echo '</div>';
187
    }
188
}
189
190
/**
191
 * @param string|int $path
192
 * @param mixed      $fallback
193
 *
194
 * @return mixed
195
 */
196
function glsr_get($array, $path = '', $fallback = '')
197
{
198
    return Arr::get($array, $path, $fallback);
199
}
200
201
/**
202
 * @param string $path
203
 * @param mixed  $fallback
204
 * @param string $cast
205
 *
206
 * @return mixed
207
 */
208
function glsr_get_option($path = '', $fallback = '', $cast = '')
209
{
210
    return is_string($path)
0 ignored issues
show
The condition is_string($path) is always true.
Loading history...
211
        ? glsr(OptionManager::class)->get(Str::prefix($path, 'settings.'), $fallback, $cast)
212
        : $fallback;
213
}
214
215
/**
216
 * @return array
217
 */
218
function glsr_get_options()
219
{
220
    return glsr(OptionManager::class)->get('settings');
221
}
222
223
/**
224
 * @return Arguments
225
 */
226
function glsr_get_ratings($args = [])
227
{
228
    $counts = glsr(RatingManager::class)->ratings(Arr::consolidate($args));
229
    return new Arguments([
230
        'average' => glsr(Rating::class)->average($counts),
231
        'maximum' => Rating::max(),
232
        'minimum' => Rating::min(),
233
        'ranking' => glsr(Rating::class)->ranking($counts),
234
        'ratings' => $counts,
235
        'reviews' => array_sum($counts),
236
    ]);
237
}
238
239
function glsr_get_review($postId): Review
240
{
241
    return glsr(ReviewManager::class)->get(Cast::toInt($postId));
242
}
243
244
/**
245
 * @return GeminiLabs\SiteReviews\Reviews
246
 */
247
function glsr_get_reviews($args = [])
248
{
249
    return glsr(ReviewManager::class)->reviews(Arr::consolidate($args));
250
}
251
252
/**
253
 * @param mixed ...$args
254
 *
255
 * @return Console
256
 */
257
function glsr_log(...$args)
258
{
259
    $console = glsr(Console::class);
260
    return !empty($args)
0 ignored issues
show
Bug Best Practice introduced by
The expression return ! empty($args) ? ...ug'), $args) : $console also could return the type callable which is incompatible with the documented return type GeminiLabs\SiteReviews\Modules\Console.
Loading history...
261
        ? call_user_func_array([$console, 'debug'], $args)
262
        : $console;
263
}
264
265
function glsr_premium_link(string $path, $attrs = []): string
266
{
267
    $url = glsr_premium_url($path);
268
    $texts = [
269
        'license-keys' => _x('License Keys', 'admin-text', 'site-reviews'),
270
        'site-reviews-actions' => _x('Review Actions', 'admin-text', 'site-reviews'),
271
        'site-reviews-authors' => _x('Review Authors', 'admin-text', 'site-reviews'),
272
        'site-reviews-filters' => _x('Review Filters', 'admin-text', 'site-reviews'),
273
        'site-reviews-forms' => _x('Review Forms', 'admin-text', 'site-reviews'),
274
        'site-reviews-images' => _x('Review Images', 'admin-text', 'site-reviews'),
275
        'site-reviews-notifications' => _x('Review Notifications', 'admin-text', 'site-reviews'),
276
        'site-reviews-premium' => _x('Site Reviews Premium', 'admin-text', 'site-reviews'),
277
        'site-reviews-themes' => _x('Review Themes', 'admin-text', 'site-reviews'),
278
    ];
279
    $text = trim(is_string($attrs) ? $attrs : ($attrs['text'] ?? ''));
280
    $text = $text ?: ($texts[$path] ?? $url);
281
    $attrs = Arr::consolidate($attrs);
282
    $attrs['href'] = $url;
283
    $attrs['target'] = '_blank';
284
    $attrs['text'] = $text;
285
    return glsr(Builder::class)->a($attrs);
286
}
287
288
function glsr_premium_url(string $path = '/'): string
289
{
290
    $baseUrl = 'https://niftyplugins.com/';
291
    $paths = [
292
        'account' => '/account/',
293
        'addons' => '/plugins/',
294
        'license-keys' => '/account/license-keys/',
295
        'site-reviews-actions' => '/plugins/site-reviews-actions/',
296
        'site-reviews-authors' => '/plugins/site-reviews-authors/',
297
        'site-reviews-filters' => '/plugins/site-reviews-filters/',
298
        'site-reviews-forms' => '/plugins/site-reviews-forms/',
299
        'site-reviews-images' => '/plugins/site-reviews-images/',
300
        'site-reviews-notifications' => '/plugins/site-reviews-notifications/',
301
        'site-reviews-premium' => '/plugins/site-reviews-premium/',
302
        'site-reviews-themes' => '/plugins/site-reviews-themes/',
303
        'support' => '/account/support/',
304
    ];
305
    $urlPath = trim($paths[$path] ?? $path);
306
    $urlPath = trailingslashit(ltrim($urlPath, '/'));
307
    return esc_url(trailingslashit($baseUrl).$urlPath);
308
}
309
310
/**
311
 * @param string $path
312
 * @param mixed  $value
313
 *
314
 * @return array
315
 */
316
function glsr_set(array $data, $path, $value)
317
{
318
    return Arr::set($data, $path, $value);
319
}
320
321
/**
322
 * @param mixed    $rating
323
 * @param int|null $reviews
324
 *
325
 * @return string
326
 */
327
function glsr_star_rating($rating, $reviews = 0, array $args = [])
328
{
329
    return glsr(Partial::class)->build('star-rating', [
330
        'args' => $args,
331
        'rating' => $rating,
332
        'reviews' => $reviews,
333
    ]);
334
}
335
336
/**
337
 * @param int $limit
338
 *
339
 * @return void
340
 */
341
function glsr_trace($limit = 5)
342
{
343
    glsr_log(glsr(Backtrace::class)->trace($limit));
344
}
345
346
/**
347
 * @param int $postId
348
 *
349
 * @return Review|false
350
 */
351
function glsr_update_review($postId, $values = [])
352
{
353
    $postId = Cast::toInt($postId);
354
    $values = Arr::consolidate($values);
355
    glsr()->store('glsr_update_review', true);
356
    $result = glsr(ReviewManager::class)->update($postId, $values);
357
    glsr()->discard('glsr_update_review');
358
    return $result;
359
}
360
361
/**
362
 * @return int
363
 */
364
function glsr_user_count()
365
{
366
    if (function_exists('get_user_count')) {
367
        return get_user_count();
368
    }
369
    return Arr::getAs('int', count_users(), 'total_users');
370
}
371