ContentResolver::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
namespace Axstrad\Bundle\ContentBundle\Resolver;
3
4
use Axstrad\Bundle\ContentBundle\Exception\InvalidContentReferenceException;
5
use Axstrad\Bundle\ContentBundle\Model\Content;
6
use Axstrad\Bundle\ContentBundle\Repository\ContentRepository;
7
use PhpOption\Option;
8
9
/**
10
 * Axstrad\Bundle\ContentBundle\Resolver\ContentResolver
11
 */
12
class ContentResolver
13
{
14
    /**
15
     * @var Content
16
     */
17
    protected $content = null;
18
19
    /**
20
     * @var ContentRepository
21
     */
22
    protected $repo;
23
24
    public function __construct(ContentRepository $repo)
25
    {
26
        $this->repo = $repo;
27
    }
28
29
    /**
30
     * @param array|\ArrayAccess $context
31
     * @param null|string|Content $content
32
     * @return self
33
     * @throws InvalidContentReferenceException If $content is a string, but not
34
     *         a valid content reference.
35
     */
36
    public function resolveFromContext($context, $content = null)
37
    {
38
        if (null === $content) {
39
            $content = isset($context['axstrad_content'])
40
                ? $context['axstrad_content']
41
                : null;
42
        }
43
44
        if (is_string($content) &&
45
            (null === $this->content || $this->content->getReference() != $content)
46
        ) {
47
            $content = $this->repo->findByReference($content)->getOrThrow(
48
                InvalidContentReferenceException::create($content)
49
            );
50
        }
51
52
        if ($content instanceof Content) {
53
            $this->content = $content;
54
        }
55
56
        return $this;
57
    }
58
59
    /**
60
     * @return Option The current Content
61
     */
62
    public function getContent()
63
    {
64
        return Option::fromValue($this->content);
65
    }
66
}
67