53e0de50 |
<?php
namespace elanpl\L3;
class Serialization{
|
cdfe8eaf |
protected $serializers; //registered serializers dictionary
|
53e0de50 |
public function __construct()
{
|
cdfe8eaf |
$this->serializers = array();
|
53e0de50 |
}
|
cdfe8eaf |
public function register($contentType, $serializer, $viewModelClass = null){
|
cd60f809 |
if(!class_exists($serializer,true)){
throw new \Exception("Class \"$serializer\" not found!");
}
if(!isset(class_implements($serializer, true)['elanpl\\L3\\ISerializer'])){
|
cdfe8eaf |
throw new \Exception("Class \"$serializer\" does not implement ISerializer interface!");
}
|
c6173b1c |
if(isset($viewModelClass) && $viewModelClass!=''){
$class_key = $viewModelClass.'|';
|
53e0de50 |
}
else{
$class_key = '';
}
|
cdfe8eaf |
$this->serializers[$class_key.$contentType] = $serializer;
|
53e0de50 |
}
|
c6173b1c |
public function match($acceptTypes, $viewModel=null){
if(isset($viewModel)){
if(is_object($viewModel)){
$viewModelClass = get_class($viewModel);
|
53e0de50 |
}
|
c6173b1c |
if(is_string($viewModel)){
$viewModelClass = $viewModel;
|
53e0de50 |
}
}
|
c6173b1c |
if(is_array($acceptTypes)){
|
cdfe8eaf |
$registeredTypes = array_keys($this->serializers);
|
53e0de50 |
|
c6173b1c |
foreach ($acceptTypes as $type){
|
53e0de50 |
//Dedicated config for ViewModel class first...
|
cdfe8eaf |
if(array_key_exists($viewModelClass."|".$type, $this->serializers)){
|
53e0de50 |
return $type;
}
|
c6173b1c |
foreach($registeredTypes as $rtype_with_class){
|
53e0de50 |
$rtype_parts = explode("|", $rtype_with_class);
if(count($rtype_parts)==2){
$rclass = $rtype_parts[0];
$t = explode("/", $type);
$rt = explode("/", $rtype_parts[1]);
|
c6173b1c |
if($rclass==$viewModelClass && ($t[0]=="*" || $rt[0]=="*" || $t[0]==$rt[0]) && ($t[1]=="*" || $rt[1]=="*" || $t[1]==$rt[1])){
|
53e0de50 |
return $rtype_with_class;
}
}
}
//Then check configs without the ViewModel class name
|
cdfe8eaf |
if(array_key_exists($type, $this->serializers)){
|
53e0de50 |
return $type;
}
|
c6173b1c |
foreach($registeredTypes as $rtype){
|
53e0de50 |
$t = explode("/", $type);
$rt = explode("/", $rtype);
|
133f20a3 |
if(($t[0]=="*" || $rt[0]=="*" || $t[0]==$rt[0]) && ($t[1]=="*" || $rt[1]=="*" || $t[1]==$rt[1])){
|
53e0de50 |
return $rtype;
}
}
}
}
return false;
}
|
c6173b1c |
public function serialize($contentType, $viewModel){
|
cdfe8eaf |
if(isset($this->serializers[get_class($viewModel).'|'.$contentType])){
$serializerClass = $this->serializers[get_class($viewModel).'|'.$contentType];
|
53e0de50 |
}
|
cdfe8eaf |
else if(isset($this->serializers[$contentType])){
$serializerClass = $this->serializers[$contentType];
|
53e0de50 |
}
if(isset($serializerClass)){
$serializer = new $serializerClass();
|
cdfe8eaf |
return $serializer->serialize($viewModel);
|
53e0de50 |
}
else{
return null;
}
}
}
|