EngineRegistry::getEngineInstance()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 10
nc 5
nop 1
dl 0
loc 16
rs 9.6111
c 2
b 0
f 0
1
<?php
2
3
4
namespace ntentan\honam;
5
6
7
use ntentan\honam\engines\AbstractEngine;
8
use ntentan\honam\exceptions\FactoryException;
9
use ntentan\honam\exceptions\TemplateEngineNotFoundException;
10
use ntentan\honam\factories\EngineFactoryInterface;
11
12
class EngineRegistry
13
{
14
    private $extensions = [];
15
16
    public function registerEngine($extensions, $factory)
17
    {
18
        foreach($extensions as $extension) {
19
            $this->extensions[$extension] = $factory;
20
        }
21
    }
22
23
    public function getSupportedExtensions()
24
    {
25
        return array_keys($this->extensions);
26
    }
27
28
    /**
29
     * @param $templateFile
30
     * @return AbstractEngine
31
     * @throws FactoryException
32
     * @throws TemplateEngineNotFoundException
33
     */
34
    public function getEngineInstance($templateFile) : AbstractEngine
35
    {
36
        foreach($this->extensions as $extension => $factory) {
37
            if($extension == substr($templateFile, -strlen($extension))) {
38
                if(is_a($factory, EngineFactoryInterface::class)) {
39
                    $engine = $factory->create();
40
                } else if (is_callable($factory)) {
41
                    $engine = $factory();
42
                } else {
43
                    throw new FactoryException("There is no factory for creating engines for the {$extension} extension");
44
                }
45
                return $engine;
46
            }
47
        }
48
49
        throw new TemplateEngineNotFoundException("An engine for rendering the {$templateFile} extension was not found.");
50
    }
51
}
52