Passed
Push — develop ( 5de766...610859 )
by Paul
13:53
created

helpers.php (1 issue)

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
use GeminiLabs\SiteReviews\Reviews;
23
24
defined('ABSPATH') || exit;
25
26
/*
27
 * Alternate method of using the functions without having to use `function_exists()`
28
 * Example: apply_filters('glsr_get_reviews', [], ['assigned_posts' => 'post_id']);
29
 */
30
add_action('plugins_loaded', function () {
31
    $hooks = [
32
        'glsr_create_review' => 2,
33
        'glsr_debug' => 10,
34
        'glsr_get' => 4,
35
        'glsr_get_option' => 4,
36
        'glsr_get_options' => 1,
37
        'glsr_get_ratings' => 2,
38
        'glsr_get_review' => 2,
39
        'glsr_get_reviews' => 2,
40
        'glsr_log' => 3,
41
        'glsr_star_rating' => 4,
42
        'glsr_trace' => 2,
43
        'glsr_update_review' => 3,
44
    ];
45
    foreach ($hooks as $function => $acceptedArgs) {
46
        add_filter($function, function () use ($function) {
47
            $args = func_get_args();
48
            array_shift($args); // remove the fallback value
49
            return call_user_func_array($function, $args);
50
        }, 10, $acceptedArgs);
51
    }
52
});
53
54
/**
55
 * @return mixed
56
 */
57
function glsr($alias = null, array $parameters = [])
58
{
59
    if (is_null($alias)) {
60
        return Application::load();
61
    }
62
    try {
63
        return Application::load()->make($alias, $parameters);
64
    } catch (BindingResolutionException $e) {
65
        glsr_log()->error($e->getMessage());
66
        return Application::load()->make(BlackHole::class, compact('alias'));
67
    }
68
}
69
70
function glsr_admin_url(string $page = '', string $tab = '', string $sub = ''): string
71
{
72
    if ('welcome' === $page) {
73
        $page = glsr()->id.'-welcome';
74
        $args = array_filter(compact('page', 'tab'));
75
        return add_query_arg($args, admin_url('index.php'));
76
    }
77
    if (!empty($page)) {
78
        $page = Str::dashCase(glsr()->prefix.$page);
79
    }
80
    $post_type = glsr()->post_type;
81
    $args = array_filter(compact('post_type', 'page', 'tab', 'sub'));
82
    return add_query_arg($args, admin_url('edit.php'));
83
}
84
85
/**
86
 * @param string|array $attrs
87
 */
88
function glsr_admin_link(string $path = '', $attrs = [], string $expand = ''): string
89
{
90
    $parts = explode('.', $path);
91
    $parts = array_slice(array_pad(array_filter($parts, 'is_string'), 3, ''), 0, 3);
92
    $text = trim(is_string($attrs) ? $attrs : ($attrs['text'] ?? ''));
93
    if (empty($text)) {
94
        $texts = [
95
            'addons' => _x('Addons', 'admin-text', 'site-reviews'),
96
            'api' => _x('API', 'admin-text', 'site-reviews'),
97
            'console' => _x('Console', 'admin-text', 'site-reviews'),
98
            'documentation' => _x('Help & Support', 'admin-text', 'site-reviews'),
99
            'faq' => _x('FAQ', 'admin-text', 'site-reviews'),
100
            'forms' => _x('Forms', 'admin-text', 'site-reviews'),
101
            'functions' => _x('Functions', 'admin-text', 'site-reviews'),
102
            'general' => _x('General', 'admin-text', 'site-reviews'),
103
            'hooks' => _x('Hooks', 'admin-text', 'site-reviews'),
104
            'integrations' => _x('Integrations', 'admin-text', 'site-reviews'),
105
            'licenses' => _x('Licenses', 'admin-text', 'site-reviews'),
106
            'profilepress' => 'ProfilePress',
107
            'reviews' => _x('Reviews', 'admin-text', 'site-reviews'),
108
            'scheduled' => _x('Scheduled Actions', 'admin-text', 'site-reviews'),
109
            'schema' => _x('Schema', 'admin-text', 'site-reviews'),
110
            'settings' => _x('Settings', 'admin-text', 'site-reviews'),
111
            'shortcodes' => _x('Shortcodes', 'admin-text', 'site-reviews'),
112
            'strings' => _x('Strings', 'admin-text', 'site-reviews'),
113
            'support' => _x('Support', 'admin-text', 'site-reviews'),
114
            'surecart' => 'SureCart',
115
            'system-info' => _x('System Info', 'admin-text', 'site-reviews'),
116
            'tools' => _x('Tools', 'admin-text', 'site-reviews'),
117
            'ultimatemember' => 'Ultimate Member',
118
            'woocommerce' => 'WooCommerce',
119
        ];
120
        $textParts = array_filter([
121
            $texts[$parts[0]] ?? ucfirst($parts[0]),
122
            $texts[$parts[1]] ?? ucfirst($parts[1]),
123
            $texts[$parts[2]] ?? ucfirst($parts[2]),
124
        ]);
125
        $text = implode(' &rarr; ', $textParts);
126
    }
127
    $url = call_user_func_array('glsr_admin_url', $parts);
128
    $attrs = Arr::consolidate($attrs);
129
    $attrs['href'] = $url;
130
    $attrs['text'] = $text ?: _x('All Reviews', 'admin-text', 'site-reviews');
131
    return glsr(Builder::class)->a(wp_parse_args($attrs, [
132
        'data-expand' => $expand,
133
    ]));
134
}
135
136
/**
137
 * @return Review|false
138
 */
