Passed
Push — master ( fe64ef...2e5fa1 )
by Ivan
02:01
created

FlashMessages::mutate()   A

Complexity

Conditions 3
Paths 6

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 12
nc 6
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Everlution\AjaxcomBundle\Mutation;
6
7
use Everlution\Ajaxcom\Handler;
8
use Everlution\AjaxcomBundle\AjaxcomException;
9
use Everlution\AjaxcomBundle\Service\RenderBlock;
10
use Symfony\Component\HttpFoundation\Session\Session;
11
12
/**
13
 * Class FlashMessages.
14
 *
15
 * @author Ivan Barlog <[email protected]>
16
 */
17
class FlashMessages implements MutatorInterface
18
{
19
    /** @var RenderBlock */
20
    private $renderBlock;
21
    /** @var Session */
22
    private $session;
23
    /** @var string */
24
    private $flashesTemplate;
25
    /** @var string */
26
    private $flashesBlockId;
27
28
    public function __construct(RenderBlock $renderBlock, Session $session, string $flashesTemplate, string $flashesBlockId)
29
    {
30
        $this->renderBlock = $renderBlock;
31
        $this->session = $session;
32
        $this->flashesTemplate = $flashesTemplate;
33
        $this->flashesBlockId = $flashesBlockId;
34
    }
35
36
    public function mutate(Handler $ajax): Handler
37
    {
38
        $flashBag = $this->session->getFlashBag();
39
40
        if (empty($flashBag->peekAll())) {
41
            return $ajax;
42
        }
43
44
        try {
45
            $messages = $this->renderBlock->render(
46
                $this->flashesTemplate,
47
                $this->flashesBlockId,
48
                ['flashes' => $flashBag->all()]
49
            );
50
            $ajax->container("#$this->flashesBlockId")->html($messages);
51
        } catch (AjaxcomException $exception) {
52
            // do nothing
53
        } finally {
54
            return $ajax;
55
        }
56
    }
57
}
58