Passed
Push — steve-cms-pages ( d6d222...393d30 )
by steve
20:40
created

id()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 1
c 1
b 0
f 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 1
cp 0
crap 2
rs 10
1
<?php
2
/**
3
 * @link http://www.newicon.net/neon
4
 * @copyright Copyright (c) 2016 Newicon Ltd
5
 * @license http://www.newicon.net/neon/license/
6
 * @author Steve O'Brien <[email protected]> 13/11/2016 17:38
7
 * @package neon
8
 */
9
10
/**
11
 * This file is autoloaded via the composer autoload_file.php
12
 */
13
use \neon\core\helpers\Str;
14
use \neon\core\helpers\Collection;
15
use \neon\core\helpers\Arr;
16
use \neon\core\Env;
17
use \Carbon\Carbon;
18
use neon\core\helpers\Url;
19
20
if (! function_exists('dp')) {
21
	/**
22
	 * Debug function. Prints all passed in arguments to the screen.
23
	 * arguments containing objects or arrays are output using print_r
24
	 * arguments containing simple types are output using var_export.
25
	 * **Note:** Strings will be shown in single quotes.
26
	 * **Note:** boolean's will be output as string true | false
27
	 * **Note:** if not in debug mode, will print to the error log
28
	 * @param mixed
29
	 * @return void
30
	 */
31
	function dp(...$dump)
32
	{
33
		echo dp_string(...$dump);
34
		$backtrace = backtrace_line_by_function('dp');
35
		if (neon()->debug)
0 ignored issues
show
Bug Best Practice introduced by
The property debug does not exist on neon\core\ApplicationWeb. Since you implemented __get, consider adding a @property annotation.
Loading history...
36
			echo $backtrace;
37
		else
38
			\Neon::error($backtrace);
39
	}
40
}
41
42
if (! function_exists('backtrace_line_by_function')) {
43
	/**
44
	 * Tries to get the line and file that called the specified functions
45
	 * - will return the earliest match in execution order that it found.
46
	 * @see dp()
47
	 * @param string $functionToShow function name to find
48
	 * @return string
49
	 */
50
	function backtrace_line_by_function($functionToShow = 'dp')
51
	{
52
		$bt = debug_backtrace();
53
		$lineInfo = '';
54
		foreach($bt as $trace) {
55
			if (isset($trace['function']) && $trace['function'] === $functionToShow) {
56
				$lineInfo = '==> [' . (isset($trace['file']) ? $trace['file'] : ' unknown file '). ':' . (isset($trace['line']) ? $trace['line'] : ' unknown line ' ) . ']';
57
				break;
58
			}
59
		}
60
		return $lineInfo;
61
	}
62
}
63
64
if (! function_exists('dp_string')) {
65
	/**
66
	 * This generates a nice debug string and returns it. It will only
67
	 * print to the screen if you are in debug mode. Otherwise it prints
68
	 * to Neon::error log.
69
	 * @see dp()
70
	 * @param mixed $dump
71
	 * @return string
72
	 */
73
	function dp_string(...$dump)
74
	{
75
		if (php_sapi_name() == 'cli') {
76
			// use symfony dump function
77
			dump(...$dump);
78
			return;
79
		}
80
		// only allow printing of debug data to the screen if in debug mode
81
		$arguments = func_get_args();
82
		$str = '';
83
		foreach ($arguments as $arg) {
84
			$debug = (is_object($arg) || is_array($arg))
85
				? print_r($arg, true) : var_export($arg, true);
86
			$str .= "<pre>$debug</pre>";
87
		}
88
89
		if (neon()->debug)
0 ignored issues
show
Bug Best Practice introduced by
The property debug does not exist on neon\core\ApplicationWeb. Since you implemented __get, consider adding a @property annotation.
Loading history...
90
			return $str;
91
		\Neon::error($str);
92
		return '';
93
	}
94
}
95
96
if (! function_exists('dd')) {
97
	/**
98
	 * This is the same as the dp (debug print) function but exits after
99
	 * **Note:** If not in debug will print to log error and not exit
100
	 * @see dp()
101
	 * @param mixed $dump
102
	 * @return void
103
	 */
104
	function dd(...$dump)
105
	{
106
		echo dp_string(...$dump);
107
		$backtrace = backtrace_line_by_function('dd');
108
		if (neon()->debug) {
0 ignored issues
show
Bug Best Practice introduced by
The property debug does not exist on neon\core\ApplicationWeb. Since you implemented __get, consider adding a @property annotation.
Loading history...
109
			echo $backtrace;
110
			exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
111
		}
112
		\Neon::error($backtrace);
113
	}
114
}
115
116
if (! function_exists('debug_message')) {
117
	/**
118
	 * This is the same as the dp_string (debug print) function however it returns the string
119
	 * The main difference is that it will only output a message if neon is in debug mode
120
	 * Therefore it is safe to leave in the source code on error pages
121
	 * @see dp()
122
	 * @param mixed $dump
123
	 * @return string
124
	 */
125
	function debug_message(...$dump)
126
	{
127
		// security feature to ensure debug is not displayed unless in debug mode
128
		if (!neon()->debug)
0 ignored issues
show
Bug Best Practice introduced by
The property debug does not exist on neon\core\ApplicationWeb. Since you implemented __get, consider adding a @property annotation.
Loading history...
129
			return '';
130
		return dp_string(...$dump);
131
	}
132
}
133
134
135
if (! function_exists('neon')) {
136
	/**
137
	 * Shortcut method to ```\Neon::$app```
138
	 * @param string $name
139
	 * @return \neon\core\ApplicationWeb
140
	 */
141
	function neon($name = null)
142
	{
143 492
		return \Neon::app($name);
144
	}
145
}
146
147
if (! function_exists('setting')) {
148
	/**
149
	 * Get a setting value
150
	 *
151
	 * @param string $app the app responsible for this setting
152
	 * @param string $name the setting name
153
	 * @param mixed $default the default property to return if the setting does not exist
154
	 * @param boolean $refresh to force a refresh - will trigger a reload of the settings - this is only necessary if
155
	 * the setting has been set in the current session
156
	 * @return string
157
	 */
158
	function setting($app, $name, $default=null, $refresh=false)
159
	{
160 2
		return neon()->getSettingsManager()->get($app, $name, $default, $refresh);
161
	}
162
}
163
164
if (! function_exists('set_setting')) {
165
	/**
166
	 * @param string $app the app responsible for this setting
167
	 * @param string $name the setting name
168
	 * @param mixed $value the setting value
169
	 * @return boolean whether successfully saved
170
	 */
171
	function set_setting($app, $name, $value)
172
	{
173
		return neon()->getSettingsManager()->set($app, $name, $value);
174
	}
175
}
176
177
if (! function_exists('url')) {
178
	/**
179
	 * Alias of \neon\core\helpers\Url::to
180
	 * @see \neon\core\helpers\Url::to()
181
	 *
182
	 * @param array|string $url the parameter to be used to generate a valid URL
183
	 * @param boolean|string $absolute the URI scheme to use in the generated URL:
184
	 *
185
	 * - `false` (default): generating a relative URL.
186
	 * - `true`: returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::hostInfo]].
187
	 *
188
	 * @return string the generated URL
189
	 * @throws InvalidParamException a relative route is given while there is no active controller
190
	 */
191
	function url($url = '', $absolute = false)
192
	{
193 2
		if ($url === null)
0 ignored issues
show
introduced by
The condition $url === null is always false.
Loading history...
194
			return '';
195 2
		$url = is_string($url) ? "/$url" : $url;
196 2
		return Url::toRoute($url, $absolute);
197
	}
198
}
199
200
if (! function_exists('url_base')) {
201
	/**
202
	 * Returns the base URL of the current request.
203
	 * @param boolean|string $scheme the URI scheme to use in the returned base URL:
204
	 *
205
	 * - `false`: returning the base URL without host info.
206
	 * - `true` (default): returning an absolute base URL whose scheme is the same as that in [[\yii\web\UrlManager::hostInfo]].
207
	 * - string: returning an absolute base URL with the specified scheme (either `http` or `https`).
208
	 * @return string
209
	 */
210
	function url_base($scheme = true)
211
	{
212
		return \neon\core\helpers\Url::base($scheme);
213
	}
214
}
215
216
if (! function_exists('to_bytes')) {
217
	/**
218
	 * Returns the number of bytes as integer from a strings like `128K` | `128M` | `2G` | `1T` | `1P`
219
	 *
220
	 * @param  string  $string  A bytes string like 128M
221
	 * @return int
222
	 */
223
	function to_bytes($string) {
224 26
		return \neon\core\helpers\Str::toBytes($string);
225
	}
226
}
227
228
if (! function_exists('format_bytes')) {
229
	/**
230
	 * Output a formatted size like '128M' from bytes.
231
	 *
232
	 * @param  int  $size
233
	 * @param  int  $precision
234
	 * @return string
235
	 */
236
	function format_bytes($size, $precision = 2) {
237
		return \neon\core\helpers\Str::formatBytes($size, $precision);
238
	}
239
}
240
241
if (! function_exists('truthy')) {
242
	/**
243
	 * Php if statement handles truthy and falsey string conversions by default e.g. evaluating a '0' string to false
244
	 * however a string of 'false' is evaluated as true. This function resolves that difference. This should be used
245
	 * in caution in places where you are expecting a boolean.
246
	 * @param string $value - the value to test
247
	 * @return boolean
248
	 */
249
	function truthy($value)
250
	{
251 2
		if ($value && strtolower($value) !== "false")
252 2
			return true;
253 2
		return false;
254
	}
255
}
256
257
if (! function_exists('env')) {
258
	/**
259
	 * Gets the value of an environment variable.
260
	 * Interprets 'true', 'false', 'empty' and 'null' strings appropriately
261
	 *
262
	 * @param  string  $key
263
	 * @param  mixed  $default
264
	 * @return mixed
265
	 */
266
	function env($key, $default = null)
267
	{
268 44
		$value = getenv($key);
269
270 44
		if ($value === false) {
271 2
			return $default;
272
		}
273 44
		switch (strtolower($value)) {
274 44
			case 'true': case 'on': case 'yes':
275 6
				return true;
276 38
			case 'false': case 'off': case 'no': case 'none':
277 8
				return false;
278 30
			case 'empty':
279 2
				return '';
280 28
			case 'null':
281 2
				return;
282
		}
283
284 26
		if (strlen($value) > 1 && Str::startsWith($value, '"') && Str::endsWith($value, '"')) {
285 6
			return substr($value, 1, -1);
286
		}
287
288 20
		return $value;
289
	}
290
}
291
292
if (! function_exists('neon_secret')) {
293
	/**
294
	 * Gets the value of NEON_SECRET creating it if missing
295
	 * @return string
296
	 */
297
	function neon_secret() {
298
		return Env::getNeonSecret();
299
	}
300
}
301
302
if (! function_exists('neon_encryption_key')) {
303
	/**
304
	 * Gets the value of NEON_SECRET creating it if missing
305
	 * @return string
306
	 */
307
	function neon_encryption_key() {
308
		return Env::getNeonEncryptionKey();
309
	}
310
}
311
312
if (! function_exists('value')) {
313
	/**
314
	 * Return the value of the given value.
315
	 * If the $value is a Closure, it will first be executed then its result returned
316
	 *
317
	 * @param  mixed  $value
318
	 * @return mixed
319
	 */
320
	function value($value)
321
	{
322 94
		return $value instanceof Closure ? $value() : $value;
323
	}
324
}
325
326
if (! function_exists('collect')) {
327
	/**
328
	 * Create a collection from the given value.
329
	 *
330
	 * @param  mixed  $value
331
	 * @return \neon\core\helpers\Collection
332
	 */
333
	function collect($value = null)
334
	{
335 54
		return new Collection($value);
336
	}
337
}
338
339
if (! function_exists('now')) {
340
	/**
341
	 * Create a new Carbon instance for the current time.
342
	 *
343
	 * @param  \DateTimeZone|string|null $tz
344
	 * @return \Carbon\Carbon
345
	 */
346
	function now($tz = null)
347
	{
348
		return Carbon::now($tz);
349
	}
350
}
351
352
if (! function_exists('profile_begin')) {
353
	/**
354
	 * @param string $name
355
	 */
356
	function profile_begin($name, $category='neon')
357
	{
358 106
		\Neon::beginProfile($name, $category);
359 106
	}
360
}
361
362
if (! function_exists('profile_end')) {
363
	/**
364
	 * @param string $name
365
	 */
366
	function profile_end($name=null, $category='neon')
367
	{
368 106
		\Neon::endProfile($name, $category);
369 106
	}
370
}
371
372
if (! function_exists('encrypt')) {
373
	/**
374
	 * @param string $data
375
	 * @return string - encrypted data
376
	 */
377
	function encrypt($data)
378
	{
379
		return Str::base64UrlEncode(neon()->security->encryptByKey($data, Env::getNeonEncryptionKey()));
380
	}
381
}
382
383
if (! function_exists('decrypt')) {
384
	/**
385
	 * @param string $data
386
	 * @return string - encrypted data
387
	 */
388
	function decrypt($data)
389
	{
390
		return neon()->security->decryptByKey(Str::base64UrlDecode($data), Env::getNeonEncryptionKey());
391
	}
392
}
393
394
if (! function_exists('get_alias')) {
395
	/**
396
	 * @param string $path
397
	 * @return string - resolved path
398
	 */
399
	function get_alias($path)
400
	{
401
		return neon()->getAlias($path);
402
	}
403
}
404
405
if (! function_exists('on_url')) {
406
	/**
407
	 * This function is useful for checking if links should be active,
408
	 *
409
	 * Note: can accept multiple urls - will return true if any one urls matches the current url
410
	 * @example
411
	 * ```php
412
	 * // current url === /two
413
	 * isUrl('/one', '/two');
414
	 * // => true
415
	 * ```
416
	 *
417
	 * @param string|array $urls,... accepts multiple parameters representing urls to check - will return true if any match
418
	 * @return boolean  - whether the request is on the current url
419
	 */
420
	function on_url(...$urls)
421
	{
422
		return \neon\core\helpers\Url::isUrl(...$urls);
423
	}
424
}
425
if (! function_exists('_t')) {
426
	/**
427
	 * Translates a message to the target language
428
	 * This function is a wrapper to the \Neon::t method
429
	 *
430
	 * You can add parameters to a translation message that will be substituted with the corresponding value after
431
	 * translation. The format for this is to use curly brackets around the parameter name as you can see in the following example:
432
	 *
433
	 * ```php
434
	 * $username = 'Neon';
435
	 * echo t('Hello, {username}!', ['username' => $username]);
436
	 * ```
437
	 * Further formatting of message parameters is supported using the [PHP intl extensions](http://www.php.net/manual/en/intro.intl.php)
438
	 * message formatter. See [[\yii\i18n\I18N::translate()]] for more details.
439
	 *
440
	 * @param string $text the message to be translated.
441
	 * @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
442
	 * @param string $category  if provided will save the text to that category. Defaults to 'neon'
443
	 * @return string the translated message.
444
	 */
445
	function _t($text, $params=[], $category='neon')
446
	{
447
		return \Neon::t($category, $text, $params);
448
	}
449
}
450
if (! function_exists('faker')) {
451
	/**
452
	 * Generate a faker object
453
	 * @return \Faker\Generator;
454
	 */
455
	function faker()
456
	{
457 2
		static $faker = null;
458 2
		if ($faker === null)
459 2
			$faker = \Faker\Factory::create();
460 2
		return $faker;
461
	}
462
}
463
if (! function_exists('user_is')) {
464
	/**
465
	 * @return boolean whether the user is/has a particular role
466
	 */
467
	function user_is($role)
468
	{
469
		return neon()->user->is($role);
470
	}
471
}
472
473
if (! function_exists('user_can')) {
474
	/**
475
	 * Whether the user can perform a permission
476
	 * @param $permission
477
	 * @return bool
478
	 */
479
	function user_can($permission)
480
	{
481
		return neon()->user->can($permission);
482
	}
483
}
484
if (! function_exists('uuid')) {
485
	/**
486
	 * Generate a universally unique id
487
	 * @param string $separator - default '-'
488
	 * @return bool
489
	 */
490
	function uuid($separator='-')
491
	{
492
		return \neon\core\helpers\Hash::uuid($separator);
493
	}
494
}
495
if (! function_exists('uuid64')) {
496
	/**
497
	 * Generate a universally unique id in base64
498
	 * @return bool
499
	 */
500
	function uuid64()
501
	{
502
		return \neon\core\helpers\Hash::uuid64();
503
	}
504
}
505
if (! function_exists('id')) {
506
	/**
507
	 * Whether the user can perform a permission
508
	 * @return bool
509
	 */
510
	function id()
511
	{
512
		return \neon\core\helpers\Hash::id();
513
	}
514
}
515
if (! function_exists('is_route')) {
516
	/**
517
	 * Test whether the current application is on a particular route
518
	 * This is url rewrite safe! However you must reference the module/controller/action and not the url directly
519
	 * - sometimes these are very similar but they can all be overriden
520
	 * For e.g. cms routes are on_route('/cms/render/page', ['nice_id'=>'home'])
521
	 *
522
	 * @param string $pattern
523
	 * @param array $params
524
	 * @return boolean - whether on the route
525
	 */
526
	function is_route($pattern, $params=[])
527
	{
528
		return neon()->request->isRoute($pattern, $params);
529
	}
530
}
531
if (! function_exists('abort')) {
532
	/**
533
	 * Throw a HttpException with the given data.
534
	 *
535
	 * @param  int  $code
536
	 * @param  string  $message
537
	 * @return void
538
	 *
539
	 * @throws \yii\web\HttpException
540
	 */
541
	function abort($code, $message = '')
542
	{
543 2
		throw new \yii\web\HttpException($code, $message);
544
	}
545
}
546
547
if (! function_exists('abort_if')) {
548
	/**
549
	 * Throw a HttpException with the given data if the given condition is true.
550
	 *
551
	 * @param  bool  $boolean
552
	 * @param  int  $code
553
	 * @param  string  $message
554
	 * @return void
555
	 *
556
	 * @throws \yii\web\HttpException
557
	 */
558
	function abort_if($boolean, $code, $message = '')
559
	{
560
		if ($boolean) {
561
			abort($code, $message);
562
		}
563
	}
564
}
565
if (! function_exists('request')) {
566
	/**
567
	 * Get an instance of the current request or an input item from the request.
568
	 *
569
	 * @param  array|string|null  $key
570
	 * @param  mixed  $default
571
	 * @return \neon\core\web\Request|string|array
572
	 */
573
	function request($key = null, $default = null)
574
	{
575
		if (is_null($key)) {
576
			return neon()->request;
577
		}
578
579
		$value = neon()->request->get($key);
580
581
		return is_null($value) ? value($default) : $value;
582
	}
583
}
584
if (! function_exists('object_get')) {
585
	/**
586
	 * Get an item from an object using "dot" notation.
587
	 *
588
	 * @param  object  $object
589
	 * @param  string|null  $key
590
	 * @param  mixed  $default
591
	 * @return mixed
592
	 */
593
	function object_get($object, $key, $default = null)
594
	{
595
		if (is_null($key) || trim($key) == '') {
596
			return $object;
597
		}
598
599
		foreach (explode('.', $key) as $segment) {
600
			if (! is_object($object) || ! isset($object->{$segment})) {
601
				return value($default);
602
			}
603
604
			$object = $object->{$segment};
605
		}
606
607
		return $object;
608
	}
609
}
610