src/Model/AbstractModel.php line 9

Open in your IDE?
  1. <?php
  2. namespace App\Model;
  3. class AbstractModel implements \Serializable\JsonSerializable
  4. {
  5.     public function jsonSerialize(): mixed
  6.     {
  7.         return $this->serialize();
  8.     }
  9.     public function __serialize(): array {
  10.         return $this->serialize();
  11.     }
  12.     public function serialize(): array
  13.     {
  14.         $data=[];
  15.         foreach(get_object_vars($this) as $key=>$val) {
  16.             $value=$val//store value incase we need to modify format
  17.             if($val instanceof \DateTime) {
  18.                 $value=$val->format('c');
  19.             }
  20.             $data[$this->camel_to_snake($key)]=$value;
  21.         }
  22.         return $data;
  23.     }
  24.     public function __unserialize($serialized) {
  25.         return $this->unserialize($serialized);
  26.     }
  27.     public function unserialize($serialized)
  28.     {
  29.         foreach($serialized as $key=>$val) {
  30.             $prop=$this->snakeToCamel($key);
  31.             $f="set".ucfirst($prop);
  32.             if(method_exists($this,$f)) {
  33.                 $this->$f($val);
  34.             }
  35.         }
  36.     }
  37.     function camel_to_snake($input)
  38.     {
  39.         return strtolower(preg_replace('/(?<!^)[A-Z]/''_$0'$input));
  40.     }
  41.     function snakeToCamel($input)
  42.     {
  43.         return lcfirst(str_replace(' '''ucwords(str_replace('_'' '$input))));
  44. //        return lcfirst(str_replace('', '', ucwords($input, '')));
  45.     }
  46. }