| 1: | <?php |
| 2: | namespace TIC\CoreBundle\Util; |
| 3: | |
| 4: | |
| 5: | |
| 6: | |
| 7: | class ObjectHelper |
| 8: | { |
| 9: | |
| 10: | |
| 11: | |
| 12: | |
| 13: | private function __construct() |
| 14: | { |
| 15: | } |
| 16: | |
| 17: | |
| 18: | |
| 19: | |
| 20: | |
| 21: | |
| 22: | |
| 23: | |
| 24: | |
| 25: | public static function changeField(object $item, string $property, mixed $value): bool |
| 26: | { |
| 27: | $cur_value = null; |
| 28: | |
| 29: | $accessor = 'get' . \ucfirst($property); |
| 30: | if ( \method_exists($item, $accessor)) $cur_value = \call_user_func([$item, $accessor]); |
| 31: | elseif (\property_exists($item, $property)) $cur_value = $item->{$property}; |
| 32: | |
| 33: | if ($cur_value === $value) return false; |
| 34: | |
| 35: | $mutator = 'set' . \ucfirst($property); |
| 36: | if ( \method_exists($item, $mutator) ) \call_user_func([$item, $mutator], $value); |
| 37: | elseif (\property_exists($item, $property)) $item->{$property} = $value; |
| 38: | else throw new \InvalidArgumentException(\sprintf("No property named `%s` exists", $property)); |
| 39: | |
| 40: | return true; |
| 41: | } |
| 42: | |
| 43: | |
| 44: | |
| 45: | |
| 46: | |
| 47: | |
| 48: | |
| 49: | |
| 50: | |
| 51: | public static function toggleField(object $item, string $property, ?bool $value = null): ?bool |
| 52: | { |
| 53: | $cur_value = null; |
| 54: | |
| 55: | $accessor = 'get' . \ucfirst($property); |
| 56: | if ( \method_exists($item, $accessor)) $cur_value = \call_user_func([$item, $accessor]); |
| 57: | elseif (\property_exists($item, $property)) $cur_value = $item->{$property}; |
| 58: | |
| 59: | |
| 60: | if ($value === null) $value = ($cur_value) ? false : true; |
| 61: | elseif ($value === $cur_value) return null; |
| 62: | |
| 63: | $mutator = 'set' . \ucfirst($property); |
| 64: | if ( \method_exists($item, $mutator) ) \call_user_func([$item, $mutator], $value); |
| 65: | elseif (\property_exists($item, $property)) $item->{$property} = $value; |
| 66: | else throw new \InvalidArgumentException(\sprintf("No property named `%s` exists", $property)); |
| 67: | |
| 68: | return $value; |
| 69: | } |
| 70: | |
| 71: | } |
| 72: | |