Skip to content

Commit

Permalink
[Admin] Extracted notification fetching to services
Browse files Browse the repository at this point in the history
  • Loading branch information
NoResponseMate committed Mar 28, 2017
1 parent c276708 commit af6ec66
Show file tree
Hide file tree
Showing 12 changed files with 251 additions and 45 deletions.
@@ -0,0 +1,86 @@
<?php

/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Sylius\Bundle\AdminBundle\Controller;

use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Uri;
use Http\Message\MessageFactory;
use Psr\Http\Message\UriInterface;
use Sylius\Bundle\CoreBundle\Application\Kernel;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
* @author Jan Góralski <jan.goralski@lakion.com>
*/
class NotificationController
{
/**
* @var ClientInterface
*/
protected $client;

/**
* @var MessageFactory
*/
protected $messageFactory;

/**
* @var UriInterface
*/
protected $hubUri;

/**
* @param ClientInterface $client
* @param MessageFactory $messageFactory
* @param string $hubUri
*/
public function __construct(ClientInterface $client, MessageFactory $messageFactory, $hubUri)
{
$this->client = $client;
$this->messageFactory = $messageFactory;
$this->hubUri = new Uri($hubUri);
}

/**
* @param Request $request
*
* @return JsonResponse
*/
public function getVersionAction(Request $request)
{
$content = [
'version' => Kernel::VERSION,
'hostname' => $request->getHost(),
'locale' => $request->getLocale(),
'user_agent' => $request->headers->get('User-Agent'),
];

$headers = ['Content-Type' => 'application/json'];

$hubRequest = $this->messageFactory->createRequest(
Request::METHOD_GET,
$this->hubUri,
$headers,
json_encode($content)
);

try {
$hubResponse = $this->client->send($hubRequest, ['verify' => false]);
} catch (GuzzleException $exception) {
return JsonResponse::create('', JsonResponse::HTTP_NO_CONTENT);
}

return JsonResponse::fromJsonString($hubResponse->getBody()->getContents());
}
}
Expand Up @@ -29,7 +29,7 @@ public function getConfigTreeBuilder()

$rootNode
->children()
->arrayNode('notification')
->arrayNode('notifications')
->addDefaultsIfNotSet()
->children()
->booleanNode('enabled')
Expand Down
Expand Up @@ -11,10 +11,8 @@

namespace Sylius\Bundle\AdminBundle\DependencyInjection;

use Sylius\Bundle\AdminBundle\Twig\NotificationExtension;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

Expand All @@ -31,24 +29,9 @@ public function load(array $config, ContainerBuilder $container)
$config = $this->processConfiguration($this->getConfiguration([], $container), $config);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));

$this->configureNotifications($config['notification'], $container);
$container->setParameter('sylius.admin.notification.enabled', $config['notifications']['enabled']);
$container->setParameter('sylius.admin.notification.frequency', $config['notifications']['frequency']);

$loader->load('services.xml');
}

/**
* @param array $config
* @param ContainerBuilder $container
*/
private function configureNotifications(array $config, ContainerBuilder $container)
{
$container->setParameter('sylius.admin.notification.enabled', $config['enabled']);

$notificationExtension = new Definition(NotificationExtension::class);
$notificationExtension->addArgument($config['enabled']);
$notificationExtension->addArgument($config['frequency'] ?: null);
$notificationExtension->addTag('twig.extension');

$container->setDefinition('sylius.notification.extension', $notificationExtension);
}
}
Expand Up @@ -20,3 +20,8 @@ sylius_admin_ajax_render_province_form:
_controller: sylius.controller.province:choiceOrTextFieldFormAction
_sylius:
template: "@SyliusAdmin/Common/Form/_province.html.twig"

sylius_admin_ajax_get_version:
path: /get-version
defaults:
_controller: sylius.controller.admin.notification:getVersionAction
9 changes: 9 additions & 0 deletions src/Sylius/Bundle/AdminBundle/Resources/config/services.xml
Expand Up @@ -24,5 +24,14 @@
<argument type="service" id="security.token_storage" />
<tag name="sylius.context.locale" priority="128" />
</service>

<service id="sylius.twig.extension.widget.admin_notification" class="Sylius\Bundle\AdminBundle\Twig\NotificationWidgetExtension">
<argument>%sylius.admin.notification.enabled%</argument>
<argument>%sylius.admin.notification.frequency%</argument>
<tag name="twig.extension" />
</service>

<service id="sylius.http_client" class="GuzzleHttp\Client" public="false" />
<service id="sylius.http_message_factory" class="Http\Message\MessageFactory\GuzzleMessageFactory" public="false" />
</services>
</container>
Expand Up @@ -12,6 +12,10 @@
-->

<container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<parameters>
<parameter key="sylius.admin.notification.uri">http://hub.sylius.com/version</parameter>
</parameters>

<services>
<service id="sylius.controller.admin.dashboard" class="Sylius\Bundle\AdminBundle\Controller\DashboardController">
<argument type="service" id="sylius.dashboard.statistics_provider" />
Expand All @@ -33,5 +37,11 @@
<argument type='service' id="sylius.repository.customer" />
<argument type='service' id="templating" />
</service>

<service id="sylius.controller.admin.notification" class="Sylius\Bundle\AdminBundle\Controller\NotificationController">
<argument type="service" id="sylius.http_client" />
<argument type="service" id="sylius.http_message_factory" />
<argument type="string">%sylius.admin.notification.uri%</argument>
</service>
</services>
</container>
Expand Up @@ -12,10 +12,10 @@