139
function glsr_create_review(array $values = [])
140
{
141
    $values = Arr::removeEmptyValues($values);
142
    $request = new Request($values);
143
    $review = false;
144
    glsr()->store('glsr_create_review', true);
145
    $command = new CreateReview($request);
146
    if ($command->isRequestValid()) {
147
        $review = glsr(ReviewManager::class)->create($command);
148
    }
149
    glsr()->discard('glsr_create_review');
150
    return $review;
151
}
152
153
/**
154
 * @return WP_Screen|object
155
 */
156
function glsr_current_screen()
157
{
158
    if (function_exists('get_current_screen')) {
159
        $screen = get_current_screen();
160
    }
161
    return empty($screen)
162
        ? (object) array_fill_keys(['action', 'base', 'id', 'post_type'], '')
163
        : $screen;
164
}
165
166
/**
167
 * @param mixed ...$vars
168
 */
169
function glsr_debug(...$vars): void
170
{
171
    if (1 === count($vars)) {
172
        $dump = glsr(Dump::class)->dump($vars[0]);
173
        $value = htmlspecialchars($dump, ENT_QUOTES, 'UTF-8');
174
        printf('<div class="glsr-debug"><pre>%s</pre></div>', $value);
175
    } else {
176
        echo '<div class="glsr-debug-group">';
177
        foreach ($vars as $var) {
178
            glsr_debug($var);
179
        }
180
        echo '</div>';
181
    }
182
}
183
184
/**
185
 * @param string|int $path
186
 * @param mixed      $fallback
187
 *
188
 * @return mixed
189
 */
190
function glsr_get($array, $path = '', $fallback = '')
191
{
192
    return Arr::get($array, $path, $fallback);
193
}
194
195
/**
196
 * @param mixed $fallback
197
 *
198
 * @return mixed
199
 */
200
function glsr_get_option(string $path = '', $fallback = '', string $cast = '')
201
{
202
    return glsr(OptionManager::class)->get(Str::prefix($path, 'settings.'), $fallback, $cast);
203
}
204
205
function glsr_get_options(): array
206
{
207
    return glsr(OptionManager::class)->get('settings');
208
}
209
210
function glsr_get_ratings(array $args = []): Arguments
211
{
212
    $counts = glsr(RatingManager::class)->ratings($args);
213
    return new Arguments([
214
        'average' => glsr(Rating::class)->average($counts),
215
        'maximum' => Rating::max(),
216
        'minimum' => Rating::min(),
217
        'ranking' => glsr(Rating::class)->ranking($counts),
218
        'ratings' => $counts,
219
        'reviews' => array_sum($counts),
220
    ]);
221
}
222
223
function glsr_get_review($postId): Review
224
{
225
    return glsr(ReviewManager::class)->get(Cast::toInt($postId));
226
}
227
228
function glsr_get_reviews(array $args = []): Reviews
229
{
230
    return glsr(ReviewManager::class)->reviews($args);
231
}
232
233
/**
234
 * @param mixed ...$args
235
 */
