Passed
Push — master ( a9546d...6aabd8 )
by Paul
05:58
created
plugin/Modules/Console.php 1 patch
Indentation   +433 added lines, -433 removed lines patch added patch discarded remove patch
@@ -10,437 +10,437 @@
 block discarded – undo
10 10
 
11 11
 class Console
12 12
 {
13
-    const DEBUG = 0;      // Detailed debug information
14
-    const INFO = 1;       // Interesting events
15
-    const NOTICE = 2;     // Normal but significant events
16
-    const WARNING = 4;    // Exceptional occurrences that are not errors
17
-    const ERROR = 8;      // Runtime errors that do not require immediate action
18
-    const CRITICAL = 16;  // Critical conditions
19
-    const ALERT = 32;     // Action must be taken immediately
20
-    const EMERGENCY = 64; // System is unusable
21
-
22
-    protected $file;
23
-    protected $log;
24
-    protected $logOnceKey = 'glsr_log_once';
25
-
26
-    public function __construct()
27
-    {
28
-        $this->file = glsr()->path('console.log');
29
-        $this->log = file_exists($this->file)
30
-            ? file_get_contents($this->file)
31
-            : '';
32
-        $this->reset();
33
-    }
34
-
35
-    /**
36
-     * @return string
37
-     */
38
-    public function __toString()
39
-    {
40
-        return $this->get();
41
-    }
42
-
43
-    /**
44
-     * Action must be taken immediately
45
-     * Example: Entire website down, database unavailable, etc. This should trigger the SMS alerts and wake you up.
46
-     * @param mixed $message
47
-     * @param array $context
48
-     * @return static
49
-     */
50
-    public function alert($message, array $context = [])
51
-    {
52
-        return $this->log(static::ALERT, $message, $context);
53
-    }
54
-
55
-    /**
56
-     * @return void
57
-     */
58
-    public function clear()
59
-    {
60
-        $this->log = '';
61
-        file_put_contents($this->file, $this->log);
62
-    }
63
-
64
-    /**
65
-     * Critical conditions
66
-     * Example: Application component unavailable, unexpected exception.
67
-     * @param mixed $message
68
-     * @param array $context
69
-     * @return static
70
-     */
71
-    public function critical($message, array $context = [])
72
-    {
73
-        return $this->log(static::CRITICAL, $message, $context);
74
-    }
75
-
76
-    /**
77
-     * Detailed debug information.
78
-     * @param mixed $message
79
-     * @param array $context
80
-     * @return static
81
-     */
82
-    public function debug($message, array $context = [])
83
-    {
84
-        return $this->log(static::DEBUG, $message, $context);
85
-    }
86
-
87
-    /**
88
-     * System is unusable.
89
-     * @param mixed $message
90
-     * @param array $context
91
-     * @return static
92
-     */
93
-    public function emergency($message, array $context = [])
94
-    {
95
-        return $this->log(static::EMERGENCY, $message, $context);
96
-    }
97
-
98
-    /**
99
-     * Runtime errors that do not require immediate action but should typically be logged and monitored.
100
-     * @param mixed $message
101
-     * @param array $context
102
-     * @return static
103
-     */
104
-    public function error($message, array $context = [])
105
-    {
106
-        return $this->log(static::ERROR, $message, $context);
107
-    }
108
-
109
-    /**
110
-     * @return string
111
-     */
112
-    public function get()
113
-    {
114
-        return empty($this->log)
115
-            ? __('Console is empty', 'site-reviews')
116
-            : $this->log;
117
-    }
118
-
119
-    /**
120
-     * @return int
121
-     */
122
-    public function getLevel()
123
-    {
124
-        return intval(apply_filters('site-reviews/console/level', static::INFO));
125
-    }
126
-
127
-    /**
128
-     * @return array
129
-     */
130
-    public function getLevels()
131
-    {
132
-        $constants = (new ReflectionClass(__CLASS__))->getConstants();
133
-        return array_map('strtolower', array_flip($constants));
134
-    }
135
-
136
-    /**
137
-     * @return string
138
-     */
139
-    public function humanLevel()
140
-    {
141
-        $level = $this->getLevel();
142
-        return sprintf('%s (%d)', strtoupper(Arr::get($this->getLevels(), $level, 'unknown')), $level);
143
-    }
144
-
145
-    /**
146
-     * @param string|null $valueIfEmpty
147
-     * @return string
148
-     */
149
-    public function humanSize($valueIfEmpty = null)
150
-    {
151
-        $bytes = $this->size();
152
-        if (empty($bytes) && is_string($valueIfEmpty)) {
153
-            return $valueIfEmpty;
154
-        }
155
-        $exponent = floor(log(max($bytes, 1), 1024));
156
-        return round($bytes / pow(1024, $exponent), 2).' '.['bytes', 'KB', 'MB', 'GB'][$exponent];
157
-    }
158
-
159
-    /**
160
-     * Interesting events
161
-     * Example: User logs in, SQL logs.
162
-     * @param mixed $message
163
-     * @param array $context
164
-     * @return static
165
-     */
166
-    public function info($message, array $context = [])
167
-    {
168
-        return $this->log(static::INFO, $message, $context);
169
-    }
170
-
171
-    /**
172
-     * @param int $level
173
-     * @param mixed $message
174
-     * @param array $context
175
-     * @param string $backtraceLine
176
-     * @return static
177
-     */
178
-    public function log($level, $message, $context = [], $backtraceLine = '')
179
-    {
180
-        if (empty($backtraceLine)) {
181
-            $backtraceLine = $this->getBacktraceLine();
182
-        }
183
-        if ($this->canLogEntry($level, $backtraceLine)) {
184
-            $levelName = Arr::get($this->getLevels(), $level);
185
-            $context = Arr::consolidateArray($context);
186
-            $backtraceLine = $this->normalizeBacktraceLine($backtraceLine);
187
-            $message = $this->interpolate($message, $context);
188
-            $entry = $this->buildLogEntry($levelName, $message, $backtraceLine);
189
-            file_put_contents($this->file, $entry.PHP_EOL, FILE_APPEND | LOCK_EX);
190
-            apply_filters('console', $message, $levelName, $backtraceLine); // Show in Blackbar plugin if installed
191
-            $this->reset();
192
-        }
193
-        return $this;
194
-    }
195
-
196
-    /**
197
-     * @return void
198
-     */
199
-    public function logOnce()
200
-    {
201
-        $once = Arr::consolidateArray(glsr()->{$this->logOnceKey});
202
-        $levels = $this->getLevels();
203
-        foreach ($once as $entry) {
204
-            $levelName = Arr::get($entry, 'level');
205
-            if (!in_array($levelName, $levels)) {
206
-                continue;
207
-            }
208
-            $level = Arr::get(array_flip($levels), $levelName);
209
-            $message = Arr::get($entry, 'message');
210
-            $backtraceLine = Arr::get($entry, 'backtrace');
211
-            $this->log($level, $message, [], $backtraceLine);
212
-        }
213
-        glsr()->{$this->logOnceKey} = [];
214
-    }
215
-
216
-    /**
217
-     * Normal but significant events.
218
-     * @param mixed $message
219
-     * @param array $context
220
-     * @return static
221
-     */
222
-    public function notice($message, array $context = [])
223
-    {
224
-        return $this->log(static::NOTICE, $message, $context);
225
-    }
226
-
227
-    /**
228
-     * @param string $levelName
229
-     * @param string $handle
230
-     * @param mixed $data
231
-     * @return void
232
-     */
233
-    public function once($levelName, $handle, $data)
234
-    {
235
-        $once = Arr::consolidateArray(glsr()->{$this->logOnceKey});
236
-        $filtered = array_filter($once, function ($entry) use ($levelName, $handle) {
237
-            return Arr::get($entry, 'level') == $levelName
238
-                && Arr::get($entry, 'handle') == $handle;
239
-        });
240
-        if (!empty($filtered)) {
241
-            return;
242
-        }
243
-        $once[] = [
244
-            'backtrace' => $this->getBacktraceLineFromData($data),
245
-            'handle' => $handle,
246
-            'level' => $levelName,
247
-            'message' => '[RECURRING] '.$this->getMessageFromData($data),
248
-        ];
249
-        glsr()->{$this->logOnceKey} = $once;
250
-    }
251
-
252
-    /**
253
-     * @return int
254
-     */
255
-    public function size()
256
-    {
257
-        return file_exists($this->file)
258
-            ? filesize($this->file)
259
-            : 0;
260
-    }
261
-
262
-    /**
263
-     * Exceptional occurrences that are not errors
264
-     * Example: Use of deprecated APIs, poor use of an API, undesirable things that are not necessarily wrong.
265
-     * @param mixed $message
266
-     * @param array $context
267
-     * @return static
268
-     */
269
-    public function warning($message, array $context = [])
270
-    {
271
-        return $this->log(static::WARNING, $message, $context);
272
-    }
273
-
274
-    /**
275
-     * @param array $backtrace
276
-     * @param int $index
277
-     * @return string
278
-     */
279
-    protected function buildBacktraceLine($backtrace, $index)
280
-    {
281
-        return sprintf('%s:%s',
282
-            Arr::get($backtrace, $index.'.file'), // realpath
283
-            Arr::get($backtrace, $index.'.line')
284
-        );
285
-    }
286
-
287
-    /**
288
-     * @param string $levelName
289
-     * @param mixed $message
290
-     * @param string $backtraceLine
291
-     * @return string
292
-     */
293
-    protected function buildLogEntry($levelName, $message, $backtraceLine = '')
294
-    {
295
-        return sprintf('[%s] %s [%s] %s',
296
-            current_time('mysql'),
297
-            strtoupper($levelName),
298
-            $backtraceLine,
299
-            $message
300
-        );
301
-    }
302
-
303
-    /**
304
-     * @param int $level
305
-     * @return bool
306
-     */
307
-    protected function canLogEntry($level, $backtraceLine)
308
-    {
309
-        $levelExists = array_key_exists($level, $this->getLevels());
310
-        if (!Str::contains($backtraceLine, glsr()->path())) {
311
-            return $levelExists; // ignore level restriction if triggered outside of the plugin
312
-        }
313
-        return $levelExists && $level >= $this->getLevel();
314
-    }
315
-
316
-    /**
317
-     * @return void|string
318
-     */
319
-    protected function getBacktraceLine()
320
-    {
321
-        $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6);
322
-        $search = array_search('glsr_log', glsr_array_column($backtrace, 'function'));
323
-        if (false !== $search) {
324
-            return $this->buildBacktraceLine($backtrace, (int) $search);
325
-        }
326
-        $search = array_search('log', glsr_array_column($backtrace, 'function'));
327
-        if (false !== $search) {
328
-            $index = '{closure}' == Arr::get($backtrace, ($search + 2).'.function')
329
-                ? $search + 4
330
-                : $search + 1;
331
-            return $this->buildBacktraceLine($backtrace, $index);
332
-        }
333
-        return 'Unknown';
334
-    }
335
-
336
-    /**
337
-     * @param mixed $data
338
-     * @return string
339
-     */
340
-    protected function getBacktraceLineFromData($data)
341
-    {
342
-        $backtrace = $data instanceof Throwable
343
-            ? $data->getTrace()
344
-            : debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
345
-        return $this->buildBacktraceLine($backtrace, 0);
346
-    }
347
-
348
-    /**
349
-     * @param mixed $data
350
-     * @return string
351
-     */
352
-    protected function getMessageFromData($data)
353
-    {
354
-        return $data instanceof Throwable
355
-            ? $this->normalizeThrowableMessage($data->getMessage())
356
-            : print_r($data, 1);
357
-    }
358
-
359
-    /**
360
-     * Interpolates context values into the message placeholders.
361
-     * @param mixed $message
362
-     * @param array $context
363
-     * @return string
364
-     */
365
-    protected function interpolate($message, $context = [])
366
-    {
367
-        if ($this->isObjectOrArray($message) || !is_array($context)) {
368
-            return print_r($message, true);
369
-        }
370
-        $replace = [];
371
-        foreach ($context as $key => $value) {
372
-            $replace['{'.$key.'}'] = $this->normalizeValue($value);
373
-        }
374
-        return strtr($message, $replace);
375
-    }
376
-
377
-    /**
378
-     * @param mixed $value
379
-     * @return bool
380
-     */
381
-    protected function isObjectOrArray($value)
382
-    {
383
-        return is_object($value) || is_array($value);
384
-    }
385
-
386
-    /**
387
-     * @param string $backtraceLine
388
-     * @return string
389
-     */
390
-    protected function normalizeBacktraceLine($backtraceLine)
391
-    {
392
-        $search = [
393
-            glsr()->path('plugin/'),
394
-            glsr()->path('plugin/', false),
395
-            trailingslashit(glsr()->path()),
396
-            trailingslashit(glsr()->path('', false)),
397
-            WP_CONTENT_DIR,
398
-            ABSPATH,
399
-        ];
400
-        return str_replace(array_unique($search), '', $backtraceLine);
401
-    }
402
-
403
-    /**
404
-     * @param string $message
405
-     * @return string
406
-     */
407
-    protected function normalizeThrowableMessage($message)
408
-    {
409
-        $calledIn = strpos($message, ', called in');
410
-        return false !== $calledIn
411
-            ? substr($message, 0, $calledIn)
412
-            : $message;
413
-    }
414
-
415
-    /**
416
-     * @param mixed $value
417
-     * @return string
418
-     */
419
-    protected function normalizeValue($value)
420
-    {
421
-        if ($value instanceof DateTime) {
422
-            $value = $value->format('Y-m-d H:i:s');
423
-        } elseif ($this->isObjectOrArray($value)) {
424
-            $value = json_encode($value);
425
-        }
426
-        return (string) $value;
427
-    }
428
-
429
-    /**
430
-     * @return void
431
-     */
432
-    protected function reset()
433
-    {
434
-        if ($this->size() <= pow(1024, 2) / 8) {
435
-            return;
436
-        }
437
-        $this->clear();
438
-        file_put_contents(
439
-            $this->file,
440
-            $this->buildLogEntry(
441
-                static::NOTICE,
442
-                __('Console was automatically cleared (128 KB maximum size)', 'site-reviews')
443
-            )
444
-        );
445
-    }
13
+	const DEBUG = 0;      // Detailed debug information
14
+	const INFO = 1;       // Interesting events
15
+	const NOTICE = 2;     // Normal but significant events
16
+	const WARNING = 4;    // Exceptional occurrences that are not errors
17
+	const ERROR = 8;      // Runtime errors that do not require immediate action
18
+	const CRITICAL = 16;  // Critical conditions
19
+	const ALERT = 32;     // Action must be taken immediately
20
+	const EMERGENCY = 64; // System is unusable
21
+
22
+	protected $file;
23
+	protected $log;
24
+	protected $logOnceKey = 'glsr_log_once';
25
+
26
+	public function __construct()
27
+	{
28
+		$this->file = glsr()->path('console.log');
29
+		$this->log = file_exists($this->file)
30
+			? file_get_contents($this->file)
31
+			: '';
32
+		$this->reset();
33
+	}
34
+
35
+	/**
36
+	 * @return string
37
+	 */
38
+	public function __toString()
39
+	{
40
+		return $this->get();
41
+	}
42
+
43
+	/**
44
+	 * Action must be taken immediately
45
+	 * Example: Entire website down, database unavailable, etc. This should trigger the SMS alerts and wake you up.
46
+	 * @param mixed $message
47
+	 * @param array $context
48
+	 * @return static
49
+	 */
50
+	public function alert($message, array $context = [])
51
+	{
52
+		return $this->log(static::ALERT, $message, $context);
53
+	}
54
+
55
+	/**
56
+	 * @return void
57
+	 */
58
+	public function clear()
59
+	{
60
+		$this->log = '';
61
+		file_put_contents($this->file, $this->log);
62
+	}
63
+
64
+	/**
65
+	 * Critical conditions
66
+	 * Example: Application component unavailable, unexpected exception.
67
+	 * @param mixed $message
68
+	 * @param array $context
69
+	 * @return static
70
+	 */
71
+	public function critical($message, array $context = [])
72
+	{
73
+		return $this->log(static::CRITICAL, $message, $context);
74
+	}
75
+
76
+	/**
77
+	 * Detailed debug information.
78
+	 * @param mixed $message
79
+	 * @param array $context
80
+	 * @return static
81
+	 */
82
+	public function debug($message, array $context = [])
83
+	{
84
+		return $this->log(static::DEBUG, $message, $context);
85
+	}
86
+
87
+	/**
88
+	 * System is unusable.
89
+	 * @param mixed $message
90
+	 * @param array $context
91
+	 * @return static
92
+	 */
93
+	public function emergency($message, array $context = [])
94
+	{
95
+		return $this->log(static::EMERGENCY, $message, $context);
96
+	}
97
+
98
+	/**
99
+	 * Runtime errors that do not require immediate action but should typically be logged and monitored.
100
+	 * @param mixed $message
101
+	 * @param array $context
102
+	 * @return static
103
+	 */
104
+	public function error($message, array $context = [])
105
+	{
106
+		return $this->log(static::ERROR, $message, $context);
107
+	}
108
+
109
+	/**
110
+	 * @return string
111
+	 */
112
+	public function get()
113
+	{
114
+		return empty($this->log)
115
+			? __('Console is empty', 'site-reviews')
116
+			: $this->log;
117
+	}
118
+
119
+	/**
120
+	 * @return int
121
+	 */
122
+	public function getLevel()
123
+	{
124
+		return intval(apply_filters('site-reviews/console/level', static::INFO));
125
+	}
126
+
127
+	/**
128
+	 * @return array
129
+	 */
130
+	public function getLevels()
131
+	{
132
+		$constants = (new ReflectionClass(__CLASS__))->getConstants();
133
+		return array_map('strtolower', array_flip($constants));
134
+	}
135
+
136
+	/**
137
+	 * @return string
138
+	 */
139
+	public function humanLevel()
140
+	{
141
+		$level = $this->getLevel();
142
+		return sprintf('%s (%d)', strtoupper(Arr::get($this->getLevels(), $level, 'unknown')), $level);
143
+	}
144
+
145
+	/**
146
+	 * @param string|null $valueIfEmpty
147
+	 * @return string
148
+	 */
149
+	public function humanSize($valueIfEmpty = null)
150
+	{
151
+		$bytes = $this->size();
152
+		if (empty($bytes) && is_string($valueIfEmpty)) {
153
+			return $valueIfEmpty;
154
+		}
155
+		$exponent = floor(log(max($bytes, 1), 1024));
156
+		return round($bytes / pow(1024, $exponent), 2).' '.['bytes', 'KB', 'MB', 'GB'][$exponent];
157
+	}
158
+
159
+	/**
160
+	 * Interesting events
161
+	 * Example: User logs in, SQL logs.
162
+	 * @param mixed $message
163
+	 * @param array $context
164
+	 * @return static
165
+	 */
166
+	public function info($message, array $context = [])
167
+	{
168
+		return $this->log(static::INFO, $message, $context);
169
+	}
170
+
171
+	/**
172
+	 * @param int $level
173
+	 * @param mixed $message
174
+	 * @param array $context
175
+	 * @param string $backtraceLine
176
+	 * @return static
177
+	 */
178
+	public function log($level, $message, $context = [], $backtraceLine = '')
179
+	{
180
+		if (empty($backtraceLine)) {
181
+			$backtraceLine = $this->getBacktraceLine();
182
+		}
183
+		if ($this->canLogEntry($level, $backtraceLine)) {
184
+			$levelName = Arr::get($this->getLevels(), $level);
185
+			$context = Arr::consolidateArray($context);
186
+			$backtraceLine = $this->normalizeBacktraceLine($backtraceLine);
187
+			$message = $this->interpolate($message, $context);
188
+			$entry = $this->buildLogEntry($levelName, $message, $backtraceLine);
189
+			file_put_contents($this->file, $entry.PHP_EOL, FILE_APPEND | LOCK_EX);
190
+			apply_filters('console', $message, $levelName, $backtraceLine); // Show in Blackbar plugin if installed
191
+			$this->reset();
192
+		}
193
+		return $this;
194
+	}
195
+
196
+	/**
197
+	 * @return void
198
+	 */
199
+	public function logOnce()
200
+	{
201
+		$once = Arr::consolidateArray(glsr()->{$this->logOnceKey});
202
+		$levels = $this->getLevels();
203
+		foreach ($once as $entry) {
204
+			$levelName = Arr::get($entry, 'level');
205
+			if (!in_array($levelName, $levels)) {
206
+				continue;
207
+			}
208
+			$level = Arr::get(array_flip($levels), $levelName);
209
+			$message = Arr::get($entry, 'message');
210
+			$backtraceLine = Arr::get($entry, 'backtrace');
211
+			$this->log($level, $message, [], $backtraceLine);
212
+		}
213
+		glsr()->{$this->logOnceKey} = [];
214
+	}
215
+
216
+	/**
217
+	 * Normal but significant events.
218
+	 * @param mixed $message
219
+	 * @param array $context
220
+	 * @return static
221
+	 */
222
+	public function notice($message, array $context = [])
223
+	{
224
+		return $this->log(static::NOTICE, $message, $context);
225
+	}
226
+
227
+	/**
228
+	 * @param string $levelName
229
+	 * @param string $handle
230
+	 * @param mixed $data
231
+	 * @return void
232
+	 */
233
+	public function once($levelName, $handle, $data)
234
+	{
235
+		$once = Arr::consolidateArray(glsr()->{$this->logOnceKey});
236
+		$filtered = array_filter($once, function ($entry) use ($levelName, $handle) {
237
+			return Arr::get($entry, 'level') == $levelName
238
+				&& Arr::get($entry, 'handle') == $handle;
239
+		});
240
+		if (!empty($filtered)) {
241
+			return;
242
+		}
243
+		$once[] = [
244
+			'backtrace' => $this->getBacktraceLineFromData($data),
245
+			'handle' => $handle,
246
+			'level' => $levelName,
247
+			'message' => '[RECURRING] '.$this->getMessageFromData($data),
248
+		];
249
+		glsr()->{$this->logOnceKey} = $once;
250
+	}
251
+
252
+	/**
253
+	 * @return int
254
+	 */
255
+	public function size()
256
+	{
257
+		return file_exists($this->file)
258
+			? filesize($this->file)
259
+			: 0;
260
+	}
261
+
262
+	/**
263
+	 * Exceptional occurrences that are not errors
264
+	 * Example: Use of deprecated APIs, poor use of an API, undesirable things that are not necessarily wrong.
265
+	 * @param mixed $message
266
+	 * @param array $context
267
+	 * @return static
268
+	 */
269
+	public function warning($message, array $context = [])
270
+	{
271
+		return $this->log(static::WARNING, $message, $context);
272
+	}
273
+
274
+	/**
275
+	 * @param array $backtrace
276
+	 * @param int $index
277
+	 * @return string
278
+	 */
279
+	protected function buildBacktraceLine($backtrace, $index)
280
+	{
281
+		return sprintf('%s:%s',
282
+			Arr::get($backtrace, $index.'.file'), // realpath
283
+			Arr::get($backtrace, $index.'.line')
284
+		);
285
+	}
286
+
287
+	/**
288
+	 * @param string $levelName
289
+	 * @param mixed $message
290
+	 * @param string $backtraceLine
291
+	 * @return string
292
+	 */
293
+	protected function buildLogEntry($levelName, $message, $backtraceLine = '')
294
+	{
295
+		return sprintf('[%s] %s [%s] %s',
296
+			current_time('mysql'),
297
+			strtoupper($levelName),
298
+			$backtraceLine,
299
+			$message
300
+		);
301
+	}
302
+
303
+	/**
304
+	 * @param int $level
305
+	 * @return bool
306
+	 */
307
+	protected function canLogEntry($level, $backtraceLine)
308
+	{
309
+		$levelExists = array_key_exists($level, $this->getLevels());
310
+		if (!Str::contains($backtraceLine, glsr()->path())) {
311
+			return $levelExists; // ignore level restriction if triggered outside of the plugin
312
+		}
313
+		return $levelExists && $level >= $this->getLevel();
314
+	}
315
+
316
+	/**
317
+	 * @return void|string
318
+	 */
319
+	protected function getBacktraceLine()
320
+	{
321
+		$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6);
322
+		$search = array_search('glsr_log', glsr_array_column($backtrace, 'function'));
323
+		if (false !== $search) {
324
+			return $this->buildBacktraceLine($backtrace, (int) $search);
325
+		}
326
+		$search = array_search('log', glsr_array_column($backtrace, 'function'));
327
+		if (false !== $search) {
328
+			$index = '{closure}' == Arr::get($backtrace, ($search + 2).'.function')
329
+				? $search + 4
330
+				: $search + 1;
331
+			return $this->buildBacktraceLine($backtrace, $index);
332
+		}
333
+		return 'Unknown';
334
+	}
335
+
336
+	/**
337
+	 * @param mixed $data
338
+	 * @return string
339
+	 */
340
+	protected function getBacktraceLineFromData($data)
341
+	{
342
+		$backtrace = $data instanceof Throwable
343
+			? $data->getTrace()
344
+			: debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
345
+		return $this->buildBacktraceLine($backtrace, 0);
346
+	}
347
+
348
+	/**
349
+	 * @param mixed $data
350
+	 * @return string
351
+	 */
352
+	protected function getMessageFromData($data)
353
+	{
354
+		return $data instanceof Throwable
355
+			? $this->normalizeThrowableMessage($data->getMessage())
356
+			: print_r($data, 1);
357
+	}
358
+
359
+	/**
360
+	 * Interpolates context values into the message placeholders.
361
+	 * @param mixed $message
362
+	 * @param array $context
363
+	 * @return string
364
+	 */
365
+	protected function interpolate($message, $context = [])
366
+	{
367
+		if ($this->isObjectOrArray($message) || !is_array($context)) {
368
+			return print_r($message, true);
369
+		}
370
+		$replace = [];
371
+		foreach ($context as $key => $value) {
372
+			$replace['{'.$key.'}'] = $this->normalizeValue($value);
373
+		}
374
+		return strtr($message, $replace);
375
+	}
376
+
377
+	/**
378
+	 * @param mixed $value
379
+	 * @return bool
380
+	 */
381
+	protected function isObjectOrArray($value)
382
+	{
383
+		return is_object($value) || is_array($value);
384
+	}
385
+
386
+	/**
387
+	 * @param string $backtraceLine
388
+	 * @return string
389
+	 */
390
+	protected function normalizeBacktraceLine($backtraceLine)
391
+	{
392
+		$search = [
393
+			glsr()->path('plugin/'),
394
+			glsr()->path('plugin/', false),
395
+			trailingslashit(glsr()->path()),
396
+			trailingslashit(glsr()->path('', false)),
397
+			WP_CONTENT_DIR,
398
+			ABSPATH,
399
+		];
400
+		return str_replace(array_unique($search), '', $backtraceLine);
401
+	}
402
+
403
+	/**
404
+	 * @param string $message
405
+	 * @return string
406
+	 */
407
+	protected function normalizeThrowableMessage($message)
408
+	{
409
+		$calledIn = strpos($message, ', called in');
410
+		return false !== $calledIn
411
+			? substr($message, 0, $calledIn)
412
+			: $message;
413
+	}
414
+
415
+	/**
416
+	 * @param mixed $value
417
+	 * @return string
418
+	 */
419
+	protected function normalizeValue($value)
420
+	{
421
+		if ($value instanceof DateTime) {
422
+			$value = $value->format('Y-m-d H:i:s');
423
+		} elseif ($this->isObjectOrArray($value)) {
424
+			$value = json_encode($value);
425
+		}
426
+		return (string) $value;
427
+	}
428
+
429
+	/**
430
+	 * @return void
431
+	 */
432
+	protected function reset()
433
+	{
434
+		if ($this->size() <= pow(1024, 2) / 8) {
435
+			return;
436
+		}
437
+		$this->clear();
438
+		file_put_contents(
439
+			$this->file,
440
+			$this->buildLogEntry(
441
+				static::NOTICE,
442
+				__('Console was automatically cleared (128 KB maximum size)', 'site-reviews')
443
+			)
444
+		);
445
+	}
446 446
 }
