Skip to content

Commit

Permalink
add new features
Browse files Browse the repository at this point in the history
  • Loading branch information
Bukashk0zzz committed Mar 9, 2016
1 parent 590d863 commit 13b77a2
Show file tree
Hide file tree
Showing 6 changed files with 97 additions and 30 deletions.
28 changes: 23 additions & 5 deletions Annotation/LiipImagineSerializableField.php
Expand Up @@ -59,17 +59,17 @@ public function __construct(array $options)
throw new \LogicException(sprintf('Either "value" or "filter" option must be set.'));
}

if ($this->checkOption('value')) {
if ($this->checkArrayOption('value')) {
$this->setFilter($options['value']);
} elseif ($this->checkOption('filter')) {
} elseif ($this->checkArrayOption('filter')) {
$this->setFilter($this->options['filter']);
}

if ($this->checkOption('vichUploaderField')) {
if ($this->checkStringOption('vichUploaderField')) {
$this->setVichUploaderField($this->options['vichUploaderField']);
}

if ($this->checkOption('virtualField')) {
if ($this->checkStringOption('virtualField')) {
$this->setVirtualField($this->options['virtualField']);
}
}
Expand Down Expand Up @@ -136,7 +136,7 @@ public function setVirtualField($virtualField)
* @return bool
* @throws \Exception
*/
private function checkOption($optionName)
private function checkStringOption($optionName)
{
if (array_key_exists($optionName, $this->options)) {
if (!is_string($this->options[$optionName])) {
Expand All @@ -148,4 +148,22 @@ private function checkOption($optionName)

return false;
}

/**
* @param $optionName
* @return bool
* @throws \Exception
*/
private function checkArrayOption($optionName)
{
if (array_key_exists($optionName, $this->options)) {
if (!is_array($this->options[$optionName]) && !is_string($this->options[$optionName])) {
throw new \InvalidArgumentException(sprintf('Option "'.$optionName.'" must be a array or string.'));
}

return true;
}

return false;
}
}
1 change: 1 addition & 0 deletions DependencyInjection/Configuration.php
Expand Up @@ -36,6 +36,7 @@ public function getConfigTreeBuilder()
->children()
->scalarNode('includeHost')->defaultValue(true)->end()
->scalarNode('vichUploaderSerialize')->defaultValue(true)->end()
->scalarNode('includeOriginal')->defaultValue(false)->end()
;

return $treeBuilder;
Expand Down
34 changes: 29 additions & 5 deletions EventListener/JmsSerializeListener.php
Expand Up @@ -15,6 +15,7 @@
use Doctrine\Common\Annotations\CachedReader;
use Doctrine\Common\Util\ClassUtils;
use JMS\Serializer\EventDispatcher\ObjectEvent;
use JMS\Serializer\GenericSerializationVisitor;
use Symfony\Component\Routing\RequestContext;
use Doctrine\Common\Persistence\Proxy;
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
Expand Down Expand Up @@ -165,8 +166,9 @@ public function onPostSerialize(ObjectEvent $event)
$property->setValue($object, $value);
}

/** @noinspection PhpUndefinedMethodInspection */
$event->getVisitor()->addData($virtualField, $this->serializeValue($liipImagineAnnotation, $object, $value));
/** @var GenericSerializationVisitor $visitor */
$visitor = $event->getVisitor();
$visitor->addData($virtualField, $this->serializeValue($liipImagineAnnotation, $object, $value));
}
}

