Skip to content

Commit

Permalink
Add normalize events ✨
Browse files Browse the repository at this point in the history
  • Loading branch information
Bukashk0zzz committed Mar 2, 2017
1 parent 44ea8ea commit 1ef3462
Show file tree
Hide file tree
Showing 10 changed files with 248 additions and 10 deletions.
48 changes: 48 additions & 0 deletions Event/UrlNormalizerEvent.php
@@ -0,0 +1,48 @@
<?php

namespace Bukashk0zzz\LiipImagineSerializationBundle\Event;

use Symfony\Component\EventDispatcher\Event;

/**
* UrlNormalizerEvent
*
* @author Denis Golubovskiy <bukashk0zzz@gmail.com>
*/
class UrlNormalizerEvent extends Event
{
const ORIGIN = 'bukashk0zzz_liip_imagine.event_pre_origin_normalize';
const FILTERED = 'bukashk0zzz_liip_imagine.event_pre_filtered_normalize';

/**
* @var string
*/
protected $url;

/**
* @param string $url
*/
public function __construct($url)
{
$this->url = $url;
}

/**
* @return string
*/
public function getUrl()
{
return $this->url;
}

/**
* @param string $url
* @return $this
*/
public function setUrl($url)
{
$this->url = $url;

return $this;
}
}
3 changes: 2 additions & 1 deletion EventListener/JmsPreSerializeListener.php
Expand Up @@ -12,6 +12,7 @@

use Bukashk0zzz\LiipImagineSerializationBundle\Annotation\LiipImagineSerializableClass;
use Bukashk0zzz\LiipImagineSerializationBundle\Annotation\LiipImagineSerializableField;
use Bukashk0zzz\LiipImagineSerializationBundle\Normalizer\UrlNormalizerInterface;
use Doctrine\Common\Util\ClassUtils;
use JMS\Serializer\EventDispatcher\ObjectEvent;

Expand Down Expand Up @@ -55,7 +56,7 @@ public function onPreSerialize(ObjectEvent $event)
if (array_key_exists('includeHost', $this->config) && $this->config['includeHost']) {
$originalImageUri = $this->getHostUrl().$originalImageUri;
}
$property->setValue($object, $this->normalizeUrl($originalImageUri, 'originUrlNormalizer'));
$property->setValue($object, $this->normalizeUrl($originalImageUri, UrlNormalizerInterface::TYPE_ORIGIN));
}
}
}
Expand Down
45 changes: 38 additions & 7 deletions EventListener/JmsSerializeListenerAbstract.php
Expand Up @@ -11,9 +11,11 @@
namespace Bukashk0zzz\LiipImagineSerializationBundle\EventListener;

use Bukashk0zzz\LiipImagineSerializationBundle\Annotation\LiipImagineSerializableField;
use Bukashk0zzz\LiipImagineSerializationBundle\Event\UrlNormalizerEvent;
use Bukashk0zzz\LiipImagineSerializationBundle\Normalizer\UrlNormalizerInterface;
use Doctrine\Common\Annotations\CachedReader;
use JMS\Serializer\EventDispatcher\ObjectEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Routing\RequestContext;
use Doctrine\Common\Persistence\Proxy;
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
Expand Down Expand Up @@ -46,6 +48,11 @@ class JmsSerializeListenerAbstract
*/
protected $vichStorage;

/**
* @var EventDispatcherInterface $eventDispatcher
*/
protected $eventDispatcher;

/**
* @var array $config Bundle config
*/
Expand All @@ -54,23 +61,26 @@ class JmsSerializeListenerAbstract
/**
* JmsSerializeListenerAbstract constructor.
*
* @param RequestContext $requestContext
* @param CachedReader $annotationReader
* @param CacheManager $cacheManager
* @param StorageInterface $vichStorage
* @param array $config
* @param RequestContext $requestContext
* @param CachedReader $annotationReader
* @param CacheManager $cacheManager
* @param StorageInterface $vichStorage
* @param EventDispatcherInterface $eventDispatcher
* @param array $config
*/
public function __construct(
RequestContext $requestContext,
CachedReader $annotationReader,
CacheManager $cacheManager,
StorageInterface $vichStorage,
EventDispatcherInterface $eventDispatcher,
array $config
) {
$this->requestContext = $requestContext;
$this->annotationReader = $annotationReader;
$this->cacheManager = $cacheManager;
$this->vichStorage = $vichStorage;
$this->eventDispatcher = $eventDispatcher;
$this->config = $config;
}