Please login to merge, or discard this patch.
deprecated.php 1 patch
Indentation   +116 added lines, -116 removed lines patch added patch discarded remove patch
@@ -3,134 +3,134 @@
 block discarded – undo
3 3
 defined('WPINC') || die;
4 4
 
5 5
 if (apply_filters('site-reviews/support/deprecated/v4', true)) {
6
-    // Unprotected review meta has been deprecated
7
-    add_filter('get_post_metadata', function ($data, $postId, $metaKey, $single) {
8
-        $metaKeys = array_keys(glsr('Defaults\CreateReviewDefaults')->defaults());
9
-        if (!in_array($metaKey, $metaKeys) || glsr()->post_type != get_post_type($postId)) {
10
-            return $data;
11
-        }
12
-        glsr()->deprecated[] = sprintf(
13
-            'The "%1$s" meta_key has been deprecated for Reviews. Please use the protected "_%1$s" meta_key instead.',
14
-            $metaKey
15
-        );
16
-        return get_post_meta($postId, '_'.$metaKey, $single);
17
-    }, 10, 4);
6
+	// Unprotected review meta has been deprecated
7
+	add_filter('get_post_metadata', function ($data, $postId, $metaKey, $single) {
8
+		$metaKeys = array_keys(glsr('Defaults\CreateReviewDefaults')->defaults());
9
+		if (!in_array($metaKey, $metaKeys) || glsr()->post_type != get_post_type($postId)) {
10
+			return $data;
11
+		}
12
+		glsr()->deprecated[] = sprintf(
13
+			'The "%1$s" meta_key has been deprecated for Reviews. Please use the protected "_%1$s" meta_key instead.',
14
+			$metaKey
15
+		);
16
+		return get_post_meta($postId, '_'.$metaKey, $single);
17
+	}, 10, 4);
18 18
 
19
-    // Modules/Html/Template.php
20
-    add_filter('site-reviews/interpolate/reviews', function ($context, $template) {
21
-        $search = '{{ navigation }}';
22
-        if (false !== strpos($template, $search)) {
23
-            $context['navigation'] = $context['pagination'];
24
-            glsr()->deprecated[] = 'The {{ navigation }} template key in "YOUR_THEME/site-reviews/reviews.php" has been deprecated. Please use the {{ pagination }} template key instead.';
25
-        }
26
-        return $context;
27
-    }, 10, 2);
19
+	// Modules/Html/Template.php
20
+	add_filter('site-reviews/interpolate/reviews', function ($context, $template) {
21
+		$search = '{{ navigation }}';
22
+		if (false !== strpos($template, $search)) {
23
+			$context['navigation'] = $context['pagination'];
24
+			glsr()->deprecated[] = 'The {{ navigation }} template key in "YOUR_THEME/site-reviews/reviews.php" has been deprecated. Please use the {{ pagination }} template key instead.';
25
+		}
26
+		return $context;
27
+	}, 10, 2);
28 28
 
29
-    // Database/ReviewManager.php
30
-    add_action('site-reviews/review/created', function ($review) {
31
-        if (has_action('site-reviews/local/review/create')) {
32
-            glsr()->deprecated[] = 'The "site-reviews/local/review/create" hook has been deprecated. Please use the "site-reviews/review/created" hook instead.';
33
-            do_action('site-reviews/local/review/create', (array) get_post($review->ID), (array) $review, $review->ID);
34
-        }
35
-    }, 9);
29
+	// Database/ReviewManager.php
30
+	add_action('site-reviews/review/created', function ($review) {
31
+		if (has_action('site-reviews/local/review/create')) {
32
+			glsr()->deprecated[] = 'The "site-reviews/local/review/create" hook has been deprecated. Please use the "site-reviews/review/created" hook instead.';
33
+			do_action('site-reviews/local/review/create', (array) get_post($review->ID), (array) $review, $review->ID);
34
+		}
35
+	}, 9);
36 36
 
37
-    // Handlers/CreateReview.php
38
-    add_action('site-reviews/review/submitted', function ($review) {
39
-        if (has_action('site-reviews/local/review/submitted')) {
40
-            glsr()->deprecated[] = 'The "site-reviews/local/review/submitted" hook has been deprecated. Please use the "site-reviews/review/submitted" hook instead.';
41
-            do_action('site-reviews/local/review/submitted', null, $review);
42
-        }
43
-        if (has_filter('site-reviews/local/review/submitted/message')) {
44
-            glsr()->deprecated[] = 'The "site-reviews/local/review/submitted/message" hook has been deprecated.';
45
-        }
46
-    }, 9);
37
+	// Handlers/CreateReview.php
38
+	add_action('site-reviews/review/submitted', function ($review) {
39
+		if (has_action('site-reviews/local/review/submitted')) {
40
+			glsr()->deprecated[] = 'The "site-reviews/local/review/submitted" hook has been deprecated. Please use the "site-reviews/review/submitted" hook instead.';
41
+			do_action('site-reviews/local/review/submitted', null, $review);
42
+		}
43
+		if (has_filter('site-reviews/local/review/submitted/message')) {
44
+			glsr()->deprecated[] = 'The "site-reviews/local/review/submitted/message" hook has been deprecated.';
45
+		}
46
+	}, 9);
47 47
 
48
-    // Database/ReviewManager.php
49
-    add_filter('site-reviews/create/review-values', function ($values, $command) {
50
-        if (has_filter('site-reviews/local/review')) {
51
-            glsr()->deprecated[] = 'The "site-reviews/local/review" hook has been deprecated. Please use the "site-reviews/create/review-values" hook instead.';
52
-            return apply_filters('site-reviews/local/review', $values, $command);
53
-        }
54
-        return $values;
55
-    }, 9, 2);
48
+	// Database/ReviewManager.php
49
+	add_filter('site-reviews/create/review-values', function ($values, $command) {
50
+		if (has_filter('site-reviews/local/review')) {
51
+			glsr()->deprecated[] = 'The "site-reviews/local/review" hook has been deprecated. Please use the "site-reviews/create/review-values" hook instead.';
52
+			return apply_filters('site-reviews/local/review', $values, $command);
53
+		}
54
+		return $values;
55
+	}, 9, 2);
56 56
 
57
-    // Handlers/EnqueuePublicAssets.php
58
-    add_filter('site-reviews/enqueue/public/localize', function ($variables) {
59
-        if (has_filter('site-reviews/enqueue/localize')) {
60
-            glsr()->deprecated[] = 'The "site-reviews/enqueue/localize" hook has been deprecated. Please use the "site-reviews/enqueue/public/localize" hook instead.';
61
-            return apply_filters('site-reviews/enqueue/localize', $variables);
62
-        }
63
-        return $variables;
64
-    }, 9);
57
+	// Handlers/EnqueuePublicAssets.php
58
+	add_filter('site-reviews/enqueue/public/localize', function ($variables) {
59
+		if (has_filter('site-reviews/enqueue/localize')) {
60
+			glsr()->deprecated[] = 'The "site-reviews/enqueue/localize" hook has been deprecated. Please use the "site-reviews/enqueue/public/localize" hook instead.';
61
+			return apply_filters('site-reviews/enqueue/localize', $variables);
62
+		}
63
+		return $variables;
64
+	}, 9);
65 65
 
66
-    // Modules/Rating.php
67
-    add_filter('site-reviews/rating/average', function ($average) {
68
-        if (has_filter('site-reviews/average/rating')) {
69
-            glsr()->deprecated[] = 'The "site-reviews/average/rating" hook has been deprecated. Please use the "site-reviews/rating/average" hook instead.';
70
-        }
71
-        return $average;
72
-    }, 9);
66
+	// Modules/Rating.php
67
+	add_filter('site-reviews/rating/average', function ($average) {
68
+		if (has_filter('site-reviews/average/rating')) {
69
+			glsr()->deprecated[] = 'The "site-reviews/average/rating" hook has been deprecated. Please use the "site-reviews/rating/average" hook instead.';
70
+		}
71
+		return $average;
72
+	}, 9);
73 73
 
74
-    // Modules/Rating.php
75
-    add_filter('site-reviews/rating/ranking', function ($ranking) {
76
-        if (has_filter('site-reviews/bayesian/ranking')) {
77
-            glsr()->deprecated[] = 'The "site-reviews/bayesian/ranking" hook has been deprecated. Please use the "site-reviews/rating/ranking" hook instead.';
78
-        }
79
-        return $ranking;
80
-    }, 9);
74
+	// Modules/Rating.php
75
+	add_filter('site-reviews/rating/ranking', function ($ranking) {
76
+		if (has_filter('site-reviews/bayesian/ranking')) {
77
+			glsr()->deprecated[] = 'The "site-reviews/bayesian/ranking" hook has been deprecated. Please use the "site-reviews/rating/ranking" hook instead.';
78
+		}
79
+		return $ranking;
80
+	}, 9);
81 81
 
82
-    // Modules/Html/Partials/SiteReviews.php
83
-    add_filter('site-reviews/review/build/after', function ($renderedFields) {
84
-        if (has_filter('site-reviews/reviews/review/text')) {
85
-            glsr()->deprecated[] = 'The "site-reviews/reviews/review/text" hook has been deprecated. Please use the "site-reviews/review/build/after" hook instead.';
86
-        }
87
-        if (has_filter('site-reviews/reviews/review/title')) {
88
-            glsr()->deprecated[] = 'The "site-reviews/reviews/review/title" hook has been deprecated. Please use the "site-reviews/review/build/after" hook instead.';
89
-        }
90
-        return $renderedFields;
91
-    }, 9);
82
+	// Modules/Html/Partials/SiteReviews.php
83
+	add_filter('site-reviews/review/build/after', function ($renderedFields) {
84
+		if (has_filter('site-reviews/reviews/review/text')) {
85
+			glsr()->deprecated[] = 'The "site-reviews/reviews/review/text" hook has been deprecated. Please use the "site-reviews/review/build/after" hook instead.';
86
+		}
87
+		if (has_filter('site-reviews/reviews/review/title')) {
88
+			glsr()->deprecated[] = 'The "site-reviews/reviews/review/title" hook has been deprecated. Please use the "site-reviews/review/build/after" hook instead.';
89
+		}
90
+		return $renderedFields;
91
+	}, 9);
92 92
 
93
-    // Modules/Html/Partials/SiteReviews.php
94
-    add_filter('site-reviews/review/build/before', function ($review) {
95
-        if (has_filter('site-reviews/rendered/review')) {
96
-            glsr()->deprecated[] = 'The "site-reviews/rendered/review" hook has been deprecated. Please either use a custom "review.php" template (refer to the documentation), or use the "site-reviews/review/build/after" hook instead.';
97
-        }
98
-        if (has_filter('site-reviews/rendered/review/meta/order')) {
99
-            glsr()->deprecated[] = 'The "site-reviews/rendered/review/meta/order" hook has been deprecated. Please use a custom "review.php" template instead (refer to the documentation).';
100
-        }
101
-        if (has_filter('site-reviews/rendered/review/order')) {
102
-            glsr()->deprecated[] = 'The "site-reviews/rendered/review/order" hook has been deprecated. Please use a custom "review.php" template instead (refer to the documentation).';
103
-        }
104
-        if (has_filter('site-reviews/rendered/review-form/login-register')) {
105
-            glsr()->deprecated[] = 'The "site-reviews/rendered/review-form/login-register" hook has been deprecated. Please use a custom "login-register.php" template instead (refer to the documentation).';
106
-        }
107
-        if (has_filter('site-reviews/reviews/navigation_links')) {
108
-            glsr()->deprecated[] = 'The "site-reviews/reviews/navigation_links" hook has been deprecated. Please use a custom "pagination.php" template instead (refer to the documentation).';
109
-        }
110
-        return $review;
111
-    }, 9);
93
+	// Modules/Html/Partials/SiteReviews.php
94
+	add_filter('site-reviews/review/build/before', function ($review) {
95
+		if (has_filter('site-reviews/rendered/review')) {
96
+			glsr()->deprecated[] = 'The "site-reviews/rendered/review" hook has been deprecated. Please either use a custom "review.php" template (refer to the documentation), or use the "site-reviews/review/build/after" hook instead.';
97
+		}
98
+		if (has_filter('site-reviews/rendered/review/meta/order')) {
99
+			glsr()->deprecated[] = 'The "site-reviews/rendered/review/meta/order" hook has been deprecated. Please use a custom "review.php" template instead (refer to the documentation).';
100
+		}
101
+		if (has_filter('site-reviews/rendered/review/order')) {
102
+			glsr()->deprecated[] = 'The "site-reviews/rendered/review/order" hook has been deprecated. Please use a custom "review.php" template instead (refer to the documentation).';
103
+		}
104
+		if (has_filter('site-reviews/rendered/review-form/login-register')) {
105
+			glsr()->deprecated[] = 'The "site-reviews/rendered/review-form/login-register" hook has been deprecated. Please use a custom "login-register.php" template instead (refer to the documentation).';
106
+		}
107
+		if (has_filter('site-reviews/reviews/navigation_links')) {
108
+			glsr()->deprecated[] = 'The "site-reviews/reviews/navigation_links" hook has been deprecated. Please use a custom "pagination.php" template instead (refer to the documentation).';
109
+		}
110
+		return $review;
111
+	}, 9);
112 112
 
113
-    add_filter('site-reviews/validate/custom', function ($result, $request) {
114
-        if (has_filter('site-reviews/validate/review/submission')) {
115
-            glsr_log()->warning('The "site-reviews/validate/review/submission" hook has been deprecated. Please use the "site-reviews/validate/custom" hook instead.');
116
-            return apply_filters('site-reviews/validate/review/submission', $result, $request);
117
-        }
118
-        return $result;
119
-    }, 9, 2);
113
+	add_filter('site-reviews/validate/custom', function ($result, $request) {
114
+		if (has_filter('site-reviews/validate/review/submission')) {
115
+			glsr_log()->warning('The "site-reviews/validate/review/submission" hook has been deprecated. Please use the "site-reviews/validate/custom" hook instead.');
116
+			return apply_filters('site-reviews/validate/review/submission', $result, $request);
117
+		}
118
+		return $result;
119
+	}, 9, 2);
120 120
 
121
-    add_filter('site-reviews/views/file', function ($file, $view, $data) {
122
-        if (has_filter('site-reviews/addon/views/file')) {
123
-            glsr()->deprecated[] = 'The "site-reviews/addon/views/file" hook has been deprecated. Please use the "site-reviews/views/file" hook instead.';
124
-            $file = apply_filters('site-reviews/addon/views/file', $file, $view, $data);
125
-        }
126
-        return $file;
127
-    }, 9, 3);
121
+	add_filter('site-reviews/views/file', function ($file, $view, $data) {
122
+		if (has_filter('site-reviews/addon/views/file')) {
123
+			glsr()->deprecated[] = 'The "site-reviews/addon/views/file" hook has been deprecated. Please use the "site-reviews/views/file" hook instead.';
124
+			$file = apply_filters('site-reviews/addon/views/file', $file, $view, $data);
125
+		}
126
+		return $file;
127
+	}, 9, 3);
128 128
 }
