JsonServiceFactory::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Gr8abbasi\Container\Factory;
4
5
use Gr8abbasi\Container\Exception\NotFoundException;
6
use Gr8abbasi\Container\Exception\ContainerException;
7
8
/**
9
 * Class JsonServiceFactory
10
 */
11
class JsonServiceFactory implements ServiceFactoryInterface
12
{
13
    /**
14
     * @var array $services
15
     */
16
    private $services;
17
18
    /**
19
     * Constructor
20
     *
21
     * @param string $jsonFile
22
     *
23
     */
24
    public function __construct($jsonFile)
25
    {
26
       $this->loadServiceList($jsonFile);
27
    }
28
29
    /**
30
     * @param string $jsonFile
31
     *
32
     * @return array
33
     */
34
    private function loadJsonFile($jsonFile)
35
    {
36
        $jsonString = file_get_contents($jsonFile);
37
        return json_decode($jsonString);
38
    }
39
40
    /**
41
     * @param string $jsonFile
42
     *
43
     * @return void
44
     */
45
    private function loadServiceList($jsonFile)
46
    {
47
       $services =  $this->loadJsonFile($jsonFile);
48
49
       foreach($services->services as $service) {
50
           $this->services[$service->id] = $service;
51
       }
52
    }
53
54
    /**
55
     * @inheritdoc
56
     */
57
    public function create($service)
58
    {
59
        if(!isset($this->services[$service])) {
60
            throw new NotFoundException('Service not found: ' . $service);
61
        }
62
63
        if (!class_exists($this->services[$service]->class)) {
64
            throw new ContainerException(
65
                'Class does not exists: ' . $this->services[$service]->class
66
            );
67
        }
68
69
        $service = new \ReflectionClass($this->services[$service]->class);
70
        return $service->newInstance();
71
    }
72
}
73