$.fn.extend({
notification: function () {
const HUB_REQUEST_TIME = 'hub_request_time';
const LAST_HUB_SYLIUS_VERSION = 'last_sylius_version';
const SYLIUS_VERSION_DISMISSED = 'sylius_version_dismissed';
const MILISECONDS_MULTIPLIER = 1000;
var HUB_REQUEST_TIME = 'hub_request_time';
var LAST_HUB_SYLIUS_VERSION = 'last_sylius_version';
var SYLIUS_VERSION_DISMISSED = 'sylius_version_dismissed';
var MILISECONDS_MULTIPLIER = 1000;

var notificationMenu = $('#sylius-version-notification');
var askFrequency = notificationMenu.attr('data-frequency') * MILISECONDS_MULTIPLIER;
Expand Down Expand Up @@ -65,7 +65,7 @@
}
}

function notify(/*boolean*/ bool) {
function notify(bool) {
var notificationMenu = $('#sylius-version-notification');

if (true === bool) {
Expand All @@ -83,10 +83,10 @@
return new Date().getTime() - parseInt(retrieve(HUB_REQUEST_TIME));
}

function store(/* string */ key, /* string */ value) {
function store(key, value) {
localStorage.setItem(key, value);
}
function retrieve(/* string */ key) {
function retrieve(key) {
return localStorage.getItem(key);
}
}
Expand Down
Expand Up @@ -24,9 +24,7 @@

<div class="ui right floated dividing empty item"></div>

{% if sylius_version_notifications_enabled %}
{{ sylius_render_notifications_widget() }}
{% endif %}
{{ sylius_render_notifications_widget() }}
{% include '@SyliusAdmin/_security.html.twig' %}

{{ sonata_block_render_event('sylius.admin.layout.topbar_right') }}
Expand Down
@@ -0,0 +1,108 @@
<?php

/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Sylius\Bundle\AdminBundle\Tests\Controller;

use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\ConnectException;
use Http\Message\MessageFactory;
use Prophecy\Argument;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
use Sylius\Bundle\AdminBundle\Controller\NotificationController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
* @author Jan Góralski <jan.goralski@lakion.com>
*/
final class NotificationControllerTest extends \PHPUnit_Framework_TestCase
{
/**
* @var ClientInterface
*/
private $client;

/**
* @var MessageFactory
*/
private $messageFactory;

/**
* @var NotificationController
*/
private $controller;

/**
* @var string
*/
private static $hubUri = 'www.doesnotexist.test.com';

/**
* @test
*/
public function it_returns_an_empty_json_response_upon_client_exception()
{
$this->messageFactory->createRequest(Argument::cetera())
->willReturn($this->prophesize(RequestInterface::class)->reveal())
;

$this->client->send(Argument::cetera())->willThrow(ConnectException::class);

$emptyResponse = $this->controller->getVersionAction(new Request());

$this->assertEquals(JsonResponse::HTTP_NO_CONTENT, $emptyResponse->getStatusCode());
$this->assertEquals('""', $emptyResponse->getContent());
}

/**
* @test
*/
public function it_returns_json_response_from_client_on_success()
{
$content = json_encode(['version' => '9001']);

$this->messageFactory->createRequest(Argument::cetera())
->willReturn($this->prophesize(RequestInterface::class)->reveal())
;

$stream = $this->prophesize(StreamInterface::class);
$stream->getContents()->willReturn($content);

$externalResponse = $this->prophesize(ResponseInterface::class);
$externalResponse->getBody()->willReturn($stream->reveal());

$this->client->send(Argument::cetera())->willReturn($externalResponse->reveal());

$response = $this->controller->getVersionAction(new Request());

$this->assertEquals(JsonResponse::HTTP_OK, $response->getStatusCode());
$this->assertEquals($content, $response->getContent());
}

/**
* {@inheritdoc}
*/
protected function setUp()
{
$this->client = $this->prophesize(ClientInterface::class);
$this->messageFactory = $this->prophesize(MessageFactory::class);

$this->controller = new NotificationController(
$this->client->reveal(),
$this->messageFactory->reveal(),
self::$hubUri
);

parent::setUp();
}
}
Expand Up @@ -11,12 +11,10 @@

namespace Sylius\Bundle\AdminBundle\Twig;

use Sylius\Bundle\CoreBundle\Application\Kernel;

/**
* @author Jan Góralski <jan.goralski@lakion.com>
*/
final class NotificationExtension extends \Twig_Extension implements \Twig_Extension_GlobalsInterface
final class NotificationWidgetExtension extends \Twig_Extension
{
/**
* @var bool
Expand Down Expand Up @@ -45,7 +43,7 @@ public function getFunctions()
{
return [
new \Twig_SimpleFunction(
'sylius_render_notification_widget',
'sylius_render_notifications_widget',
[$this, 'renderWidget'],
[
'needs_environment' => true,
Expand All @@ -55,26 +53,19 @@ public function getFunctions()
];
}

/**
* @return array
*/
public function getGlobals()
{
return [
'sylius_version_notification_enabled' => $this->areNotificationsEnabled,
];
}

/**
* @param \Twig_Environment $environment
*
* @return string
*/
public function renderWidget(\Twig_Environment $environment)
{
if (!$this->areNotificationsEnabled) {
return '';
}

return $environment->render('@SyliusAdmin/_notification.html.twig', [
'frequency' => $this->checkFrequency,
'version' => Kernel::VERSION,
]);
}
}
1 change: 1 addition & 0 deletions src/Sylius/Bundle/AdminBundle/composer.json
Expand Up @@ -28,6 +28,7 @@
"symfony/framework-bundle": "^3.2"
},
"require-dev": {
"phpunit/phpunit": "^5.6",
"phpspec/phpspec": "^3.2"
},
"config": {
Expand Down

0 comments on commit af6ec66

Please sign in to comment.