HelperAwareView::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 6
rs 10
c 1
b 0
f 0
ccs 0
cts 3
cp 0
crap 2
1
<?php
2
declare(strict_types = 1);
3
4
namespace Phauthentic\Presentation\View;
5
6
use Psr\Container\ContainerInterface;
7
use RuntimeException;
8
9
/**
10
 * Helper Aware View
11
 *
12
 * Some MVC Frameworks implement "view helpers". Objects that can be accessed
13
 * in the view layer to fulfill some view specific tasks that aren't application
14
 * logic.
15
 *
16
 * This class is simple extension to the default view object that takes a
17
 * PSR compatible container object from which we retrieve helper objects
18
 * through php's magic __get().
19
 */
20
class HelperAwareView extends View implements HelperAwareViewInterface
21
{
22
    /**
23
     * View Helper Container
24
     *
25
     * @var \Psr\Container\ContainerInterface;
26
     */
27
    protected $helpers;
28
29
    /**
30
     * Container namespace prefix
31
     *
32
     * @var string
33
     */
34
    protected $containerNamespacePrefix = '';
35
36
    /**
37
     * Constructor
38
     *
39
     * @param \Psr\Container\ContainerInterface $services
40
     */
41
    public function __construct(
42
        ContainerInterface $services,
43
        string $containerNamespacePrefix = ''
44
    ) {
45
        $this->helpers = $services;
46
        $this->containerNamespacePrefix = $containerNamespacePrefix;
47
    }
48
49
    /**
50
     * Gets the helper service container
51
     *
52
     * @return \Psr\Container\ContainerInterface
53
     */
54
    public function helpers(): ContainerInterface
55
    {
56
        return $this->helpers;
57
    }
58
59
    /**
60
     * Magic getter
61
     *
62
     * @param string $name Name
63
     * @return mixed
64
     */
65
    public function __get($name)
66
    {
67
        if (!$this->helpers->has($name)) {
68
            return;
69
        }
70
71
        $helper = $this->helpers()->get($this->containerNamespacePrefix . $name);
72
73
        if ($helper instanceof ViewAwareInterface) {
74
            $helper->setView($this);
75
        }
76
77
        if (!is_object($helper)) {
78
            throw new RuntimeException(sprintf('%s is not an object, %s given', $name, gettype($helper)));
79
        }
80
81
        return $helper;
82
    }
83
}
84