Expand Down Expand Up @@ -107,7 +117,7 @@ protected function serializeValue(LiipImagineSerializableField $liipAnnotation,
}

$result = [];
$value = $this->normalizeUrl($value, 'originUrlNormalizer');
$value = $this->normalizeUrl($value, UrlNormalizerInterface::TYPE_ORIGIN);
if (array_key_exists('includeOriginal', $this->config) && $this->config['includeOriginal']) {
$result['original'] = (array_key_exists('includeHostForOriginal', $this->config) && $this->config['includeHostForOriginal'] && $liipAnnotation->getVichUploaderField())
? $this->getHostUrl().$value
Expand Down Expand Up @@ -161,6 +171,8 @@ protected function getHostUrl()
*/
protected function normalizeUrl($url, $normalizer)
{
$url = $this->addPreNormalizeUrlEvent($normalizer, $url);

if (array_key_exists($normalizer, $this->config) && $this->config[$normalizer]) {
$normalizerClassName = $this->config[$normalizer];
$normalizer = new $normalizerClassName();
Expand All @@ -185,7 +197,7 @@ private function prepareFilteredUrl($url)
$url = $this->stripHostFromUrl($url);
}

return $this->normalizeUrl($url, 'filteredUrlNormalizer');
return $this->normalizeUrl($url, UrlNormalizerInterface::TYPE_FILTERED);
}

/**
Expand All @@ -204,4 +216,23 @@ private function stripHostFromUrl($url)

throw new \InvalidArgumentException('Can\'t strip host from url, because can\'t parse url.');
}

/**
* @param string $type
* @param string $url
*
* @return string
*/
private function addPreNormalizeUrlEvent($type, $url)
{
/** @var UrlNormalizerEvent $event */
$event = $this->eventDispatcher->dispatch(
$type === UrlNormalizerInterface::TYPE_ORIGIN
? UrlNormalizerEvent::ORIGIN
: UrlNormalizerEvent::FILTERED,
new UrlNormalizerEvent($url)
);

return $event->getUrl();
}
}
3 changes: 3 additions & 0 deletions Normalizer/UrlNormalizerInterface.php
Expand Up @@ -9,6 +9,9 @@
*/
interface UrlNormalizerInterface
{
const TYPE_ORIGIN = 'originUrlNormalizer';
const TYPE_FILTERED = 'filteredUrlNormalizer';

/**
* @param string $url
* @return string
Expand Down
62 changes: 62 additions & 0 deletions README.md
Expand Up @@ -150,6 +150,68 @@ class UrlNormalizer implements UrlNormalizerInterface
}
```

Events
-------
There are two events:
- bukashk0zzz_liip_imagine.event_pre_origin_normalize // Dispatch before origin url normalization
- bukashk0zzz_liip_imagine.event_pre_filtered_normalize // Dispatch before filtered url normalization

**Example subscriber:**
```yaml
services:
app.liip_imagine_serialization_subscriber:
class: AppBundle\EventSubscriber\LiipImagineSerializationEventSubscriber
tags:
- { name: bukashk0zzz_liip_imagine_subscriber }
```

```php
<?php

namespace AppBundle\EventSubscriber;

use Bukashk0zzz\LiipImagineSerializationBundle\Event\UrlNormalizerEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
* LiipImagineSerializationEventSubscriber
*/
class LiipImagineSerializationEventSubscriber implements EventSubscriberInterface
{
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
UrlNormalizerEvent::ORIGIN => [
['normalizeOrigin', 10],
],
UrlNormalizerEvent::FILTERED => [
['normalizeFiltered', 10],
],
];
}

/**
* @param UrlNormalizerEvent $event
*/
public function normalizeOrigin(UrlNormalizerEvent $event)
{
$event->setUrl(str_replace('photo', 'newPhoto', $event->getUrl()));
}

