1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Created by PhpStorm. |
4
|
|
|
* User: PBX_g33k |
5
|
|
|
* Date: 24-May-16 |
6
|
|
|
* Time: 13:02 |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Pbxg33k\Traits; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class PropertyTrait |
13
|
|
|
* |
14
|
|
|
* This trait adds helpers for getters and setters by automatically trying |
15
|
|
|
* to set properties using various methods while respecting property visibility. |
16
|
|
|
* |
17
|
|
|
* @author Oguzhan uysal <[email protected]> |
18
|
|
|
* @package Pbxg33k\Traits |
19
|
|
|
*/ |
20
|
|
|
trait PropertyTrait |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* Sets the property value for the object |
24
|
|
|
* |
25
|
|
|
* @param string $key |
26
|
|
|
* @param mixed $value |
27
|
|
|
* @param bool $override |
28
|
|
|
* @param bool $isCollection Boolean to indicate Doctrine Collections |
29
|
|
|
* @return Object |
30
|
|
|
* @throws \Exception if setting value has failed |
31
|
|
|
*/ |
32
|
|
|
public function setPropertyValue($key, $value, $override = false, $isCollection = false) |
33
|
|
|
{ |
34
|
|
|
// Replace empty strings with null |
35
|
|
|
$value = ($value === "") ? null : $value; |
36
|
|
|
|
37
|
|
|
// Convert key to method names |
38
|
|
|
$methodName = $this->getMethodName($key); |
39
|
|
|
|
40
|
|
|
if (!$override && $this->getPropertyValue($key) === $value) { |
41
|
|
|
return $this; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
$setMethod = ($isCollection) ? 'add' : 'set'; |
45
|
|
|
if (method_exists($this, $setMethod . $methodName)) { |
46
|
|
|
return $this->{$setMethod . $methodName}($value); |
47
|
|
|
} else { |
48
|
|
|
throw new \Exception(sprintf( |
49
|
|
|
'Unable to set value, method not found: %s%s in class: %s', |
50
|
|
|
$setMethod, |
51
|
|
|
$methodName, |
52
|
|
|
static::class |
53
|
|
|
)); |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Get property value |
59
|
|
|
* |
60
|
|
|
* @param $key |
61
|
|
|
* @return mixed |
62
|
|
|
*/ |
63
|
|
|
public function getPropertyValue($key) { |
64
|
|
|
$methodName = 'get' . $this->getMethodName($key); |
65
|
|
|
if(method_exists($this, $methodName)) { |
66
|
|
|
return $this->{$methodName}(); |
67
|
|
|
} |
68
|
|
|
return false; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* Converts snake_case to CamelCase to convert property names to getters |
73
|
|
|
* |
74
|
|
|
* @param string $propertyKey |
75
|
|
|
* @return string |
76
|
|
|
*/ |
77
|
|
|
protected function getMethodName($propertyKey) |
78
|
|
|
{ |
79
|
|
|
return ucfirst(preg_replace_callback('/_([a-z])/', function ($match) { |
80
|
|
|
return strtoupper($match[1]); |
81
|
|
|
}, $propertyKey)); |
82
|
|
|
} |
83
|
|
|
} |