Completed
Push — master ( 5aa8b4...39ef33 )
by Arman
20s queued 16s
created

ServiceFactory   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
dl 0
loc 53
rs 10
c 1
b 0
f 0
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 8 3
A get() 0 9 2
A create() 0 5 1
1
<?php
2
3
/**
4
 * Quantum PHP Framework
5
 *
6
 * An open source software development framework for PHP
7
 *
8
 * @package Quantum
9
 * @author Arman Ag. <[email protected]>
10
 * @copyright Copyright (c) 2018 Softberg LLC (https://softberg.org)
11
 * @link http://quantum.softberg.org/
12
 * @since 2.9.7
13
 */
14
15
namespace Quantum\Service\Factories;
16
17
use Quantum\Service\Exceptions\ServiceException;
18
use Quantum\Di\Exceptions\DiException;
19
use Quantum\Service\QtService;
20
use ReflectionException;
21
use Quantum\Di\Di;
22
23
/**
24
 * Class ServiceFactory
25
 * @package Quantum\Service
26
 */
27
class ServiceFactory
28
{
29
30
    /**
31
     * Creates and initiates the service once
32
     * @param string $serviceClass
33
     * @param array $args
34
     * @return QtService
35
     * @throws DiException
36
     * @throws ServiceException
37
     * @throws ReflectionException
38
     */
39
    public static function get(string $serviceClass, array $args = []): QtService
40
    {
41
        self::validate($serviceClass);
42
43
        if (!Di::isRegistered($serviceClass)) {
44
            Di::register($serviceClass);
45
        }
46
47
        return Di::get($serviceClass, $args);
48
    }
49
50
    /**
51
     * Creates new service instance
52
     * @param string $serviceClass
53
     * @param array $args
54
     * @return QtService
55
     * @throws DiException
56
     * @throws ReflectionException
57
     * @throws ServiceException
58
     */
59
    public static function create(string $serviceClass, array $args = []): QtService
60
    {
61
        self::validate($serviceClass);
62
63
        return Di::create($serviceClass, $args);
64
    }
65
66
    /**
67
     * Validates the service class
68
     * @param string $serviceClass
69
     * @return void
70
     * @throws ServiceException
71
     */
72
    private static function validate(string $serviceClass): void
73
    {
74
        if (!class_exists($serviceClass)) {
75
            throw ServiceException::serviceNotFound($serviceClass);
76
        }
77
78
        if (!is_subclass_of($serviceClass, QtService::class)) {
79
            throw ServiceException::notServiceInstance([$serviceClass, QtService::class]);
80
        }
81
    }
82
}