JsonServiceFactory   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 7
c 2
b 1
f 0
lcom 1
cbo 2
dl 0
loc 62
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A loadJsonFile() 0 5 1
A loadServiceList() 0 8 2
A __construct() 0 4 1
A create() 0 15 3
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