Completed
Pull Request — master (#4)
by James Ekow Abaka
03:06 queued 36s
created

EngineRegistry::getEngineInstance()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 6.6

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 5
nop 1
dl 0
loc 16
ccs 6
cts 10
cp 0.6
crap 6.6
rs 9.6111
c 0
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 37
    public function registerEngine($extensions, $factory)
17
    {
18 37
        foreach($extensions as $extension) {
19 37
            $this->extensions[$extension] = $factory;
20
        }
21 37
    }
22
23 29
    public function getSupportedExtensions()
24
    {
25 29
        return array_keys($this->extensions);
26
    }
27
28
    /**
29
     * @param $templateFile
30
     * @return AbstractEngine
31
     * @throws FactoryException
32
     * @throws TemplateEngineNotFoundException
33
     */
34 28
    public function getEngineInstance($templateFile) : AbstractEngine
35
    {
36 28
        foreach($this->extensions as $extension => $factory) {
37 28
            if($extension == substr($templateFile, -strlen($extension))) {
38 28
                if(is_a($factory, EngineFactoryInterface::class)) {
39 28
                    $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 28
                return $engine;
46
            }
47
        }
48
49
        throw new TemplateEngineNotFoundException("An engine for rendering the {$templateFile} extension was not found.");
50
    }
51
}
52