1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
/** |
3
|
|
|
* PHP: Nelson Martell Library file |
4
|
|
|
* |
5
|
|
|
* Copyright © 2019 Nelson Martell (http://nelson6e65.github.io) |
6
|
|
|
* |
7
|
|
|
* Licensed under The MIT License (MIT) |
8
|
|
|
* For full copyright and license information, please see the LICENSE |
9
|
|
|
* Redistributions of files must retain the above copyright notice. |
10
|
|
|
* |
11
|
|
|
* @copyright 2019 Nelson Martell |
12
|
|
|
* @link http://nelson6e65.github.io/php_nml/ |
13
|
|
|
* @since 1.0.0 |
14
|
|
|
* @license http://www.opensource.org/licenses/mit-license.php The MIT License (MIT) |
15
|
|
|
* */ |
16
|
|
|
namespace NelsonMartell\Extensions; |
17
|
|
|
|
18
|
|
|
use InvalidArgumentException; |
19
|
|
|
|
20
|
|
|
use NelsonMartell\IComparer; |
21
|
|
|
use NelsonMartell\StrictObject; |
22
|
|
|
|
23
|
|
|
use function NelsonMartell\msg; |
24
|
|
|
use function NelsonMartell\typeof; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Provides extension methods to handle class properties. |
28
|
|
|
* |
29
|
|
|
* @since 1.0.0 |
30
|
|
|
* @author Nelson Martell <[email protected]> |
31
|
|
|
* */ |
32
|
|
|
class PropertyExtension |
33
|
|
|
{ |
34
|
|
|
/** |
35
|
|
|
* Ensures that a string is a valid property name. |
36
|
|
|
* |
37
|
|
|
* @param string $name Property name to be ensured. |
38
|
|
|
* |
39
|
|
|
* @return string |
40
|
|
|
* @throws InvalidArgumentException if name do not follows the PHP variables naming convention. |
41
|
|
|
* |
42
|
|
|
* @see Text::ensureIsValidVarName() |
43
|
|
|
*/ |
44
|
181 |
|
public static function ensureIsValidName(string $name) : string |
45
|
|
|
{ |
46
|
|
|
try { |
47
|
181 |
|
return Text::ensureIsValidVarName($name); |
48
|
|
|
} catch (InvalidArgumentException $e) { |
49
|
|
|
$msg = msg('"{0}" is not a valid property name.', $name); |
50
|
|
|
throw new InvalidArgumentException($msg, 10, $e); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Ensures that the property is defined in the specified class. |
56
|
|
|
* |
57
|
|
|
* @param string $property |
58
|
|
|
* @param string $class |
59
|
|
|
* |
60
|
|
|
* @return string |
61
|
|
|
* |
62
|
|
|
* @throws InvalidArgumentException if `$property` is not valid, `$class` do not exists or `$class` has not the |
63
|
|
|
* property. |
64
|
|
|
* |
65
|
|
|
* @see PropertyExtension::ensureIsValidName() |
66
|
|
|
*/ |
67
|
181 |
|
public static function ensureIsDefined(string $property, string $class) : string |
68
|
|
|
{ |
69
|
181 |
|
$type = typeof($class, true); |
70
|
|
|
|
71
|
181 |
|
if (!$type->hasProperty(static::ensureIsValidName($property))) { |
72
|
24 |
|
$msg = msg( |
73
|
24 |
|
'"{property}" property do not exists in "{class}" class or parent classes.', |
74
|
24 |
|
compact('property', 'class') |
75
|
|
|
); |
76
|
|
|
|
77
|
24 |
|
throw new InvalidArgumentException($msg, 11); |
78
|
|
|
} |
79
|
|
|
|
80
|
157 |
|
return $property; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|