129 129
 
130 130
 add_action('wp_footer', function () {
131
-    $notices = array_keys(array_flip(glsr()->deprecated));
132
-    natsort($notices);
133
-    foreach ($notices as $notice) {
134
-        glsr_log()->warning($notice);
135
-    }
131
+	$notices = array_keys(array_flip(glsr()->deprecated));
132
+	natsort($notices);
133
+	foreach ($notices as $notice) {
134
+		glsr_log()->warning($notice);
135
+	}
136 136
 });
Please login to merge, or discard this patch.
plugin/Handlers/EnqueuePublicAssets.php 1 patch
Indentation   +136 added lines, -136 removed lines patch added patch discarded remove patch
@@ -9,148 +9,148 @@
 block discarded – undo
9 9
 
10 10
 class EnqueuePublicAssets
11 11
 {
12
-    /**
13
-     * @return void
14
-     */
15
-    public function handle()
16
-    {
17
-        $this->enqueueAssets();
18
-        $this->enqueuePolyfillService();
19
-        $this->enqueueRecaptchaScript();
20
-        $this->inlineScript();
21
-        $this->inlineStyles();
22
-    }
12
+	/**
13
+	 * @return void
14
+	 */
15
+	public function handle()
16
+	{
17
+		$this->enqueueAssets();
18
+		$this->enqueuePolyfillService();
19
+		$this->enqueueRecaptchaScript();
20
+		$this->inlineScript();
21
+		$this->inlineStyles();
22
+	}
23 23
 
24
-    /**
25
-     * @return void
26
-     */
27
-    public function enqueueAssets()
28
-    {
29
-        if (apply_filters('site-reviews/assets/css', true)) {
30
-            wp_enqueue_style(
31
-                Application::ID,
32
-                $this->getStylesheet(),
33
-                [],
34
-                glsr()->version
35
-            );
36
-        }
37
-        if (apply_filters('site-reviews/assets/js', true)) {
38
-            $dependencies = apply_filters('site-reviews/assets/polyfill', true)
39
-                ? [Application::ID.'/polyfill']
40
-                : [];
41
-            $dependencies = apply_filters('site-reviews/enqueue/public/dependencies', $dependencies);
42
-            wp_enqueue_script(
43
-                Application::ID,
44
-                glsr()->url('assets/scripts/'.Application::ID.'.js'),
45
-                $dependencies,
46
-                glsr()->version,
47
-                true
48
-            );
49
-        }
50
-    }
24
+	/**
25
+	 * @return void
26
+	 */
27
+	public function enqueueAssets()
28
+	{
29
+		if (apply_filters('site-reviews/assets/css', true)) {
30
+			wp_enqueue_style(
31
+				Application::ID,
32
+				$this->getStylesheet(),
33
+				[],
34
+				glsr()->version
35
+			);
36
+		}
37
+		if (apply_filters('site-reviews/assets/js', true)) {
38
+			$dependencies = apply_filters('site-reviews/assets/polyfill', true)
39
+				? [Application::ID.'/polyfill']
40
+				: [];
41
+			$dependencies = apply_filters('site-reviews/enqueue/public/dependencies', $dependencies);
42
+			wp_enqueue_script(
43
+				Application::ID,
44
+				glsr()->url('assets/scripts/'.Application::ID.'.js'),
45
+				$dependencies,
46
+				glsr()->version,
47
+				true
48
+			);
49
+		}
50
+	}
51 51
 
52
-    /**
53
-     * @return void
54
-     */
55
-    public function enqueuePolyfillService()
56
-    {
57
-        if (!apply_filters('site-reviews/assets/polyfill', true)) {
58
-            return;
59
-        }
60
-        wp_enqueue_script(Application::ID.'/polyfill', add_query_arg([
61
-            'features' => 'Array.prototype.findIndex,CustomEvent,Element.prototype.closest,Element.prototype.dataset,Event,XMLHttpRequest,MutationObserver',
62
-            'flags' => 'gated',
63
-        ], 'https://polyfill.io/v3/polyfill.min.js'));
64
-    }
52
+	/**
53
+	 * @return void
54
+	 */
55
+	public function enqueuePolyfillService()
56
+	{
57
+		if (!apply_filters('site-reviews/assets/polyfill', true)) {
58
+			return;
59
+		}
60
+		wp_enqueue_script(Application::ID.'/polyfill', add_query_arg([
61
+			'features' => 'Array.prototype.findIndex,CustomEvent,Element.prototype.closest,Element.prototype.dataset,Event,XMLHttpRequest,MutationObserver',
62
+			'flags' => 'gated',
63
+		], 'https://polyfill.io/v3/polyfill.min.js'));
64
+	}
65 65
 
66
-    /**
67
-     * @return void
68
-     */
69
-    public function enqueueRecaptchaScript()
70
-    {
71
-        // wpforms-recaptcha
72
-        // google-recaptcha
73
-        // nf-google-recaptcha
74
-        if (!glsr(OptionManager::class)->isRecaptchaEnabled()) {
75
-            return;
76
-        }
77
-        $language = apply_filters('site-reviews/recaptcha/language', get_locale());
78
-        wp_enqueue_script(Application::ID.'/google-recaptcha', add_query_arg([
79
-            'hl' => $language,
80
-            'render' => 'explicit',
81
-        ], 'https://www.google.com/recaptcha/api.js'));
82
-    }
66
+	/**
67
+	 * @return void
68
+	 */
69
+	public function enqueueRecaptchaScript()
70
+	{
71
+		// wpforms-recaptcha
72
+		// google-recaptcha
73
+		// nf-google-recaptcha
74
+		if (!glsr(OptionManager::class)->isRecaptchaEnabled()) {
75
+			return;
76
+		}
77
+		$language = apply_filters('site-reviews/recaptcha/language', get_locale());
78
+		wp_enqueue_script(Application::ID.'/google-recaptcha', add_query_arg([
79
+			'hl' => $language,
80
+			'render' => 'explicit',
81
+		], 'https://www.google.com/recaptcha/api.js'));
82
+	}
83 83
 
84
-    /**
85
-     * @return void
86
-     */
87
-    public function inlineScript()
88
-    {
89
-        $variables = [
90
-            'action' => Application::PREFIX.'action',
91
-            'ajaxpagination' => $this->getFixedSelectorsForPagination(),
92
-            'ajaxurl' => admin_url('admin-ajax.php'),
93
-            'nameprefix' => Application::ID,
94
-            'validationconfig' => glsr(Style::class)->validation,
95
-            'validationstrings' => glsr(ValidationStringsDefaults::class)->defaults(),
96
-        ];
97
-        $variables = apply_filters('site-reviews/enqueue/public/localize', $variables);
98
-        wp_add_inline_script(Application::ID, $this->buildInlineScript($variables), 'before');
99
-    }
84
+	/**
85
+	 * @return void
86
+	 */
87
+	public function inlineScript()
88
+	{
89
+		$variables = [
90
+			'action' => Application::PREFIX.'action',
91
+			'ajaxpagination' => $this->getFixedSelectorsForPagination(),
92
+			'ajaxurl' => admin_url('admin-ajax.php'),
93
+			'nameprefix' => Application::ID,
94
+			'validationconfig' => glsr(Style::class)->validation,
95
+			'validationstrings' => glsr(ValidationStringsDefaults::class)->defaults(),
96
+		];
97
+		$variables = apply_filters('site-reviews/enqueue/public/localize', $variables);
98
+		wp_add_inline_script(Application::ID, $this->buildInlineScript($variables), 'before');
99
+	}
100 100
 
101
-    /**
102
-     * @return void
103
-     */
104
-    public function inlineStyles()
105
-    {
106
-        $inlineStylesheetPath = glsr()->path('assets/styles/inline-styles.css');
107
-        if (!apply_filters('site-reviews/assets/css', true)) {
108
-            return;
109
-        }
110
-        if (!file_exists($inlineStylesheetPath)) {
111
-            glsr_log()->error('Inline stylesheet is missing: '.$inlineStylesheetPath);
112
-            return;
113
-        }
114
-        $inlineStylesheetValues = glsr()->config('inline-styles');
115
-        $stylesheet = str_replace(
116
-            array_keys($inlineStylesheetValues),
117
-            array_values($inlineStylesheetValues),
118
-            file_get_contents($inlineStylesheetPath)
119
-        );
120
-        wp_add_inline_style(Application::ID, $stylesheet);
121
-    }
101
+	/**
102
+	 * @return void
103
+	 */
104
+	public function inlineStyles()
105
+	{
106
+		$inlineStylesheetPath = glsr()->path('assets/styles/inline-styles.css');
107
+		if (!apply_filters('site-reviews/assets/css', true)) {
108
+			return;
109
+		}
110
+		if (!file_exists($inlineStylesheetPath)) {
111
+			glsr_log()->error('Inline stylesheet is missing: '.$inlineStylesheetPath);
112
+			return;
113
+		}
114
+		$inlineStylesheetValues = glsr()->config('inline-styles');
115
+		$stylesheet = str_replace(
116
+			array_keys($inlineStylesheetValues),
117
+			array_values($inlineStylesheetValues),
118
+			file_get_contents($inlineStylesheetPath)
119
+		);
120
+		wp_add_inline_style(Application::ID, $stylesheet);
121
+	}
122 122
 
123
-    /**
124
-     * @return string
125
-     */
126
-    protected function buildInlineScript(array $variables)
127
-    {
128
-        $script = 'window.hasOwnProperty("GLSR")||(window.GLSR={});';
129
-        foreach ($variables as $key => $value) {
130
-            $script.= sprintf('GLSR.%s=%s;', $key, json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
131
-        }
132
-        $pattern = '/\"([^ \-\"]+)\"(:[{\[\"])/'; // removes unnecessary quotes surrounding object keys
133
-        $optimizedScript = preg_replace($pattern, '$1$2', $script);
134
-        return apply_filters('site-reviews/enqueue/public/inline-script', $optimizedScript, $script, $variables);
135
-    }
123
+	/**
124
+	 * @return string
125
+	 */
126
+	protected function buildInlineScript(array $variables)
127
+	{
128
+		$script = 'window.hasOwnProperty("GLSR")||(window.GLSR={});';
129
+		foreach ($variables as $key => $value) {
130
+			$script.= sprintf('GLSR.%s=%s;', $key, json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
131
+		}
132
+		$pattern = '/\"([^ \-\"]+)\"(:[{\[\"])/'; // removes unnecessary quotes surrounding object keys
133
+		$optimizedScript = preg_replace($pattern, '$1$2', $script);
134
+		return apply_filters('site-reviews/enqueue/public/inline-script', $optimizedScript, $script, $variables);
135
+	}
136 136
 
137
-    /**
138
-     * @return array
139
-     */
140
-    protected function getFixedSelectorsForPagination()
141
-    {
142
-        $selectors = ['#wpadminbar', '.site-navigation-fixed'];
143
-        return apply_filters('site-reviews/enqueue/public/localize/ajax-pagination', $selectors);
144
-    }
137
+	/**
138
+	 * @return array
139
+	 */
140
+	protected function getFixedSelectorsForPagination()
141
+	{
142
+		$selectors = ['#wpadminbar', '.site-navigation-fixed'];
143
+		return apply_filters('site-reviews/enqueue/public/localize/ajax-pagination', $selectors);
144
+	}
145 145
 
146
-    /**
147
-     * @return string
148
-     */
149
-    protected function getStylesheet()
150
-    {
151
-        $currentStyle = glsr(Style::class)->style;
152
-        return file_exists(glsr()->path('assets/styles/custom/'.$currentStyle.'.css'))
153
-            ? glsr()->url('assets/styles/custom/'.$currentStyle.'.css')
154
-            : glsr()->url('assets/styles/'.Application::ID.'.css');
155
-    }
146
+	/**
147
+	 * @return string
148
+	 */
149
+	protected function getStylesheet()
150
+	{
151
+		$currentStyle = glsr(Style::class)->style;
152
+		return file_exists(glsr()->path('assets/styles/custom/'.$currentStyle.'.css'))
153
+			? glsr()->url('assets/styles/custom/'.$currentStyle.'.css')
154
+			: glsr()->url('assets/styles/'.Application::ID.'.css');
155
+	}
156 156
 }
Please login to merge, or discard this patch.
plugin/Defaults/StyleValidationDefaults.php 1 patch
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -6,23 +6,23 @@
 block discarded – undo
6 6
 
7 7
 class StyleValidationDefaults extends Defaults
8 8
 {
9
-    /**
10
-     * @return array
11
-     */
12
-    protected function defaults()
13
-    {
14
-        return [
15
-            'error_tag' => 'div',
16
-            'error_tag_class' => 'glsr-field-error',
17
-            'field_class' => 'glsr-field',
18
-            'field_error_class' => 'glsr-has-error',
19
-            'input_error_class' => 'glsr-is-invalid',
20
-            'input_valid_class' => 'glsr-is-valid',
21
-            'message_error_class' => 'glsr-has-errors',
22
-            'message_initial_class' => 'glsr-is-visible',
23
-            'message_success_class' => 'glsr-has-success',
24
-            'message_tag' => 'div',
25
-            'message_tag_class' => 'glsr-form-message',
26
-        ];
27
-    }
9
+	/**
10
+	 * @return array
11
+	 */
12
+	protected function defaults()
13
+	{
14
+		return [
15
+			'error_tag' => 'div',
16
+			'error_tag_class' => 'glsr-field-error',
17
+			'field_class' => 'glsr-field',
18
+			'field_error_class' => 'glsr-has-error',
19
+			'input_error_class' => 'glsr-is-invalid',
20
+			'input_valid_class' => 'glsr-is-valid',
21
+			'message_error_class' => 'glsr-has-errors',
22
+			'message_initial_class' => 'glsr-is-visible',
23
+			'message_success_class' => 'glsr-has-success',
24
+			'message_tag' => 'div',
25
+			'message_tag_class' => 'glsr-form-message',
26
+		];
27
+	}
28 28
 }
Please login to merge, or discard this patch.
plugin/Handlers/EnqueueAdminAssets.php 1 patch
Indentation   +146 added lines, -146 removed lines patch added patch discarded remove patch
@@ -10,158 +10,158 @@
 block discarded – undo
10 10
 
11 11
 class EnqueueAdminAssets
12 12
 {
13
-    /**
14
-     * @var array
15
-     */
16
-    protected $pointers;
13
+	/**
14
+	 * @var array
15
+	 */
16
+	protected $pointers;
17 17
 
18
-    /**
19
-     * @return void
20
-     */
21
-    public function handle(Command $command)
22
-    {
23
-        $this->generatePointers($command->pointers);
24
-        $this->enqueueAssets();
25
-        $this->localizeAssets();
26
-    }
18
+	/**
19
+	 * @return void
20
+	 */
21
+	public function handle(Command $command)
22
+	{
23
+		$this->generatePointers($command->pointers);
24
+		$this->enqueueAssets();
25
+		$this->localizeAssets();
26
+	}
27 27
 
28
-    /**
29
-     * @return void
30
-     */
31
-    public function enqueueAssets()
32
-    {
33
-        if (!$this->isCurrentScreen()) {
34
-            return;
35
-        }
36
-        wp_enqueue_style(
37
-            Application::ID,
38
-            glsr()->url('assets/styles/'.Application::ID.'-admin.css'),
39
-            [],
40
-            glsr()->version
41
-        );
42
-        wp_enqueue_script(
43
-            Application::ID,
44
-            glsr()->url('assets/scripts/'.Application::ID.'-admin.js'),
45
-            $this->getDependencies(),
46
-            glsr()->version,
47
-            true
48
-        );
49
-        if (!empty($this->pointers)) {
50
-            wp_enqueue_style('wp-pointer');
51
-            wp_enqueue_script('wp-pointer');
52
-        }
53
-    }
28
+	/**
29
+	 * @return void
30
+	 */
31
+	public function enqueueAssets()
32
+	{
33
+		if (!$this->isCurrentScreen()) {
34
+			return;
35
+		}
36
+		wp_enqueue_style(
37
+			Application::ID,
38
+			glsr()->url('assets/styles/'.Application::ID.'-admin.css'),
39
+			[],
40
+			glsr()->version
41
+		);
42
+		wp_enqueue_script(
43
+			Application::ID,
44
+			glsr()->url('assets/scripts/'.Application::ID.'-admin.js'),
45
+			$this->getDependencies(),
46
+			glsr()->version,
47
+			true
48
+		);
49
+		if (!empty($this->pointers)) {
50
+			wp_enqueue_style('wp-pointer');
51
+			wp_enqueue_script('wp-pointer');
52
+		}
53
+	}
54 54
 
55
-    /**
56
-     * @return void
57
-     */
58
-    public function localizeAssets()
59
-    {
60
-        $variables = [
61
-            'action' => Application::PREFIX.'action',
62
-            'addons' => [],
63
-            'ajaxurl' => admin_url('admin-ajax.php'),
64
-            'hideoptions' => [
65
-                'site_reviews' => glsr(SiteReviewsShortcode::class)->getHideOptions(),
66
-                'site_reviews_form' => glsr(SiteReviewsFormShortcode::class)->getHideOptions(),
67
-                'site_reviews_summary' => glsr(SiteReviewsSummaryShortcode::class)->getHideOptions(),
68
-            ],
69
-            'nameprefix' => Application::ID,
70
-            'nonce' => [
71
-                'change-status' => wp_create_nonce('change-status'),
72
-                'clear-console' => wp_create_nonce('clear-console'),
73
-                'count-reviews' => wp_create_nonce('count-reviews'),
74
-                'fetch-console' => wp_create_nonce('fetch-console'),
75
-                'mce-shortcode' => wp_create_nonce('mce-shortcode'),
76
-                'sync-reviews' => wp_create_nonce('sync-reviews'),
77
-                'toggle-pinned' => wp_create_nonce('toggle-pinned'),
78
-            ],
79
-            'pointers' => $this->pointers,
80
-            'shortcodes' => [],
81
-            'tinymce' => [
82
-                'glsr_shortcode' => glsr()->url('assets/scripts/mce-plugin.js'),
83
-            ],
84
-        ];
85
-        if (user_can_richedit()) {
86
-            $variables['shortcodes'] = $this->localizeShortcodes();
87
-        }
88
-        $variables = apply_filters('site-reviews/enqueue/admin/localize', $variables);
89
-        wp_localize_script(Application::ID, 'GLSR', $variables);
90
-    }
55
+	/**
56
+	 * @return void
57
+	 */
58
+	public function localizeAssets()
59
+	{
60
+		$variables = [
61
+			'action' => Application::PREFIX.'action',
62
+			'addons' => [],
63
+			'ajaxurl' => admin_url('admin-ajax.php'),
64
+			'hideoptions' => [
65
+				'site_reviews' => glsr(SiteReviewsShortcode::class)->getHideOptions(),
66
+				'site_reviews_form' => glsr(SiteReviewsFormShortcode::class)->getHideOptions(),
67
+				'site_reviews_summary' => glsr(SiteReviewsSummaryShortcode::class)->getHideOptions(),
68
+			],
69
+			'nameprefix' => Application::ID,
70
+			'nonce' => [
71
+				'change-status' => wp_create_nonce('change-status'),
72
+				'clear-console' => wp_create_nonce('clear-console'),
73
+				'count-reviews' => wp_create_nonce('count-reviews'),
74
+				'fetch-console' => wp_create_nonce('fetch-console'),
75
+				'mce-shortcode' => wp_create_nonce('mce-shortcode'),
76
+				'sync-reviews' => wp_create_nonce('sync-reviews'),
77
+				'toggle-pinned' => wp_create_nonce('toggle-pinned'),
78
+			],
79
+			'pointers' => $this->pointers,
80
+			'shortcodes' => [],
81
+			'tinymce' => [
82
+				'glsr_shortcode' => glsr()->url('assets/scripts/mce-plugin.js'),
83
+			],
84
+		];
85
+		if (user_can_richedit()) {
86
+			$variables['shortcodes'] = $this->localizeShortcodes();
87
+		}
88
+		$variables = apply_filters('site-reviews/enqueue/admin/localize', $variables);
89
+		wp_localize_script(Application::ID, 'GLSR', $variables);
90
+	}
91 91
 
92
-    /**
93
-     * @return array
94
-     */
95
-    protected function getDependencies()
96
-    {
97
-        $dependencies = apply_filters('site-reviews/enqueue/admin/dependencies', []);
98
-        $dependencies = array_merge($dependencies, [
99
-            'jquery', 'jquery-ui-sortable', 'underscore', 'wp-util',
100
-        ]);
101
-        return $dependencies;
102
-    }
92
+	/**
93
+	 * @return array
94
+	 */
95
+	protected function getDependencies()
96
+	{
97
+		$dependencies = apply_filters('site-reviews/enqueue/admin/dependencies', []);
98
+		$dependencies = array_merge($dependencies, [
99
+			'jquery', 'jquery-ui-sortable', 'underscore', 'wp-util',
100
+		]);
101
+		return $dependencies;
102
+	}
103 103
 
104
-    /**
105
-     * @return array
106
-     */
107
-    protected function generatePointer(array $pointer)
108
-    {
109
-        return [
110
-            'id' => $pointer['id'],
111
-            'options' => [
112
-                'content' => '<h3>'.$pointer['title'].'</h3><p>'.$pointer['content'].'</p>',
113
-                'position' => $pointer['position'],
114
-            ],
115
-            'screen' => $pointer['screen'],
116
-            'target' => $pointer['target'],
117
-        ];
118
-    }
104
+	/**
105
+	 * @return array
106
+	 */
107
+	protected function generatePointer(array $pointer)
108
+	{
109
+		return [
110
+			'id' => $pointer['id'],
111
+			'options' => [
112
+				'content' => '<h3>'.$pointer['title'].'</h3><p>'.$pointer['content'].'</p>',
113
+				'position' => $pointer['position'],
114
+			],
115
+			'screen' => $pointer['screen'],
116
+			'target' => $pointer['target'],
117
+		];
118
+	}
119 119
 
120
-    /**
121
-     * @return void
122
-     */
123
-    protected function generatePointers(array $pointers)
124
-    {
125
-        $dismissedPointers = get_user_meta(get_current_user_id(), 'dismissed_wp_pointers', true);
126
-        $dismissedPointers = explode(',', (string) $dismissedPointers);
127
-        $generatedPointers = [];
128
-        foreach ($pointers as $pointer) {
129
-            if ($pointer['screen'] != glsr_current_screen()->id) {
130
-                continue;
131
-            }
132
-            if (in_array($pointer['id'], $dismissedPointers)) {
133
-                continue;
134
-            }
135
-            $generatedPointers[] = $this->generatePointer($pointer);
136
-        }
137
-        $this->pointers = $generatedPointers;
138
-    }
120
+	/**
121
+	 * @return void
122
+	 */
123
+	protected function generatePointers(array $pointers)
124
+	{
125
+		$dismissedPointers = get_user_meta(get_current_user_id(), 'dismissed_wp_pointers', true);
126
+		$dismissedPointers = explode(',', (string) $dismissedPointers);
127
+		$generatedPointers = [];
128
+		foreach ($pointers as $pointer) {
129
+			if ($pointer['screen'] != glsr_current_screen()->id) {
130
+				continue;
131
+			}
132
+			if (in_array($pointer['id'], $dismissedPointers)) {
133
+				continue;
134
+			}
135
+			$generatedPointers[] = $this->generatePointer($pointer);
136
+		}
137
+		$this->pointers = $generatedPointers;
138
+	}
139 139
 
140
-    /**
141
-     * @return bool
142
-     */
143
-    protected function isCurrentScreen()
144
-    {
145
-        $screen = glsr_current_screen();
146
-        return Application::POST_TYPE == $screen->post_type
147
-            || 'dashboard' == $screen->id
148
-            || 'plugins_page_'.Application::ID == $screen->id
149
-            || 'post' == $screen->base
150
-            || 'widgets' == $screen->id;
151
-    }
140
+	/**
141
+	 * @return bool
142
+	 */
143
+	protected function isCurrentScreen()
144
+	{
145
+		$screen = glsr_current_screen();
146
+		return Application::POST_TYPE == $screen->post_type
147
+			|| 'dashboard' == $screen->id
148
+			|| 'plugins_page_'.Application::ID == $screen->id
149
+			|| 'post' == $screen->base
150
+			|| 'widgets' == $screen->id;
151
+	}
152 152
 
153
-    /**
154
-     * @return array
155
-     */
156
-    protected function localizeShortcodes()
157
-    {
158
-        $variables = [];
159
-        foreach (glsr()->mceShortcodes as $tag => $args) {
160
-            if (empty($args['required'])) {
161
-                continue;
162
-            }
163
-            $variables[$tag] = $args['required'];
164
-        }
165
-        return $variables;
166
-    }
153
+	/**
154
+	 * @return array
155
+	 */
156
+	protected function localizeShortcodes()
157
+	{
158
+		$variables = [];
159
+		foreach (glsr()->mceShortcodes as $tag => $args) {
160
+			if (empty($args['required'])) {
161
+				continue;
162
+			}
163
+			$variables[$tag] = $args['required'];
164
+		}
165
+		return $variables;
166
+	}
167 167
 }
Please login to merge, or discard this patch.
plugin/Modules/Rating.php 1 patch
Indentation   +191 added lines, -191 removed lines patch added patch discarded remove patch
@@ -4,207 +4,207 @@
 block discarded – undo
4 4
 
5 5
 class Rating
6 6
 {
7
-    /**
8
-     * The more sure we are of the confidence interval (the higher the confidence level), the less
9
-     * precise the estimation will be as the margin for error will be higher.
10
-     * @see http://homepages.math.uic.edu/~bpower6/stat101/Confidence%20Intervals.pdf
11
-     * @see https://www.thecalculator.co/math/Confidence-Interval-Calculator-210.html
12
-     * @see https://www.youtube.com/watch?v=grodoLzThy4
13
-     * @see https://en.wikipedia.org/wiki/Standard_score
14
-     * @var array
15
-     */
16
-    const CONFIDENCE_LEVEL_Z_SCORES = [
17
-        50 => 0.67449,
18
-        70 => 1.04,
19
-        75 => 1.15035,
20
-        80 => 1.282,
21
-        85 => 1.44,
22
-        90 => 1.64485,
23
-        92 => 1.75,
24
-        95 => 1.95996,
25
-        96 => 2.05,
26
-        97 => 2.17009,
27
-        98 => 2.326,
28
-        99 => 2.57583,
29
-        '99.5' => 2.81,
30
-        '99.8' => 3.08,
31
-        '99.9' => 3.29053,
32
-    ];
7
+	/**
8
+	 * The more sure we are of the confidence interval (the higher the confidence level), the less
9
+	 * precise the estimation will be as the margin for error will be higher.
10
+	 * @see http://homepages.math.uic.edu/~bpower6/stat101/Confidence%20Intervals.pdf
11
+	 * @see https://www.thecalculator.co/math/Confidence-Interval-Calculator-210.html
12
+	 * @see https://www.youtube.com/watch?v=grodoLzThy4
13
+	 * @see https://en.wikipedia.org/wiki/Standard_score
14
+	 * @var array
15
+	 */
16
+	const CONFIDENCE_LEVEL_Z_SCORES = [
17
+		50 => 0.67449,
18
+		70 => 1.04,
19
+		75 => 1.15035,
20
+		80 => 1.282,
21
+		85 => 1.44,
22
+		90 => 1.64485,
23
+		92 => 1.75,
24
+		95 => 1.95996,
25
+		96 => 2.05,
26
+		97 => 2.17009,
27
+		98 => 2.326,
28
+		99 => 2.57583,
29
+		'99.5' => 2.81,
30
+		'99.8' => 3.08,
31
+		'99.9' => 3.29053,
32
+	];
33 33
 
34
-    /**
35
-     * @var int
36
-     */
37
-    const MAX_RATING = 5;
34
+	/**
35
+	 * @var int
36
+	 */
37
+	const MAX_RATING = 5;
38 38
 
39
-    /**
40
-     * @var int
41
-     */
42
-    const MIN_RATING = 1;
39
+	/**
40
+	 * @var int
41
+	 */
42
+	const MIN_RATING = 1;
43 43
 
44
-    /**
45
-     * @param int $roundBy
46
-     * @return float
47
-     */
48
-    public function getAverage(array $ratingCounts, $roundBy = 1)
49
-    {
50
-        $average = array_sum($ratingCounts);
51
-        if ($average > 0) {
52
-            $average = $this->getTotalSum($ratingCounts) / $average;
53
-        }
54
-        $roundedAverage = round($average, intval($roundBy));
55
-        return floatval(apply_filters('site-reviews/rating/average', $roundedAverage, $ratingCounts, $average));
56
-    }
44
+	/**
45
+	 * @param int $roundBy
46
+	 * @return float
47
+	 */
48
+	public function getAverage(array $ratingCounts, $roundBy = 1)
49
+	{
50
+		$average = array_sum($ratingCounts);
51
+		if ($average > 0) {
52
+			$average = $this->getTotalSum($ratingCounts) / $average;
53
+		}
54
+		$roundedAverage = round($average, intval($roundBy));
55
+		return floatval(apply_filters('site-reviews/rating/average', $roundedAverage, $ratingCounts, $average));
56
+	}
57 57
 
58
-    /**
59
-     * Get the lower bound for up/down ratings
60
-     * Method receives an up/down ratings array: [1, -1, -1, 1, 1, -1].
61
-     * @see http://www.evanmiller.org/how-not-to-sort-by-average-rating.html
62
-     * @see https://news.ycombinator.com/item?id=10481507
63
-     * @see https://dataorigami.net/blogs/napkin-folding/79030467-an-algorithm-to-sort-top-comments
64
-     * @see http://julesjacobs.github.io/2015/08/17/bayesian-scoring-of-ratings.html
65
-     * @param int $confidencePercentage
66
-     * @return int|float
67
-     */
68
-    public function getLowerBound(array $upDownCounts = [0, 0], $confidencePercentage = 95)
69
-    {
70
-        $numRatings = array_sum($upDownCounts);
71
-        if ($numRatings < 1) {
72
-            return 0;
73
-        }
74
-        $z = static::CONFIDENCE_LEVEL_Z_SCORES[$confidencePercentage];
75
-        $phat = 1 * $upDownCounts[1] / $numRatings;
76
-        return ($phat + $z * $z / (2 * $numRatings) - $z * sqrt(($phat * (1 - $phat) + $z * $z / (4 * $numRatings)) / $numRatings)) / (1 + $z * $z / $numRatings);
77
-    }
58
+	/**
59
+	 * Get the lower bound for up/down ratings
60
+	 * Method receives an up/down ratings array: [1, -1, -1, 1, 1, -1].
61
+	 * @see http://www.evanmiller.org/how-not-to-sort-by-average-rating.html
62
+	 * @see https://news.ycombinator.com/item?id=10481507
63
+	 * @see https://dataorigami.net/blogs/napkin-folding/79030467-an-algorithm-to-sort-top-comments
64
+	 * @see http://julesjacobs.github.io/2015/08/17/bayesian-scoring-of-ratings.html
65
+	 * @param int $confidencePercentage
66
+	 * @return int|float
67
+	 */
68
+	public function getLowerBound(array $upDownCounts = [0, 0], $confidencePercentage = 95)
69
+	{
70
+		$numRatings = array_sum($upDownCounts);
71
+		if ($numRatings < 1) {
72
+			return 0;
73
+		}
74
+		$z = static::CONFIDENCE_LEVEL_Z_SCORES[$confidencePercentage];
75
+		$phat = 1 * $upDownCounts[1] / $numRatings;
76
+		return ($phat + $z * $z / (2 * $numRatings) - $z * sqrt(($phat * (1 - $phat) + $z * $z / (4 * $numRatings)) / $numRatings)) / (1 + $z * $z / $numRatings);
77
+	}
78 78
 
79
-    /**
80
-     * @return int|float
81
-     */
82
-    public function getOverallPercentage(array $ratingCounts)
83
-    {
84
-        return round($this->getAverage($ratingCounts) * 100 / glsr()->constant('MAX_RATING', __CLASS__), 2);
85
-    }
79
+	/**
80
+	 * @return int|float
81
+	 */
82
+	public function getOverallPercentage(array $ratingCounts)
83
+	{
84
+		return round($this->getAverage($ratingCounts) * 100 / glsr()->constant('MAX_RATING', __CLASS__), 2);
85
+	}
86 86
 
87
-    /**
88
-     * @return array
89
-     */
90
-    public function getPercentages(array $ratingCounts)
91
-    {
92
-        $total = array_sum($ratingCounts);
93
-        foreach ($ratingCounts as $index => $count) {
94
-            if (empty($count)) {
95
-                continue;
96
-            }
97
-            $ratingCounts[$index] = $count / $total * 100;
98
-        }
99
-        return $this->getRoundedPercentages($ratingCounts);
100
-    }
87
+	/**
88
+	 * @return array
89
+	 */
90
+	public function getPercentages(array $ratingCounts)
91
+	{
92
+		$total = array_sum($ratingCounts);
93
+		foreach ($ratingCounts as $index => $count) {
94
+			if (empty($count)) {
95
+				continue;
96
+			}
97
+			$ratingCounts[$index] = $count / $total * 100;
98
+		}
99
+		return $this->getRoundedPercentages($ratingCounts);
100
+	}
101 101
 
102
-    /**
103
-     * @return float
104
-     */
105
-    public function getRanking(array $ratingCounts)
106
-    {
107
-        return floatval(apply_filters('site-reviews/rating/ranking',
108
-            $this->getRankingUsingImdb($ratingCounts),
109
-            $ratingCounts,
110
-            $this
111
-        ));
112
-    }
102
+	/**
103
+	 * @return float
104
+	 */
105
+	public function getRanking(array $ratingCounts)
106
+	{
107
+		return floatval(apply_filters('site-reviews/rating/ranking',
108
+			$this->getRankingUsingImdb($ratingCounts),
109
+			$ratingCounts,
110
+			$this
111
+		));
112
+	}
113 113
 
114
-    /**
115
-     * Get the bayesian ranking for an array of reviews
116
-     * This formula is the same one used by IMDB to rank their top 250 films.
117
-     * @see https://www.xkcd.com/937/
118
-     * @see https://districtdatalabs.silvrback.com/computing-a-bayesian-estimate-of-star-rating-means
119
-     * @see http://fulmicoton.com/posts/bayesian_rating/
120
-     * @see https://stats.stackexchange.com/questions/93974/is-there-an-equivalent-to-lower-bound-of-wilson-score-confidence-interval-for-va
121
-     * @param int $confidencePercentage
122
-     * @return int|float
123
-     */
124
-    public function getRankingUsingImdb(array $ratingCounts, $confidencePercentage = 70)
125
-    {
126
-        $avgRating = $this->getAverage($ratingCounts);
127
-        // Represents a prior (your prior opinion without data) for the average star rating. A higher prior also means a higher margin for error.
128
-        // This could also be the average score of all items instead of a fixed value.
129
-        $bayesMean = ($confidencePercentage / 100) * glsr()->constant('MAX_RATING', __CLASS__); // prior, 70% = 3.5
130
-        // Represents the number of ratings expected to begin observing a pattern that would put confidence in the prior.
131
-        $bayesMinimal = 10; // confidence
132
-        $numOfReviews = array_sum($ratingCounts);
133
-        return $avgRating > 0
134
-            ? (($bayesMinimal * $bayesMean) + ($avgRating * $numOfReviews)) / ($bayesMinimal + $numOfReviews)
135
-            : 0;
136
-    }
114
+	/**
115
+	 * Get the bayesian ranking for an array of reviews
116
+	 * This formula is the same one used by IMDB to rank their top 250 films.
117
+	 * @see https://www.xkcd.com/937/
118
+	 * @see https://districtdatalabs.silvrback.com/computing-a-bayesian-estimate-of-star-rating-means
119
+	 * @see http://fulmicoton.com/posts/bayesian_rating/
120
+	 * @see https://stats.stackexchange.com/questions/93974/is-there-an-equivalent-to-lower-bound-of-wilson-score-confidence-interval-for-va
121
+	 * @param int $confidencePercentage
122
+	 * @return int|float
123
+	 */
124
+	public function getRankingUsingImdb(array $ratingCounts, $confidencePercentage = 70)
125
+	{
126
+		$avgRating = $this->getAverage($ratingCounts);
127
+		// Represents a prior (your prior opinion without data) for the average star rating. A higher prior also means a higher margin for error.
128
+		// This could also be the average score of all items instead of a fixed value.
129
+		$bayesMean = ($confidencePercentage / 100) * glsr()->constant('MAX_RATING', __CLASS__); // prior, 70% = 3.5
130
+		// Represents the number of ratings expected to begin observing a pattern that would put confidence in the prior.
131
+		$bayesMinimal = 10; // confidence
132
+		$numOfReviews = array_sum($ratingCounts);
133
+		return $avgRating > 0
134
+			? (($bayesMinimal * $bayesMean) + ($avgRating * $numOfReviews)) / ($bayesMinimal + $numOfReviews)
135
+			: 0;
136
+	}
137 137
 
138
-    /**
139
-     * The quality of a 5 star rating depends not only on the average number of stars but also on
140
-     * the number of reviews. This method calculates the bayesian ranking of a page by its number
141
-     * of reviews and their rating.
142
-     * @see http://www.evanmiller.org/ranking-items-with-star-ratings.html
143
-     * @see https://stackoverflow.com/questions/1411199/what-is-a-better-way-to-sort-by-a-5-star-rating/1411268
144
-     * @see http://julesjacobs.github.io/2015/08/17/bayesian-scoring-of-ratings.html
145
-     * @param int $confidencePercentage
146
-     * @return float
147
-     */
148
-    public function getRankingUsingZScores(array $ratingCounts, $confidencePercentage = 90)
149
-    {
150
-        $ratingCountsSum = array_sum($ratingCounts) + glsr()->constant('MAX_RATING', __CLASS__);
151
-        $weight = $this->getWeight($ratingCounts, $ratingCountsSum);
152
-        $weightPow2 = $this->getWeight($ratingCounts, $ratingCountsSum, true);
153
-        $zScore = static::CONFIDENCE_LEVEL_Z_SCORES[$confidencePercentage];
154
-        return $weight - $zScore * sqrt(($weightPow2 - pow($weight, 2)) / ($ratingCountsSum + 1));
155
-    }
138
+	/**
139
+	 * The quality of a 5 star rating depends not only on the average number of stars but also on
140
+	 * the number of reviews. This method calculates the bayesian ranking of a page by its number
141
+	 * of reviews and their rating.
142
+	 * @see http://www.evanmiller.org/ranking-items-with-star-ratings.html
143
+	 * @see https://stackoverflow.com/questions/1411199/what-is-a-better-way-to-sort-by-a-5-star-rating/1411268
144
+	 * @see http://julesjacobs.github.io/2015/08/17/bayesian-scoring-of-ratings.html
145
+	 * @param int $confidencePercentage
146
+	 * @return float
147
+	 */
148
+	public function getRankingUsingZScores(array $ratingCounts, $confidencePercentage = 90)
149
+	{
150
+		$ratingCountsSum = array_sum($ratingCounts) + glsr()->constant('MAX_RATING', __CLASS__);
151
+		$weight = $this->getWeight($ratingCounts, $ratingCountsSum);
152
+		$weightPow2 = $this->getWeight($ratingCounts, $ratingCountsSum, true);
153
+		$zScore = static::CONFIDENCE_LEVEL_Z_SCORES[$confidencePercentage];
154
+		return $weight - $zScore * sqrt(($weightPow2 - pow($weight, 2)) / ($ratingCountsSum + 1));
155
+	}
156 156
 
157
-    /**
158
-     * @param int $target
159
-     * @return array
160
-     */
161
-    protected function getRoundedPercentages(array $percentages, $totalPercent = 100)
162
-    {
163
-        array_walk($percentages, function (&$percent, $index) {
164
-            $percent = [
165
-                'index' => $index,
166
-                'percent' => floor($percent),
167
-                'remainder' => fmod($percent, 1),
168
-            ];
169
-        });
170
-        $indexes = glsr_array_column($percentages, 'index');
171
-        $remainders = glsr_array_column($percentages, 'remainder');
172
-        array_multisort($remainders, SORT_DESC, SORT_STRING, $indexes, SORT_DESC, $percentages);
173
-        $i = 0;
174
-        if (array_sum(glsr_array_column($percentages, 'percent')) > 0) {
175
-            while (array_sum(glsr_array_column($percentages, 'percent')) < $totalPercent) {
176
-                ++$percentages[$i]['percent'];
177
-                ++$i;
178
-            }
179
-        }
180
-        array_multisort($indexes, SORT_DESC, $percentages);
181
-        return array_combine($indexes, glsr_array_column($percentages, 'percent'));
182
-    }
157
+	/**
158
+	 * @param int $target
159
+	 * @return array
160
+	 */
161
+	protected function getRoundedPercentages(array $percentages, $totalPercent = 100)
162
+	{
163
+		array_walk($percentages, function (&$percent, $index) {
164
+			$percent = [
165
+				'index' => $index,
166
+				'percent' => floor($percent),
167
+				'remainder' => fmod($percent, 1),
168
+			];
169
+		});
170
+		$indexes = glsr_array_column($percentages, 'index');
171
+		$remainders = glsr_array_column($percentages, 'remainder');
172
+		array_multisort($remainders, SORT_DESC, SORT_STRING, $indexes, SORT_DESC, $percentages);
173
+		$i = 0;
174
+		if (array_sum(glsr_array_column($percentages, 'percent')) > 0) {
175
+			while (array_sum(glsr_array_column($percentages, 'percent')) < $totalPercent) {
176
+				++$percentages[$i]['percent'];
177
+				++$i;
178
+			}
179
+		}
180
+		array_multisort($indexes, SORT_DESC, $percentages);
181
+		return array_combine($indexes, glsr_array_column($percentages, 'percent'));
182
+	}
183 183
 
184
-    /**
185
-     * @return int
186
-     */
187
-    protected function getTotalSum(array $ratingCounts)
188
-    {
189
-        return array_reduce(array_keys($ratingCounts), function ($carry, $index) use ($ratingCounts) {
190
-            return $carry + ($index * $ratingCounts[$index]);
191
-        });
192
-    }
184
+	/**
185
+	 * @return int
186
+	 */
187
+	protected function getTotalSum(array $ratingCounts)
188
+	{
189
+		return array_reduce(array_keys($ratingCounts), function ($carry, $index) use ($ratingCounts) {
190
+			return $carry + ($index * $ratingCounts[$index]);
191
+		});
192
+	}
193 193
 
194
-    /**
195
-     * @param int|float $ratingCountsSum
196
-     * @param bool $powerOf2
197
-     * @return float
198
-     */
199
-    protected function getWeight(array $ratingCounts, $ratingCountsSum, $powerOf2 = false)
200
-    {
201
-        return array_reduce(array_keys($ratingCounts),
202
-            function ($count, $rating) use ($ratingCounts, $ratingCountsSum, $powerOf2) {
203
-                $ratingLevel = $powerOf2
204
-                    ? pow($rating, 2)
205
-                    : $rating;
206
-                return $count + ($ratingLevel * ($ratingCounts[$rating] + 1)) / $ratingCountsSum;
207
-            }
208
-        );
209
-    }
194
+	/**
195
+	 * @param int|float $ratingCountsSum
196
+	 * @param bool $powerOf2
197
+	 * @return float
198
+	 */
199
+	protected function getWeight(array $ratingCounts, $ratingCountsSum, $powerOf2 = false)
200
+	{
201
+		return array_reduce(array_keys($ratingCounts),
202
+			function ($count, $rating) use ($ratingCounts, $ratingCountsSum, $powerOf2) {
203
+				$ratingLevel = $powerOf2
204
+					? pow($rating, 2)
205
+					: $rating;
206
+				return $count + ($ratingLevel * ($ratingCounts[$rating] + 1)) / $ratingCountsSum;
207
+			}
208
+		);
209
+	}
210 210
 }
Please login to merge, or discard this patch.
plugin/Modules/Html/Builder.php 1 patch
Indentation   +342 added lines, -342 removed lines patch added patch discarded remove patch
@@ -18,346 +18,346 @@
 block discarded – undo
18 18
  */
19 19
 class Builder
20 20
 {
21
-    const INPUT_TYPES = [
22
-        'checkbox', 'date', 'datetime-local', 'email', 'file', 'hidden', 'image', 'month',
23
-        'number', 'password', 'radio', 'range', 'reset', 'search', 'submit', 'tel', 'text', 'time',
24
-        'url', 'week',
25
-    ];
26
-
27
-    const TAGS_FORM = [
28
-        'input', 'select', 'textarea',
29
-    ];
30
-
31
-    const TAGS_SINGLE = [
32
-        'img',
33
-    ];
34
-
35
-    const TAGS_STRUCTURE = [
36
-        'div', 'form', 'nav', 'ol', 'section', 'ul',
37
-    ];
38
-
39
-    const TAGS_TEXT = [
40
-        'a', 'button', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'i', 'label', 'li', 'option', 'p', 'pre',
41
-        'small', 'span',
42
-    ];
43
-
44
-    /**
45
-     * @var array
46
-     */
47
-    public $args = [];
48
-
49
-    /**
50
-     * @var bool
51
-     */
52
-    public $render = false;
53
-
54
-    /**
55
-     * @var string
56
-     */
57
-    public $tag;
58
-
59
-    /**
60
-     * @param string $method
61
-     * @param array $args
62
-     * @return string|void
63
-     */
64
-    public function __call($method, $args)
65
-    {
66
-        $instance = new static();
67
-        $instance->setTagFromMethod($method);
68
-        call_user_func_array([$instance, 'normalize'], $args += ['', '']);
69
-        $tags = array_merge(static::TAGS_FORM, static::TAGS_SINGLE, static::TAGS_STRUCTURE, static::TAGS_TEXT);
70
-        do_action_ref_array('site-reviews/builder', [$instance]);
71
-        $generatedTag = in_array($instance->tag, $tags)
72
-            ? $instance->buildTag()
73
-            : $instance->buildCustomField();
74
-        $generatedTag = apply_filters('site-reviews/builder/result', $generatedTag, $instance);
75
-        if (!$this->render) {
76
-            return $generatedTag;
77
-        }
78
-        echo $generatedTag;
79
-    }
80
-
81
-    /**
82
-     * @param string $property
83
-     * @param mixed $value
84
-     * @return void
85
-     */
86
-    public function __set($property, $value)
87
-    {
88
-        $properties = [
89
-            'args' => 'is_array',
90
-            'render' => 'is_bool',
91
-            'tag' => 'is_string',
92
-        ];
93
-        if (!isset($properties[$property])
94
-            || empty(array_filter([$value], $properties[$property]))
95
-        ) {
96
-            return;
97
-        }
98
-        $this->$property = $value;
99
-    }
100
-
101
-    /**
102
-     * @return void|string
103
-     */
104
-    public function getClosingTag()
105
-    {
106
-        if (empty($this->tag)) {
107
-            return;
108
-        }
109
-        return '</'.$this->tag.'>';
110
-    }
111
-
112
-    /**
113
-     * @return void|string
114
-     */
115
-    public function getOpeningTag()
116
-    {
117
-        if (empty($this->tag)) {
118
-            return;
119
-        }
120
-        $attributes = glsr(Attributes::class)->{$this->tag}($this->args)->toString();
121
-        return '<'.trim($this->tag.' '.$attributes).'>';
122
-    }
123
-
124
-    /**
125
-     * @return void|string
126
-     */
127
-    public function getTag()
128
-    {
129
-        if (in_array($this->tag, static::TAGS_SINGLE)) {
130
-            return $this->getOpeningTag();
131
-        }
132
-        if (!in_array($this->tag, static::TAGS_FORM)) {
133
-            return $this->buildDefaultTag();
134
-        }
135
-        return call_user_func([$this, 'buildForm'.ucfirst($this->tag)]).$this->buildFieldDescription();
136
-    }
137
-
138
-    /**
139
-     * @return string
140
-     */
141
-    public function raw(array $field)
142
-    {
143
-        unset($field['label']);
144
-        return $this->{$field['type']}($field);
145
-    }
146
-
147
-    /**
148
-     * @return string|void
149
-     */
150
-    protected function buildCustomField()
151
-    {
152
-        $className = $this->getCustomFieldClassName();
153
-        if (class_exists($className)) {
154
-            return (new $className($this))->build();
155
-        }
156
-        glsr_log()->error('Field missing: '.$className);
157
-    }
158
-
159
-    /**
160
-     * @return string|void
161
-     */
162
-    protected function buildDefaultTag($text = '')
163
-    {
164
-        if (empty($text)) {
165
-            $text = $this->args['text'];
166
-        }
167
-        return $this->getOpeningTag().$text.$this->getClosingTag();
168
-    }
169
-
170
-    /**
171
-     * @return string|void
172
-     */
173
-    protected function buildFieldDescription()
174
-    {
175
-        if (empty($this->args['description'])) {
176
-            return;
177
-        }
178
-        if ($this->args['is_widget']) {
179
-            return $this->small($this->args['description']);
180
-        }
181
-        return $this->p($this->args['description'], ['class' => 'description']);
182
-    }
183
-
184
-    /**
185
-     * @return string|void
186
-     */
187
-    protected function buildFormInput()
188
-    {
189
-        if (!in_array($this->args['type'], ['checkbox', 'radio'])) {
190
-            if (isset($this->args['multiple'])) {
191
-                $this->args['name'].= '[]';
192
-            }
193
-            return $this->buildFormLabel().$this->getOpeningTag();
194
-        }
195
-        return empty($this->args['options'])
196
-            ? $this->buildFormInputChoice()
197
-            : $this->buildFormInputMultiChoice();
198
-    }
199
-
200
-    /**
201
-     * @return string|void
202
-     */
203
-    protected function buildFormInputChoice()
204
-    {
205
-        if (!empty($this->args['text'])) {
206
-            $this->args['label'] = $this->args['text'];
207
-        }
208
-        if (!$this->args['is_public']) {
209
-            return $this->buildFormLabel([
210
-                'class' => 'glsr-'.$this->args['type'].'-label',
211
-                'text' => $this->getOpeningTag().' '.$this->args['label'].'<span></span>',
212
-            ]);
213
-        }
214
-        return $this->getOpeningTag().$this->buildFormLabel([
215
-            'class' => 'glsr-'.$this->args['type'].'-label',
216
-            'text' => $this->args['label'].'<span></span>',
217
-        ]);
218
-    }
219
-
220
-    /**
221
-     * @return string|void
222
-     */
223
-    protected function buildFormInputMultiChoice()
224
-    {
225
-        if ('checkbox' == $this->args['type']) {
226
-            $this->args['name'].= '[]';
227
-        }
228
-        $index = 0;
229
-        $options = array_reduce(array_keys($this->args['options']), function ($carry, $key) use (&$index) {
230
-            return $carry.$this->li($this->{$this->args['type']}([
231
-                'checked' => in_array($key, (array) $this->args['value']),
232
-                'id' => $this->args['id'].'-'.$index++,
233
-                'name' => $this->args['name'],
234
-                'text' => $this->args['options'][$key],
235
-                'value' => $key,
236
-            ]));
237
-        });
238
-        return $this->ul($options, [
239
-            'class' => $this->args['class'],
240
-            'id' => $this->args['id'],
241
-        ]);
242
-    }
243
-
244
-    /**
245
-     * @return void|string
246
-     */
247
-    protected function buildFormLabel(array $customArgs = [])
248
-    {
249
-        if (empty($this->args['label']) || 'hidden' == $this->args['type']) {
250
-            return;
251
-        }
252
-        return $this->label(wp_parse_args($customArgs, [
253
-            'for' => $this->args['id'],
254
-            'is_public' => $this->args['is_public'],
255
-            'text' => $this->args['label'],
256
-            'type' => $this->args['type'],
257
-        ]));
258
-    }
259
-
260
-    /**
261
-     * @return string|void
262
-     */
263
-    protected function buildFormSelect()
264
-    {
265
-        return $this->buildFormLabel().$this->buildDefaultTag($this->buildFormSelectOptions());
266
-    }
267
-
268
-    /**
269
-     * @return string|void
270
-     */
271
-    protected function buildFormSelectOptions()
272
-    {
273
-        return array_reduce(array_keys($this->args['options']), function ($carry, $key) {
274
-            return $carry.$this->option([
275
-                'selected' => $this->args['value'] === (string) $key,
276
-                'text' => $this->args['options'][$key],
277
-                'value' => $key,
278
-            ]);
279
-        });
280
-    }
281
-
282
-    /**
283
-     * @return string|void
284
-     */
285
-    protected function buildFormTextarea()
286
-    {
287
-        return $this->buildFormLabel().$this->buildDefaultTag($this->args['value']);
288
-    }
289
-
290
-    /**
291
-     * @return string|void
292
-     */
293
-    protected function buildTag()
294
-    {
295
-        $this->mergeArgsWithRequiredDefaults();
296
-        return $this->getTag();
297
-    }
298
-
299
-    /**
300
-     * @return string
301
-     */
302
-    protected function getCustomFieldClassName()
303
-    {
304
-        $classname = Helper::buildClassName($this->tag, __NAMESPACE__.'\Fields');
305
-        return apply_filters('site-reviews/builder/field/'.$this->tag, $classname);
306
-    }
307
-
308
-    /**
309
-     * @return void
310
-     */
311
-    protected function mergeArgsWithRequiredDefaults()
312
-    {
313
-        $className = $this->getCustomFieldClassName();
314
-        if (class_exists($className)) {
315
-            $this->args = $className::merge($this->args);
316
-        }
317
-        $this->args = glsr(BuilderDefaults::class)->merge($this->args);
318
-    }
319
-
320
-    /**
321
-     * @param string|array ...$params
322
-     * @return void
323
-     */
324
-    protected function normalize(...$params)
325
-    {
326
-        if (is_string($params[0]) || is_numeric($params[0])) {
327
-            $this->setNameOrTextAttributeForTag($params[0]);
328
-        }
329
-        if (is_array($params[0])) {
330
-            $this->args += $params[0];
331
-        } elseif (is_array($params[1])) {
332
-            $this->args += $params[1];
333
-        }
334
-        if (!isset($this->args['is_public'])) {
335
-            $this->args['is_public'] = false;
336
-        }
337
-    }
338
-
339
-    /**
340
-     * @param string $value
341
-     * @return void
342
-     */
343
-    protected function setNameOrTextAttributeForTag($value)
344
-    {
345
-        $attribute = in_array($this->tag, static::TAGS_FORM)
346
-            ? 'name'
347
-            : 'text';
348
-        $this->args[$attribute] = $value;
349
-    }
350
-
351
-    /**
352
-     * @param string $method
353
-     * @return void
354
-     */
355
-    protected function setTagFromMethod($method)
356
-    {
357
-        $this->tag = strtolower($method);
358
-        if (in_array($this->tag, static::INPUT_TYPES)) {
359
-            $this->args['type'] = $this->tag;
360
-            $this->tag = 'input';
361
-        }
362
-    }
21
+	const INPUT_TYPES = [
22
+		'checkbox', 'date', 'datetime-local', 'email', 'file', 'hidden', 'image', 'month',
23
+		'number', 'password', 'radio', 'range', 'reset', 'search', 'submit', 'tel', 'text', 'time',
24
+		'url', 'week',
25
+	];
26
+
27
+	const TAGS_FORM = [
28
+		'input', 'select', 'textarea',
29
+	];
30
+
31
+	const TAGS_SINGLE = [
32
+		'img',
33
+	];
34
+
35
+	const TAGS_STRUCTURE = [
36
+		'div', 'form', 'nav', 'ol', 'section', 'ul',
37
+	];
38
+
39
+	const TAGS_TEXT = [
40
+		'a', 'button', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'i', 'label', 'li', 'option', 'p', 'pre',
41
+		'small', 'span',
42
+	];
43
+
44
+	/**
45
+	 * @var array
46
+	 */
47
+	public $args = [];
48
+
49
+	/**
50
+	 * @var bool
51
+	 */
52
+	public $render = false;
53
+
54
+	/**
55
+	 * @var string
56
+	 */
57
+	public $tag;
58
+
59
+	/**
60
+	 * @param string $method
61
+	 * @param array $args
62
+	 * @return string|void
63
+	 */
64
+	public function __call($method, $args)
65
+	{
66
+		$instance = new static();
67
+		$instance->setTagFromMethod($method);
68
+		call_user_func_array([$instance, 'normalize'], $args += ['', '']);
69
+		$tags = array_merge(static::TAGS_FORM, static::TAGS_SINGLE, static::TAGS_STRUCTURE, static::TAGS_TEXT);
70
+		do_action_ref_array('site-reviews/builder', [$instance]);
71
+		$generatedTag = in_array($instance->tag, $tags)
72
+			? $instance->buildTag()
73
+			: $instance->buildCustomField();
74
+		$generatedTag = apply_filters('site-reviews/builder/result', $generatedTag, $instance);
75
+		if (!$this->render) {
76
+			return $generatedTag;
77
+		}
78
+		echo $generatedTag;
79
+	}
80
+
81
+	/**
82
+	 * @param string $property
83
+	 * @param mixed $value
84
+	 * @return void
85
+	 */
86
+	public function __set($property, $value)
87
+	{
88
+		$properties = [
89
+			'args' => 'is_array',
90
+			'render' => 'is_bool',
91
+			'tag' => 'is_string',
92
+		];
93
+		if (!isset($properties[$property])
94
+			|| empty(array_filter([$value], $properties[$property]))
95
+		) {
96
+			return;
97
+		}
98
+		$this->$property = $value;
99
+	}
100
+
101
+	/**
102
+	 * @return void|string
103
+	 */
104
+	public function getClosingTag()
105
+	{
106
+		if (empty($this->tag)) {
107
+			return;
108
+		}
109
+		return '</'.$this->tag.'>';
110
+	}
111
+
112
+	/**
113
+	 * @return void|string
114
+	 */
115
+	public function getOpeningTag()
116
+	{
117
+		if (empty($this->tag)) {
118
+			return;
119
+		}
120
+		$attributes = glsr(Attributes::class)->{$this->tag}($this->args)->toString();
121
+		return '<'.trim($this->tag.' '.$attributes).'>';
122
+	}
123
+
124
+	/**
125
+	 * @return void|string
126
+	 */
127
+	public function getTag()
128
+	{
129
+		if (in_array($this->tag, static::TAGS_SINGLE)) {
130
+			return $this->getOpeningTag();
131
+		}
132
+		if (!in_array($this->tag, static::TAGS_FORM)) {
133
+			return $this->buildDefaultTag();
134
+		}
135
+		return call_user_func([$this, 'buildForm'.ucfirst($this->tag)]).$this->buildFieldDescription();
136
+	}
137
+
138
+	/**
139
+	 * @return string
140
+	 */
141
+	public function raw(array $field)
142
+	{
143
+		unset($field['label']);
144
+		return $this->{$field['type']}($field);
145
+	}
146
+
147
+	/**
148
+	 * @return string|void
149
+	 */
150
+	protected function buildCustomField()
151
+	{
152
+		$className = $this->getCustomFieldClassName();
153
+		if (class_exists($className)) {
154
+			return (new $className($this))->build();
155
+		}
156
+		glsr_log()->error('Field missing: '.$className);
157
+	}
158
+
159
+	/**
160
+	 * @return string|void
161
+	 */
162
+	protected function buildDefaultTag($text = '')
163
+	{
164
+		if (empty($text)) {
165
+			$text = $this->args['text'];
166
+		}
167
+		return $this->getOpeningTag().$text.$this->getClosingTag();
168
+	}
169
+
170
+	/**
171
+	 * @return string|void
172
+	 */
173
+	protected function buildFieldDescription()
174
+	{
175
+		if (empty($this->args['description'])) {
176
+			return;
177
+		}
178
+		if ($this->args['is_widget']) {
179
+			return $this->small($this->args['description']);
180
+		}
181
+		return $this->p($this->args['description'], ['class' => 'description']);
182
+	}
183
+
184
+	/**
185
+	 * @return string|void
186
+	 */
187
+	protected function buildFormInput()
188
+	{
189
+		if (!in_array($this->args['type'], ['checkbox', 'radio'])) {
190
+			if (isset($this->args['multiple'])) {
191
+				$this->args['name'].= '[]';
192
+			}
193
+			return $this->buildFormLabel().$this->getOpeningTag();
194
+		}
195
+		return empty($this->args['options'])
196
+			? $this->buildFormInputChoice()
197
+			: $this->buildFormInputMultiChoice();
198
+	}
199
+
200
+	/**
201
+	 * @return string|void
202
+	 */
203
+	protected function buildFormInputChoice()
204
+	{
205
+		if (!empty($this->args['text'])) {
206
+			$this->args['label'] = $this->args['text'];
207
+		}
208
+		if (!$this->args['is_public']) {
209
+			return $this->buildFormLabel([
210
+				'class' => 'glsr-'.$this->args['type'].'-label',
211
+				'text' => $this->getOpeningTag().' '.$this->args['label'].'<span></span>',
212
+			]);
213
+		}
214
+		return $this->getOpeningTag().$this->buildFormLabel([
215
+			'class' => 'glsr-'.$this->args['type'].'-label',
216
+			'text' => $this->args['label'].'<span></span>',
217
+		]);
218
+	}
219
+
220
+	/**
221
+	 * @return string|void
222
+	 */
223
+	protected function buildFormInputMultiChoice()
224
+	{
225
+		if ('checkbox' == $this->args['type']) {
226
+			$this->args['name'].= '[]';
227
+		}
228
+		$index = 0;
229
+		$options = array_reduce(array_keys($this->args['options']), function ($carry, $key) use (&$index) {
230
+			return $carry.$this->li($this->{$this->args['type']}([
231
+				'checked' => in_array($key, (array) $this->args['value']),
232
+				'id' => $this->args['id'].'-'.$index++,
233
+				'name' => $this->args['name'],
234
+				'text' => $this->args['options'][$key],
235
+				'value' => $key,
236
+			]));
237
+		});
238
+		return $this->ul($options, [
239
+			'class' => $this->args['class'],
240
+			'id' => $this->args['id'],
241
+		]);
242
+	}
243
+
244
+	/**
245
+	 * @return void|string
246
+	 */
247
+	protected function buildFormLabel(array $customArgs = [])
248
+	{
249
+		if (empty($this->args['label']) || 'hidden' == $this->args['type']) {
250
+			return;
251
+		}
252
+		return $this->label(wp_parse_args($customArgs, [
253
+			'for' => $this->args['id'],
254
+			'is_public' => $this->args['is_public'],
255
+			'text' => $this->args['label'],
256
+			'type' => $this->args['type'],
257
+		]));
258
+	}
259
+
260
+	/**
261
+	 * @return string|void
262
+	 */
263
+	protected function buildFormSelect()
264
+	{
265
+		return $this->buildFormLabel().$this->buildDefaultTag($this->buildFormSelectOptions());
266
+	}
267
+
268
+	/**
269
+	 * @return string|void
270
+	 */
271
+	protected function buildFormSelectOptions()
272
+	{
273
+		return array_reduce(array_keys($this->args['options']), function ($carry, $key) {
274
+			return $carry.$this->option([
275
+				'selected' => $this->args['value'] === (string) $key,
276
+				'text' => $this->args['options'][$key],
277
+				'value' => $key,
278
+			]);
279
+		});
280
+	}
281
+
282
+	/**
283
+	 * @return string|void
284
+	 */
285
+	protected function buildFormTextarea()
286
+	{
287
+		return $this->buildFormLabel().$this->buildDefaultTag($this->args['value']);
288
+	}
289
+
290
+	/**
291
+	 * @return string|void
292
+	 */
293
+	protected function buildTag()
294
+	{
295
+		$this->mergeArgsWithRequiredDefaults();
296
+		return $this->getTag();
297
+	}
298
+
299
+	/**
300
+	 * @return string
301
+	 */
302
+	protected function getCustomFieldClassName()
303
+	{
304
+		$classname = Helper::buildClassName($this->tag, __NAMESPACE__.'\Fields');
305
+		return apply_filters('site-reviews/builder/field/'.$this->tag, $classname);
306
+	}
307
+
308
+	/**
309
+	 * @return void
310
+	 */
311
+	protected function mergeArgsWithRequiredDefaults()
312
+	{
313
+		$className = $this->getCustomFieldClassName();
314
+		if (class_exists($className)) {
315
+			$this->args = $className::merge($this->args);
316
+		}
317
+		$this->args = glsr(BuilderDefaults::class)->merge($this->args);
318
+	}
319
+
320
+	/**
321
+	 * @param string|array ...$params
322
+	 * @return void
323
+	 */
324
+	protected function normalize(...$params)
325
+	{
326
+		if (is_string($params[0]) || is_numeric($params[0])) {
327
+			$this->setNameOrTextAttributeForTag($params[0]);
328
+		}
329
+		if (is_array($params[0])) {
330
+			$this->args += $params[0];
331
+		} elseif (is_array($params[1])) {
332
+			$this->args += $params[1];
333
+		}
334
+		if (!isset($this->args['is_public'])) {
335
+			$this->args['is_public'] = false;
336
+		}
337
+	}
338
+
339
+	/**
340
+	 * @param string $value
341
+	 * @return void
342
+	 */
343
+	protected function setNameOrTextAttributeForTag($value)
344
+	{
345
+		$attribute = in_array($this->tag, static::TAGS_FORM)
346
+			? 'name'
347
+			: 'text';
348
+		$this->args[$attribute] = $value;
349
+	}
350
+
351
+	/**
352
+	 * @param string $method
353
+	 * @return void
354
+	 */
355
+	protected function setTagFromMethod($method)
356
+	{
357
+		$this->tag = strtolower($method);
358
+		if (in_array($this->tag, static::INPUT_TYPES)) {
359
+			$this->args['type'] = $this->tag;
360
+			$this->tag = 'input';
361
+		}
362
+	}
363 363
 }
Please login to merge, or discard this patch.
plugin/Database/SqlQueries.php 1 patch
Indentation   +106 added lines, -106 removed lines patch added patch discarded remove patch
@@ -8,23 +8,23 @@  discard block
 block discarded – undo
8 8
 
9 9
 class SqlQueries
10 10
 {
11
-    protected $db;
12
-    protected $postType;
11
+	protected $db;
12
+	protected $postType;
13 13
 
14
-    public function __construct()
15
-    {
16
-        global $wpdb;
17
-        $this->db = $wpdb;
18
-        $this->postType = Application::POST_TYPE;
19
-    }
14
+	public function __construct()
15
+	{
16
+		global $wpdb;
17
+		$this->db = $wpdb;
18
+		$this->postType = Application::POST_TYPE;
19
+	}
20 20
 
21
-    /**
22
-     * @param string $metaReviewId
23
-     * @return int
24
-     */
25
-    public function getPostIdFromReviewId($metaReviewId)
26
-    {
27
-        $postId = $this->db->get_var("
21
+	/**
22
+	 * @param string $metaReviewId
23
+	 * @return int
24
+	 */
25
+	public function getPostIdFromReviewId($metaReviewId)
26
+	{
27
+		$postId = $this->db->get_var("
28 28
             SELECT p.ID
29 29
             FROM {$this->db->posts} AS p
30 30
             INNER JOIN {$this->db->postmeta} AS m ON p.ID = m.post_id
@@ -32,17 +32,17 @@  discard block
 block discarded – undo
32 32
             AND m.meta_key = '_review_id'
33 33
             AND m.meta_value = '{$metaReviewId}'
34 34
         ");
35
-        return intval($postId);
36
-    }
35
+		return intval($postId);
36
+	}
37 37
 
38
-    /**
39
-     * @param int $lastPostId
40
-     * @param int $limit
41
-     * @return array
42
-     */
43
-    public function getReviewCounts(array $args, $lastPostId = 0, $limit = 500)
44
-    {
45
-        return (array) $this->db->get_results("
38
+	/**
39
+	 * @param int $lastPostId
40
+	 * @param int $limit
41
+	 * @return array
42
+	 */
43
+	public function getReviewCounts(array $args, $lastPostId = 0, $limit = 500)
44
+	{
45
+		return (array) $this->db->get_results("
46 46
             SELECT DISTINCT p.ID, m1.meta_value AS rating, m2.meta_value AS type
47 47
             FROM {$this->db->posts} AS p
48 48
             INNER JOIN {$this->db->postmeta} AS m1 ON p.ID = m1.post_id
@@ -57,17 +57,17 @@  discard block
 block discarded – undo
57 57
             ORDER By p.ID ASC
58 58
             LIMIT {$limit}
59 59
         ");
60
-    }
60
+	}
61 61
 
62
-    /**
63
-     * @todo remove this?
64
-     * @param string $metaKey
65
-     * @return array
66
-     */
67
-    public function getReviewCountsFor($metaKey)
68
-    {
69
-        $metaKey = Str::prefix('_', $metaKey);
70
-        return (array) $this->db->get_results("
62
+	/**
63
+	 * @todo remove this?
64
+	 * @param string $metaKey
65
+	 * @return array
66
+	 */
67
+	public function getReviewCountsFor($metaKey)
68
+	{
69
+		$metaKey = Str::prefix('_', $metaKey);
70
+		return (array) $this->db->get_results("
71 71
             SELECT DISTINCT m.meta_value AS name, COUNT(*) num_posts
72 72
             FROM {$this->db->posts} AS p
73 73
             INNER JOIN {$this->db->postmeta} AS m ON p.ID = m.post_id
@@ -75,16 +75,16 @@  discard block
 block discarded – undo
75 75
             AND m.meta_key = '{$metaKey}'
76 76
             GROUP BY name
77 77
         ");
78
-    }
78
+	}
79 79
 
80
-    /**
81
-     * @todo remove this?
82
-     * @param string $reviewType
83
-     * @return array
84
-     */
85
-    public function getReviewIdsByType($reviewType)
86
-    {
87
-        $results = $this->db->get_col("
80
+	/**
81
+	 * @todo remove this?
82
+	 * @param string $reviewType
83
+	 * @return array
84
+	 */
85
+	public function getReviewIdsByType($reviewType)
86
+	{
87
+		$results = $this->db->get_col("
88 88
             SELECT DISTINCT m1.meta_value AS review_id
89 89
             FROM {$this->db->posts} AS p
90 90
             INNER JOIN {$this->db->postmeta} AS m1 ON p.ID = m1.post_id
@@ -94,20 +94,20 @@  discard block
 block discarded – undo
94 94
             AND m2.meta_key = '_review_type'
95 95
             AND m2.meta_value = '{$reviewType}'
96 96
         ");
97
-        return array_keys(array_flip($results));
98
-    }
97
+		return array_keys(array_flip($results));
98
+	}
99 99
 
100
-    /**
101
-     * @param int $greaterThanId
102
-     * @param int $limit
103
-     * @return array
104
-     */
105
-    public function getReviewRatingsFromIds(array $postIds, $greaterThanId = 0, $limit = 100)
106
-    {
107
-        sort($postIds);
108
-        $postIds = array_slice($postIds, intval(array_search($greaterThanId, $postIds)), $limit);
109
-        $postIds = implode(',', $postIds);
110
-        return (array) $this->db->get_results("
100
+	/**
101
+	 * @param int $greaterThanId
102
+	 * @param int $limit
103
+	 * @return array
104
+	 */
105
+	public function getReviewRatingsFromIds(array $postIds, $greaterThanId = 0, $limit = 100)
106
+	{
107
+		sort($postIds);
108
+		$postIds = array_slice($postIds, intval(array_search($greaterThanId, $postIds)), $limit);
109
+		$postIds = implode(',', $postIds);
110
+		return (array) $this->db->get_results("
111 111
             SELECT p.ID, m.meta_value AS rating
112 112
             FROM {$this->db->posts} AS p
113 113
             INNER JOIN {$this->db->postmeta} AS m ON p.ID = m.post_id
@@ -120,20 +120,20 @@  discard block
 block discarded – undo
120 120
             ORDER By p.ID ASC
121 121
             LIMIT {$limit}
122 122
         ");
123
-    }
123
+	}
124 124
 
125
-    /**
126
-     * @param string $key
127
-     * @param string $status
128
-     * @return array
129
-     */
130
-    public function getReviewsMeta($key, $status = 'publish')
131
-    {
132
-        $postStatusQuery = 'all' != $status && !empty($status)
133
-            ? "AND p.post_status = '{$status}'"
134
-            : '';
135
-        $key = Str::prefix('_', $key);
136
-        $values = $this->db->get_col("
125
+	/**
126
+	 * @param string $key
127
+	 * @param string $status
128
+	 * @return array
129
+	 */
130
+	public function getReviewsMeta($key, $status = 'publish')
131
+	{
132
+		$postStatusQuery = 'all' != $status && !empty($status)
133
+			? "AND p.post_status = '{$status}'"
134
+			: '';
135
+		$key = Str::prefix('_', $key);
136
+		$values = $this->db->get_col("
137 137
             SELECT DISTINCT m.meta_value
138 138
             FROM {$this->db->postmeta} m
139 139
             LEFT JOIN {$this->db->posts} p ON p.ID = m.post_id
@@ -144,42 +144,42 @@  discard block
 block discarded – undo
144 144
             GROUP BY p.ID -- remove duplicate meta_value entries
145 145
             ORDER BY m.meta_id ASC -- sort by oldest meta_value
146 146
         ");
147
-        sort($values);
148
-        return $values;
149
-    }
147
+		sort($values);
148
+		return $values;
149
+	}
150 150
 
151
-    /**
152
-     * @param string $and
153
-     * @return string
154
-     */
155
-    protected function getAndForCounts(array $args, $and = '')
156
-    {
157
-        $postIds = implode(',', array_filter(Arr::get($args, 'post_ids', [])));
158
-        $termIds = implode(',', array_filter(Arr::get($args, 'term_ids', [])));
159
-        if (!empty($args['type'])) {
160
-            $and.= "AND m2.meta_value = '{$args['type']}' ";
161
-        }
162
-        if ($postIds) {
163
-            $and.= "AND m3.meta_key = '_assigned_to' AND m3.meta_value IN ({$postIds}) ";
164
-        }
165
-        if ($termIds) {
166
-            $and.= "AND tr.term_taxonomy_id IN ({$termIds}) ";
167
-        }
168
-        return apply_filters('site-reviews/query/and-for-counts', $and);
169
-    }
151
+	/**
152
+	 * @param string $and
153
+	 * @return string
154
+	 */
155
+	protected function getAndForCounts(array $args, $and = '')
156
+	{
157
+		$postIds = implode(',', array_filter(Arr::get($args, 'post_ids', [])));
158
+		$termIds = implode(',', array_filter(Arr::get($args, 'term_ids', [])));
159
+		if (!empty($args['type'])) {
160
+			$and.= "AND m2.meta_value = '{$args['type']}' ";
161
+		}
162
+		if ($postIds) {
163
+			$and.= "AND m3.meta_key = '_assigned_to' AND m3.meta_value IN ({$postIds}) ";
164
+		}
165
+		if ($termIds) {
166
+			$and.= "AND tr.term_taxonomy_id IN ({$termIds}) ";
167
+		}
168
+		return apply_filters('site-reviews/query/and-for-counts', $and);
169
+	}
170 170
 
171
-    /**
172
-     * @param string $innerJoin
173
-     * @return string
174
-     */
175
-    protected function getInnerJoinForCounts(array $args, $innerJoin = '')
176
-    {
177
-        if (!empty(Arr::get($args, 'post_ids'))) {
178
-            $innerJoin.= "INNER JOIN {$this->db->postmeta} AS m3 ON p.ID = m3.post_id ";
179
-        }
180
-        if (!empty(Arr::get($args, 'term_ids'))) {
181
-            $innerJoin.= "INNER JOIN {$this->db->term_relationships} AS tr ON p.ID = tr.object_id ";
182
-        }
183
-        return apply_filters('site-reviews/query/inner-join-for-counts', $innerJoin);
184
-    }
171
+	/**
172
+	 * @param string $innerJoin
173
+	 * @return string
174
+	 */
175
+	protected function getInnerJoinForCounts(array $args, $innerJoin = '')
176
+	{
177
+		if (!empty(Arr::get($args, 'post_ids'))) {
178
+			$innerJoin.= "INNER JOIN {$this->db->postmeta} AS m3 ON p.ID = m3.post_id ";
179
+		}
180
+		if (!empty(Arr::get($args, 'term_ids'))) {
181
+			$innerJoin.= "INNER JOIN {$this->db->term_relationships} AS tr ON p.ID = tr.object_id ";
182
+		}
183
+		return apply_filters('site-reviews/query/inner-join-for-counts', $innerJoin);
184
+	}
185 185
 }
Please login to merge, or discard this patch.
plugin/Controllers/BlocksController.php 1 patch
Indentation   +78 added lines, -78 removed lines patch added patch discarded remove patch
@@ -8,86 +8,86 @@
 block discarded – undo
8 8
 
9 9
 class BlocksController extends Controller
10 10
 {
11
-    /**
12
-     * @param array $categories
13
-     * @return array
14
-     * @filter block_categories
15
-     */
16
-    public function filterBlockCategories($categories)
17
-    {
18
-        $categories = Arr::consolidateArray($categories);
19
-        $categories[] = [
20
-            'icon' => null,
21
-            'slug' => Application::ID,
22
-            'title' => glsr()->name,
23
-        ];
24
-        return $categories;
25
-    }
11
+	/**
12
+	 * @param array $categories
13
+	 * @return array
14
+	 * @filter block_categories
15
+	 */
16
+	public function filterBlockCategories($categories)
17
+	{
18
+		$categories = Arr::consolidateArray($categories);
19
+		$categories[] = [
20
+			'icon' => null,
21
+			'slug' => Application::ID,
22
+			'title' => glsr()->name,
23
+		];
24
+		return $categories;
25
+	}
26 26
 
27
-    /**
28
-     * @param array $editors
29
-     * @param string $postType
30
-     * @return array
31
-     * @filter classic_editor_enabled_editors_for_post_type
32
-     * @plugin classic-editor/classic-editor.php
33
-     */
34
-    public function filterEnabledEditors($editors, $postType)
35
-    {
36
-        return Application::POST_TYPE == $postType
37
-            ? ['block_editor' => false, 'classic_editor' => false]
38
-            : $editors;
39
-    }
27
+	/**
28
+	 * @param array $editors
29
+	 * @param string $postType
30
+	 * @return array
31
+	 * @filter classic_editor_enabled_editors_for_post_type
32
+	 * @plugin classic-editor/classic-editor.php
33
+	 */
34
+	public function filterEnabledEditors($editors, $postType)
35
+	{
36
+		return Application::POST_TYPE == $postType
37
+			? ['block_editor' => false, 'classic_editor' => false]
38
+			: $editors;
39
+	}
40 40
 
41
-    /**
42
-     * @param bool $bool
43
-     * @param string $postType
44
-     * @return bool
45
-     * @filter use_block_editor_for_post_type
46
-     */
47
-    public function filterUseBlockEditor($bool, $postType)
48
-    {
49
-        return Application::POST_TYPE == $postType
50
-            ? false
51
-            : $bool;
52
-    }
41
+	/**
42
+	 * @param bool $bool
43
+	 * @param string $postType
44
+	 * @return bool
45
+	 * @filter use_block_editor_for_post_type
46
+	 */
47
+	public function filterUseBlockEditor($bool, $postType)
48
+	{
49
+		return Application::POST_TYPE == $postType
50
+			? false
51
+			: $bool;
52
+	}
53 53
 
54
-    /**
55
-     * @return void
56
-     * @action init
57
-     */
58
-    public function registerAssets()
59
-    {
60
-        wp_register_style(
61
-            Application::ID.'/blocks',
62
-            glsr()->url('assets/styles/'.Application::ID.'-blocks.css'),
63
-            ['wp-edit-blocks'],
64
-            glsr()->version
65
-        );
66
-        wp_register_script(
67
-            Application::ID.'/blocks',
68
-            glsr()->url('assets/scripts/'.Application::ID.'-blocks.js'),
69
-            ['wp-api-fetch', 'wp-blocks', 'wp-i18n', 'wp-editor', 'wp-element', Application::ID],
70
-            glsr()->version
71
-        );
72
-    }
54
+	/**
55
+	 * @return void
56
+	 * @action init
57
+	 */
58
+	public function registerAssets()
59
+	{
60
+		wp_register_style(
61
+			Application::ID.'/blocks',
62
+			glsr()->url('assets/styles/'.Application::ID.'-blocks.css'),
63
+			['wp-edit-blocks'],
64
+			glsr()->version
65
+		);
66
+		wp_register_script(
67
+			Application::ID.'/blocks',
68
+			glsr()->url('assets/scripts/'.Application::ID.'-blocks.js'),
69
+			['wp-api-fetch', 'wp-blocks', 'wp-i18n', 'wp-editor', 'wp-element', Application::ID],
70
+			glsr()->version
71
+		);
72
+	}
73 73
 
74
-    /**
75
-     * @return void
76
-     * @action init
77
-     */
78
-    public function registerBlocks()
79
-    {
80
-        $blocks = [
81
-            'form', 'reviews', 'summary',
82
-        ];
83
-        foreach ($blocks as $block) {
84
-            $id = str_replace('_reviews', '', Application::ID.'_'.$block);
85
-            $blockClass = Helper::buildClassName($id.'-block', 'Blocks');
86
-            if (!class_exists($blockClass)) {
87
-                glsr_log()->error(sprintf('Class missing (%s)', $blockClass));
88
-                continue;
89
-            }
90
-            glsr($blockClass)->register($block);
91
-        }
92
-    }
74
+	/**
75
+	 * @return void
76
+	 * @action init
77
+	 */
78
+	public function registerBlocks()
79
+	{
80
+		$blocks = [
81
+			'form', 'reviews', 'summary',
82
+		];
83
+		foreach ($blocks as $block) {
84
+			$id = str_replace('_reviews', '', Application::ID.'_'.$block);
85
+			$blockClass = Helper::buildClassName($id.'-block', 'Blocks');
86
+			if (!class_exists($blockClass)) {
87
+				glsr_log()->error(sprintf('Class missing (%s)', $blockClass));
88
+				continue;
89
+			}
90
+			glsr($blockClass)->register($block);
91
+		}
92
+	}
93 93
 }
Please login to merge, or discard this patch.