DriverHandler.php (2387B)
1 <?php 2 3 namespace Finwo\Mapper; 4 5 use Finwo\Mapper\Driver\DriverInterface; 6 7 class DriverHandler 8 { 9 /** 10 * @var array<DriverInterface> 11 */ 12 protected $drivers = array(); 13 14 /** 15 * @param string $name 16 * @param DriverInterface $driver 17 * 18 * @return $this 19 * @throws \Error 20 */ 21 public function registerDriver($name = '', DriverInterface $driver) 22 { 23 if (!is_string($name)) { 24 throw new \Error("Name is not a string"); 25 } 26 27 if (isset($this->drivers[$name])) { 28 throw new \Error(sprintf("Driver by the name of '%s' already registered.",$name)); 29 } 30 31 $this->drivers[$name] = $driver; 32 33 return $this; 34 } 35 36 /** 37 * @param string $input 38 * @param string $encoding 39 * 40 * @return string 41 * @throws \Error 42 */ 43 public function deserialize($input = '', $encoding = null) 44 { 45 // We may not need to deserialize 46 if (is_array($input)|is_object($input)) { 47 return $input; 48 } 49 50 // We might need to detect which encoding to use 51 if (is_null($encoding)) { 52 foreach ($this->drivers as $name => $driver) { 53 if($driver->decodeSupport($input)) { 54 $encoding = $name; 55 break; 56 } 57 } 58 } 59 60 // Decode the data 61 if (isset($this->drivers[$encoding])) { 62 return $this->drivers[$encoding]->decode($input); 63 } 64 65 // Or notify we've failed 66 throw new \Error("No driver capable of handling data is registered"); 67 } 68 69 /** 70 * @param mixed $data 71 * @param null $encoding 72 * 73 * @return string 74 * @throws \Error 75 */ 76 public function serialize($data, $encoding = null) 77 { 78 79 // We might need to detect which encoding to use 80 if (is_null($encoding)) { 81 foreach ($this->drivers as $name => $driver) { 82 if($driver->encodeSupport($data)) { 83 $encoding = $name; 84 break; 85 } 86 } 87 } 88 89 // Decode the data 90 if (isset($this->drivers[$encoding])) { 91 return $this->drivers[$encoding]->encode($data); 92 } 93 94 // Or notify we've failed 95 throw new \Error("No driver capable of handling data is registered"); 96 } 97 98 }