Expand All @@ -179,7 +181,7 @@ public function onPostSerialize(ObjectEvent $event)
* @param ObjectEvent $event Event
* @return mixed
*/
protected function getObject($event)
protected function getObject(ObjectEvent $event)
{
$object = $event->getObject();

Expand All @@ -196,15 +198,37 @@ protected function getObject($event)
* @param LiipImagineSerializableField $liipImagineAnnotation
* @param object $object Serialized object
* @param string $value Value of field
* @return string
* @return array|string
*/
private function serializeValue(LiipImagineSerializableField $liipImagineAnnotation, $object, $value)
{
if ($vichField = $liipImagineAnnotation->getVichUploaderField()) {
$value = $this->vichStorage->resolveUri($object, $vichField);
}

return $this->cacheManager->getBrowserPath($value, $liipImagineAnnotation->getFilter());
$result = [];
if (array_key_exists('includeOriginal', $this->config) && $this->config['includeOriginal']) {
$result['original'] = $value;
}

$filters = $liipImagineAnnotation->getFilter();
if (is_array($filters)) {
foreach ($filters as $filter) {
$result[$filter] = $this->cacheManager->getBrowserPath($value, $filter);
}

return $result;
} else {
$filtered = $this->cacheManager->getBrowserPath($value, $filters);

if ($result) {
$result[$filters] = $filtered;

return $result;
}

return $filtered;
}
}

/**
Expand Down
23 changes: 19 additions & 4 deletions README.md
Expand Up @@ -51,6 +51,8 @@ bukashk0zzz_liip_imagine_serialization:
vichUploaderSerialize: false
# Set true for generating url with host for vichUploader fields
includeHost: false
# Set true for adding original field value to object
includeOriginal: false
```


Expand All @@ -68,8 +70,21 @@ At first you have to add `@Bukashk0zzz\LiipImagineSerializableClass` to the enti
Then you have to add `@Bukashk0zzz\LiipImagineSerializableField` annotation to the field you want to serialize.

Annotation `@Bukashk0zzz\LiipImagineSerializableClass` does not have any option.
Annotation `@Bukashk0zzz\LiipImagineSerializableField` has one required option *filter* which value should link to the LiipImagine filter .
It can be set like this `@Bukashk0zzz\LiipImagineSerializableField("photoFile")` or `@Bukashk0zzz\LiipImagineSerializableField(filter="photoFile")`.
Annotation `@Bukashk0zzz\LiipImagineSerializableField` has one required option *filter* which value should link to the LiipImagine filter.

It can be set like this `@Bukashk0zzz\LiipImagineSerializableField("photoFile")` or `@Bukashk0zzz\LiipImagineSerializableField(filter="photoFile")`.
*filter* can be array of filters in this case serialized field will be also array.
For example if you add annotation `@Bukashk0zzz\LiipImagineSerializableField(filter={"big", "small"})` for field `image` then you get:

```json
{
"image": {
"big": {}"/uploads/users/big/5659828fa80a7.jpg",
"small": {}"/uploads/users/small/5659828fa80a7.jpg"
}
}
```

Also there is another two not required options:
- `vichUploaderField` - If you use VichUploaderBundle for your uploads you should specify link to the field with `@Vich\UploadableField` annotation
- `virtualField` - By default serializer will override field value with link to filtered image. If you add `virtualField` option serializer will add to serialized object new field with name that you provided in this option and url to filtered image, original field in this case will be unattached.
Expand All @@ -81,7 +96,7 @@ The generated URI by default:
```json
{
"photo": "http://example.com/uploads/users/photos/5659828fa80a7.jpg",
"cover": "http://example.com/uploads/users/covers/456428fa8g4a8.jpg",
"cover": "http://example.com/uploads/users/covers/456428fa8g4a8.jpg"
}
```

Expand All @@ -90,7 +105,7 @@ The generated URI with `includeHost` set to `false`:
```json
{
"photo": "/uploads/users/photos/5659828fa80a7.jpg",
"cover": "/uploads/users/covers/456428fa8g4a8.jpg",
"cover": "/uploads/users/covers/456428fa8g4a8.jpg"
}
```

Expand Down
39 changes: 24 additions & 15 deletions Tests/EventListener/JmsSerializeListenerTest.php
Expand Up @@ -112,8 +112,9 @@ public function testVirtualFieldSerialization()
$user = new User();
$this->generateCacheManager();
$this->generateRequestContext();
$this->addEventListeners();
$serializer = SerializerBuilder::create()->configureListeners(function (EventDispatcher $dispatcher) {
$this->addEvents($dispatcher);
$this->addEvents($dispatcher, false);
})->build();
$result = $serializer->serialize($user, 'json');

Expand All @@ -130,6 +131,7 @@ public function testSerialization()
$user = new User();
$this->generateCacheManager();
$this->generateRequestContext();
$this->addEventListeners();
$this->dispatchEvents($user);
static::assertEquals('http://a/path/to/an/image1.png', $user->getCoverUrl());
static::assertEquals('http://a/path/to/an/image2.png', $user->getPhotoName());
Expand All @@ -144,41 +146,48 @@ public function testSerialization()
}

/**
* Test serialization of proxy object
* Test serialization of proxy object and field with array of filters
*/
public function testProxySerialization()
{
$userPictures = new UserPictures();
$this->generateCacheManager();
$this->generateRequestContext(false, true);
$this->addEventListeners();
$data = $this->serializeObject($userPictures);

static::assertEquals('http://a/path/to/an/image1.png', $data['cover']);
static::assertEquals('http://a/path/to/an/image1.png', $data['cover']['big']);
static::assertEquals('http://a/path/to/an/image2.png', $data['cover']['small']);
static::assertEquals('http://example.com:8000/uploads/photo.jpg', $data['photo']);
static::assertEquals('http://a/path/to/an/image2.png', $data['photoThumb']);
static::assertEquals('http://a/path/to/an/image3.png', $data['photoThumb']);
}

/**
* Test serialization with included http host and port in the URI
* Test serialization with included http host and port in the URI and include original option "true"
*/
public function testHttpsSerialization()
{
$userPictures = new UserPictures();
$this->generateCacheManager();
$this->generateRequestContext(true, true);
$data = $this->serializeObject($userPictures);
$data = $this->serializeObject($userPictures, true);

static::assertEquals('https://example.com:8800/uploads/photo.jpg', $data['photo']);
static::assertEquals('http://a/path/to/an/image1.png', $data['cover']['big']);
static::assertEquals('http://a/path/to/an/image2.png', $data['cover']['small']);
static::assertEquals('http://a/path/to/an/image3.png', $data['photoThumb']['thumb_filter']);
static::assertEquals('/uploads/photo.jpg', $data['photoThumb']['original']);
}

/**
* @param User|UserPictures $user
* @param bool $includeOriginal Include original link or not
* @return array
*/
protected function serializeObject($user)
protected function serializeObject($user, $includeOriginal = false)
{
$serializer = SerializerBuilder::create()->configureListeners(function (EventDispatcher $dispatcher) {
$this->addEvents($dispatcher);
$serializer = SerializerBuilder::create()->configureListeners(function (EventDispatcher $dispatcher) use ($includeOriginal) {
$this->addEvents($dispatcher, $includeOriginal);
})->build();
$result = $serializer->serialize($user, 'json');

Expand Down Expand Up @@ -218,28 +227,29 @@ protected function generateRequestContext($https = false, $port = false)
->willReturn(8000);
}
}

$this->addEventListeners();
}

/**
* Add post & pre serialize event listeners
* @param bool $includeOriginal Include original link or not
*/
protected function addEventListeners()
protected function addEventListeners($includeOriginal = false)
{
$this->dispatcher = new EventDispatcher();
$this->addEvents($this->dispatcher);
$this->addEvents($this->dispatcher, $includeOriginal);
}

/**
* Add post & pre serialize event to dispatcher
* @param EventDispatcher $dispatcher
* @param bool $includeOriginal Include original link or not
*/
protected function addEvents(EventDispatcher $dispatcher)
protected function addEvents(EventDispatcher $dispatcher, $includeOriginal = false)
{
$listener = new JmsSerializeListener($this->requestContext, $this->annotationReader, $this->cacheManager, $this->vichStorage, [
'includeHost' => true,
'vichUploaderSerialize' => true,
'includeOriginal' => $includeOriginal,
]);

$dispatcher->addListener(JmsEvents::PRE_SERIALIZE, [$listener, 'onPreSerialize']);
Expand All @@ -266,7 +276,6 @@ protected function generateCacheManager()
$config = static::getMock('Liip\ImagineBundle\Imagine\Filter\FilterConfiguration');
$config->expects(static::any())
->method('get')
->with('thumb_filter')
->will(static::returnValue(array(
'size' => array(180, 180),
'mode' => 'outbound',
Expand Down
2 changes: 1 addition & 1 deletion Tests/Fixtures/UserPictures.php
Expand Up @@ -50,7 +50,7 @@ class UserPictures implements Proxy
* @JMS\Expose
* @JMS\SerializedName("cover")
*
* @Bukashk0zzz\LiipImagineSerializableField("thumb_filter")
* @Bukashk0zzz\LiipImagineSerializableField(filter={"big", "small"})
*/
public $coverUrl;

Expand Down

0 comments on commit 13b77a2

Please sign in to comment.