Completed
Push — 8.x-1.x ( 411616...2574ac )
by
unknown
20:15
created

NodeParamConverter::getNode()   B

Complexity

Conditions 7
Paths 3

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 7

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 18
ccs 10
cts 10
cp 1
rs 8.2222
cc 7
eloc 11
nc 3
nop 2
crap 7
1
<?php
2
3
namespace Drupal\controller_annotations\Request\ParamConverter;
4
5
use Drupal\Core\Entity\EntityTypeManagerInterface;
6
use Drupal\node\Entity\Node;
7
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
8
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
11
12
class NodeParamConverter implements ParamConverterInterface
13
{
14
    /**
15
     * @var EntityTypeManagerInterface
16
     */
17
    private $entityTypeManager;
18
19
    /**
20
     * @param EntityTypeManagerInterface $entityTypeManager
21
     */
22 12
    public function __construct(EntityTypeManagerInterface $entityTypeManager)
23
    {
24 12
        $this->entityTypeManager = $entityTypeManager;
25 12
    }
26
27
    /**
28
     * @param Request $request
29
     * @param ParamConverter $configuration
30
     * @return bool
31
     */
32 5
    public function apply(Request $request, ParamConverter $configuration)
33
    {
34 5
        $param = $configuration->getName();
35 5
        if (!$request->attributes->has($param)) {
36 1
            return false;
37
        }
38
39 4
        $value = $request->attributes->get($param);
40
41 4
        $request->attributes->set($param, $this->getNode($value, $configuration));
42 3
    }
43
44
    /**
45
     * @param string $value
46
     * @param ParamConverter $configuration
47
     * @return \Drupal\Core\Entity\EntityInterface|null
48
     */
49 4
    protected function getNode($value, ParamConverter $configuration)
50
    {
51 4
        $options = $configuration->getOptions();
52 4
        $node = $this->entityTypeManager->getStorage('node')->load($value);
53
54
        if (
55 4
            (is_null($node) && false === $configuration->isOptional())
56 4
            || (!is_null($node) && isset($options['bundle']) && $node->bundle() !== $options['bundle'])
57
        ) {
58 1
            $class = 'node';
59 1
            if (isset($options['bundle'])) {
60 1
                $class = $options['bundle'];
61
            }
62 1
            throw new NotFoundHttpException(sprintf('%s not found.', $class));
63
        }
64
65 3
        return $node;
66
    }
67
68
    /**
69
     * @param ParamConverter $configuration
70
     * @return bool
71
     */
72 7
    public function supports(ParamConverter $configuration)
73
    {
74 7
        return Node::class === $configuration->getClass();
75
    }
76
}
77