/**
* @param UrlNormalizerEvent $event
*/
public function normalizeFiltered(UrlNormalizerEvent $event)
{
$event->setUrl(str_replace('example.com', 'img.example.com', $event->getUrl()));
}
}
```


Example
-------

Expand Down
2 changes: 2 additions & 0 deletions Resources/config/services.yml
Expand Up @@ -10,6 +10,7 @@ services:
- '@annotations.cached_reader'
- '@liip_imagine.cache.manager'
- '@vich_uploader.storage'
- '@event_dispatcher'
tags:
- { name: jms_serializer.event_listener, event: serializer.pre_serialize, method: onPreSerialize }
bukashk0zzz_liip_imagine_post_serialization.listener:
Expand All @@ -19,5 +20,6 @@ services:
- '@annotations.cached_reader'
- '@liip_imagine.cache.manager'
- '@vich_uploader.storage'
- '@event_dispatcher'
tags:
- { name: jms_serializer.event_listener, event: serializer.post_serialize, method: onPostSerialize }
Expand Up @@ -51,6 +51,7 @@ public function testLoadExtension()
$this->container->set('annotations.cached_reader', new \stdClass());
$this->container->set('liip_imagine.cache.manager', new \stdClass());
$this->container->set('vich_uploader.storage', new \stdClass());
$this->container->set('event_dispatcher', new \stdClass());

$this->container->prependExtensionConfig($this->extension->getAlias(), ['includeHost' => true]);
$this->container->loadFromExtension($this->extension->getAlias());
Expand Down
19 changes: 17 additions & 2 deletions Tests/EventListener/JmsSerializeEventsManager.php
Expand Up @@ -13,6 +13,7 @@

use Bukashk0zzz\LiipImagineSerializationBundle\EventListener\JmsPostSerializeListener;
use Bukashk0zzz\LiipImagineSerializationBundle\EventListener\JmsPreSerializeListener;
use Bukashk0zzz\LiipImagineSerializationBundle\Tests\EventSubscriber\Bukashk0zzzSerializationEventSubscriber;
use Bukashk0zzz\LiipImagineSerializationBundle\Tests\Fixtures\UserPictures;
use Bukashk0zzz\LiipImagineSerializationBundle\Tests\Fixtures\User;
use JMS\Serializer\DeserializationContext;
Expand Down Expand Up @@ -43,12 +44,18 @@ class JmsSerializeEventsManager
*/
private $annotationReader;

/**
* @var \Symfony\Component\EventDispatcher\EventDispatcher
*/
private $symfonyEventDispatcher;

/**
* JmsSerializeEventsManager constructor.
*/
public function __construct()
{
$this->annotationReader = new CachedReader(new AnnotationReader(), new ArrayCache());
$this->symfonyEventDispatcher = new \Symfony\Component\EventDispatcher\EventDispatcher();
}

/**
Expand Down Expand Up @@ -99,10 +106,18 @@ public function addEvents(EventDispatcher $dispatcher, RequestContext $requestCo
];
}

$preListener = new JmsPreSerializeListener($requestContext, $this->annotationReader, $cacheManager, $vichStorage, $config);
$postListener = new JmsPostSerializeListener($requestContext, $this->annotationReader, $cacheManager, $vichStorage, $config);
$preListener = new JmsPreSerializeListener($requestContext, $this->annotationReader, $cacheManager, $vichStorage, $this->symfonyEventDispatcher, $config);
$postListener = new JmsPostSerializeListener($requestContext, $this->annotationReader, $cacheManager, $vichStorage, $this->symfonyEventDispatcher, $config);

$dispatcher->addListener(JmsEvents::PRE_SERIALIZE, [$preListener, 'onPreSerialize']);
$dispatcher->addListener(JmsEvents::POST_SERIALIZE, [$postListener, 'onPostSerialize']);
}

/**
* Add normalizer subscriber
*/
public function addNormalizerSubscriber()
{
$this->symfonyEventDispatcher->addSubscriber(new Bukashk0zzzSerializationEventSubscriber());
}
}
21 changes: 21 additions & 0 deletions Tests/EventListener/JmsSerializeListenerTest.php
Expand Up @@ -174,6 +174,27 @@ public function testSerializationWithFilteredNormalizer()
static::assertEquals('http://img.example.com:8800/a/path/to/an/image1.png', $data['cover']['big']);
}

/**
* Test serialization with event subscriber
*/
public function testSerializationWithEventSubscriber()
{
$userPictures = new UserPictures();
$this->generateCacheManager();
$this->generateRequestContext();
$this->eventManager->addNormalizerSubscriber();
$data = $this->serializeObject($userPictures, [
'includeHost' => true,
'vichUploaderSerialize' => true,
'includeOriginal' => true,
]);

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

/**
* Test serialization with url parse exception
*
Expand Down

0 comments on commit 1ef3462

Please sign in to comment.