236
function glsr_log(...$args): Console
237
{
238
    $console = glsr(Console::class);
239
    return !empty($args)
1 ignored issue
show
Bug Best Practice introduced by
The expression return ! empty($args) ? ...ug'), $args) : $console could return the type callable which is incompatible with the type-hinted return GeminiLabs\SiteReviews\Modules\Console. Consider adding an additional type-check to rule them out.
Loading history...
240
        ? call_user_func_array([$console, 'debug'], $args)
241
        : $console;
242
}
243
244
function glsr_premium_link(string $path, $attrs = []): string
245
{
246
    $url = glsr_premium_url($path);
247
    $texts = [
248
        'license-keys' => _x('License Keys', 'admin-text', 'site-reviews'),
249
        'site-reviews-actions' => _x('Review Actions', 'admin-text', 'site-reviews'),
250
        'site-reviews-authors' => _x('Review Authors', 'admin-text', 'site-reviews'),
251
        'site-reviews-filters' => _x('Review Filters', 'admin-text', 'site-reviews'),
252
        'site-reviews-forms' => _x('Review Forms', 'admin-text', 'site-reviews'),
253
        'site-reviews-images' => _x('Review Images', 'admin-text', 'site-reviews'),
254
        'site-reviews-notifications' => _x('Review Notifications', 'admin-text', 'site-reviews'),
255
        'site-reviews-premium' => _x('Site Reviews Premium', 'admin-text', 'site-reviews'),
256
        'site-reviews-themes' => _x('Review Themes', 'admin-text', 'site-reviews'),
257
    ];
258
    $text = trim(is_string($attrs) ? $attrs : ($attrs['text'] ?? ''));
259
    $text = $text ?: ($texts[$path] ?? $url);
260
    $attrs = Arr::consolidate($attrs);
261
    $attrs['href'] = $url;
262
    $attrs['target'] = '_blank';
263
    $attrs['text'] = $text;
264
    return glsr(Builder::class)->a($attrs);
265
}
266
267
function glsr_premium_url(string $path = '/'): string
268
{
269
    $baseUrl = 'https://niftyplugins.com/';
270
    $paths = [
271
        'account' => '/account/',
272
        'addons' => '/plugins/',
273
        'license-keys' => '/account/license-keys/',
274
        'site-reviews-actions' => '/plugins/site-reviews-actions/',
275
        'site-reviews-authors' => '/plugins/site-reviews-authors/',
276
        'site-reviews-filters' => '/plugins/site-reviews-filters/',
277
        'site-reviews-forms' => '/plugins/site-reviews-forms/',
278
        'site-reviews-images' => '/plugins/site-reviews-images/',
279
        'site-reviews-notifications' => '/plugins/site-reviews-notifications/',
280
        'site-reviews-premium' => '/plugins/site-reviews-premium/',
281
        'site-reviews-themes' => '/plugins/site-reviews-themes/',
282
        'support' => '/account/support/',
283
    ];
284
    $urlPath = trim($paths[$path] ?? $path);
285
    $urlPath = trailingslashit(ltrim($urlPath, '/'));
286
    return esc_url(trailingslashit($baseUrl).$urlPath);
287
}
288
289
/**
290
 * @param string|int $path
291
 * @param mixed      $value
292
 */
293
function glsr_set(array $data, $path, $value): array
294
{
295
    return Arr::set($data, $path, $value);
296
}
297
298
/**
299
 * @param mixed    $rating
300
 * @param int|null $reviews
301
 */
302
function glsr_star_rating($rating, $reviews = 0, array $args = []): string
303
{
304
    return glsr(Partial::class)->build('star-rating', [
305
        'args' => $args,
306
        'rating' => $rating,
307
        'reviews' => $reviews,
308
    ]);
309
}
310
311
function glsr_trace(int $limit = 5): void
312
{
313
    glsr_log(glsr(Backtrace::class)->trace($limit));
314
}
315
316
/**
317
 * @return Review|false
318
 */
319
function glsr_update_review(int $postId, array $values = [])
320
{
321
    glsr()->store('glsr_update_review', true);
322
    $result = glsr(ReviewManager::class)->update($postId, $values);
323
    glsr()->discard('glsr_update_review');
324
    return $result;
325
}
326
327
function glsr_user_count(): int
328
{
329
    if (function_exists('get_user_count')) {
330
        return get_user_count();
331
    }
332
    return Arr::getAs('int', count_users(), 'total_users');
333
}
334