Skip to content

Commit

Permalink
introduced ChainSerializer
Browse files Browse the repository at this point in the history
  • Loading branch information
fprochazka committed Dec 29, 2014
1 parent b614546 commit 2f5c882
Showing 1 changed file with 84 additions and 0 deletions.
84 changes: 84 additions & 0 deletions lib/Doctrine/Search/Serializer/ChainSerializer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?php

namespace Doctrine\Search\Serializer;

use Doctrine\Common\Util\ClassUtils;
use Doctrine\Search\DefaultSerializerNotProvidedException;
use Doctrine\Search\SerializerInterface;



/**
* @author Filip Procházka <[email protected]>
*/
class ChainSerializer implements SerializerInterface
{

/**
* @var SerializerInterface[]
*/
private $serializers = [];

/**
* @var SerializerInterface
*/
private $defaultSerializer;



public function addSerializer($classType, SerializerInterface $serializer)
{
$this->serializers[strtolower($classType)] = $serializer;
}



public function setDefaultSerializer(SerializerInterface $serializer)
{
$this->defaultSerializer = $serializer;
}



/**
* @param object $object
* @throws DefaultSerializerNotProvidedException
* @return string
*/
public function serialize($object)
{
$lName = strtolower(ClassUtils::getClass($object));
if (isset($this->serializers[$lName])) {
return $this->serializers[$lName]->serialize($object);
}

if (!$this->defaultSerializer) {
throw new DefaultSerializerNotProvidedException;
}

return $this->defaultSerializer->serialize($object);
}



/**
* @param string $entityName
* @param string $data
* @throws DefaultSerializerNotProvidedException
* @return object
*/
public function deserialize($entityName, $data)
{
$lName = strtolower($entityName);
if (isset($this->serializers[$lName])) {
return $this->serializers[$lName]->deserialize($entityName, $data);
}

if (!$this->defaultSerializer) {
throw new DefaultSerializerNotProvidedException;
}

return $this->defaultSerializer->deserialize($entityName, $data);
}

}

0 comments on commit 2f5c882

Please sign in to comment.