Passed
Push — master ( e98e31...880950 )
by Bruno
06:29
created

Element::factory()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 10
c 1
b 0
f 1
nc 4
nop 2
dl 0
loc 15
rs 9.9332
1
<?php declare(strict_types=1);
2
3
namespace Formularium;
4
5
use Formularium\Exception\ClassNotFoundException;
6
use Formularium\HTMLNode;
7
8
/**
9
 * Abstract base classe to render HTML elements such as buttons.
10
 */
11
abstract class Element implements RenderableParameter
12
{
13
    /**
14
     * Factory.
15
     *
16
     * @param string $elementName
17
     * @param Framework $framework
18
     * @return Element
19
     */
20
    public static function factory(string $elementName, Framework $framework): Element
21
    {
22
        // TODO: use reflection like Datatype
23
        $frameworkClassname = get_class($framework);
24
        $lastpos = strrpos($frameworkClassname, '\\');
25
        if ($lastpos === false) {
26
            $ns = '';
27
        } else {
28
            $ns = '\\' . substr($frameworkClassname, 0, $lastpos);
29
        }
30
        $class = "$ns\\Element\\$elementName";
31
        if (!class_exists($class)) {
32
            throw new ClassNotFoundException("Invalid element $elementName for {$framework->getName()}");
33
        }
34
        return new $class($framework);
35
    }
36
37
    /**
38
     * @var Framework
39
     */
40
    protected $framework;
41
42
    public function __construct(Framework $framework)
43
    {
44
        $this->framework = $framework;
45
    }
46
47
    /**
48
     * Renders a form editable version of this Element
49
     *
50
     * @param array $parameters
51
     * @param HTMLNode $previous
52
     * @return HTMLNode The HTML rendered.
53
     */
54
    abstract public function render(array $parameters, HTMLNode $previous): HTMLNode;
55
}
56