1: <?php
2: namespace TIC\CoreBundle\Util;
3:
4: /**
5: * Méthodes statiques utilitaires pour manipuler des objets.
6: */
7: class ObjectHelper
8: {
9:
10: /**
11: * This class should not be instantiated.
12: */
13: private function __construct()
14: {
15: }
16:
17: /**
18: * Changement d'une valeur de propriété sur un objet.
19: *
20: * @param object $item Instance d'objet à modifier
21: * @param string $property Nom de la propriété concernée
22: * @param mixed $value Nouvelle valeur à affecter
23: * @return bool Vrai si propriété modifiée ; Faux si inchangée
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: * Inversion d'une valeur de propriété (booléenne) sur un objet.
45: *
46: * @param object $item Instance d'objet à modifier
47: * @param string $property Nom de la propriété booléenne à inverser
48: * @param bool $value Nouvelle valeur imposée plutôt qu'une inversion de la courante
49: * @return bool Retourne la nouvelle valeur de la propriété ; Null si spécifiée et inchangée
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: // valeur inverse par défaut ou retour null si inchangée
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: