Completed
Push — master ( ad7fd3...b10ab8 )
by Théo
03:40
created

ServicesBuilder   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 122
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6
Metric Value
wmc 15
lcom 1
cbo 6
dl 0
loc 122
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 2
B build() 0 23 6
A buildService() 0 18 1
A resolveArguments() 0 18 3
A bindAutowiringTypes() 0 6 2
A tagService() 0 4 1
1
<?php
2
3
/*
4
 * This file is part of the LaravelYaml package.
5
 *
6
 * (c) Théo FIDRY <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Fidry\LaravelYaml\DependencyInjection\Builder;
13
14
use Fidry\LaravelYaml\DependencyInjection\Definition\Reference;
15
use Fidry\LaravelYaml\DependencyInjection\Definition\Service;
16
use Fidry\LaravelYaml\DependencyInjection\Resolver\BaseReferenceResolver;
17
use Fidry\LaravelYaml\DependencyInjection\Resolver\BuildedParameterResolver;
18
use Fidry\LaravelYaml\DependencyInjection\Resolver\ParameterResolverInterface;
19
use Fidry\LaravelYaml\DependencyInjection\Resolver\ReferenceResolverInterface;
20
use Fidry\LaravelYaml\Exception\DependencyInjection\Exception;
21
use Fidry\LaravelYaml\Exception\DependencyInjection\Resolver\Exception as ResolverException;
22
use Fidry\LaravelYaml\Exception\ServiceNotFoundException;
23
use Illuminate\Contracts\Config\Repository as ConfigRepository;
24
use Illuminate\Contracts\Container\BindingResolutionException;
25
use Illuminate\Contracts\Foundation\Application;
26
27
/**
28
 * @author Théo FIDRY <[email protected]>
29
 */
30
final class ServicesBuilder implements BuilderInterface
31
{
32
    /**
33
     * @var array
34
     */
35
    private $parameters;
36
37
    /**
38
     * @var ReferenceResolverInterface
39
     */
40
    private $referenceResolver;
41
42
    /**
43
     * @var Service[]
44
     */
45
    private $services;
46
47
    /**
48
     * @var ParameterResolverInterface|null
49
     */
50
    private $parameterResolver;
51
52
    /**
53
     * @param Service[]                       $services
54
     * @param array                           $parameters
55
     * @param ParameterResolverInterface|null $parameterResolver
56
     * @param ReferenceResolverInterface|null $referenceResolver
57
     */
58
    public function __construct(
59
        array $services,
60
        array $parameters,
61
        ParameterResolverInterface $parameterResolver = null,
62
        ReferenceResolverInterface $referenceResolver = null
63
    ) {
64
        $this->services = $services;
65
        $this->parameters = $parameters;
66
        $this->parameterResolver = $parameterResolver;
67
        $this->referenceResolver = (null === $referenceResolver) ? new BaseReferenceResolver() : $referenceResolver;
68
    }
69
70
    public function build(Application $application)
71
    {
72
73
        try {
74
            $config = $application->make(ConfigRepository::class);
75
            $parameterResolver = (null === $this->parameterResolver)
76
                ? new BuildedParameterResolver($this->parameters, $config)
77
                : $this->parameterResolver
78
            ;
79
80
            foreach ($this->services as $service) {
81
                $this->buildService($service, $parameterResolver, $application);
0 ignored issues
show
Compatibility introduced by
$parameterResolver of type object<Fidry\LaravelYaml...meterResolverInterface> is not a sub-type of object<Fidry\LaravelYaml...ildedParameterResolver>. It seems like you assume a concrete implementation of the interface Fidry\LaravelYaml\Depend...ameterResolverInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
82
            }
83
84
            return $this->parameters;
85
        } catch (BindingResolutionException $exception) {
86
            throw new Exception(sprintf('Could not load "%s" class', ConfigRepository::class), 0, $exception);
87
        } catch (ResolverException $exception) {
88
            throw new Exception('Could not resolve the parameters', 0, $exception);
89
        } catch (\Exception $exception) {
90
            throw new Exception('Could not build the parameters', 0, $exception);
91
        }
92
    }
93
94
    private function buildService(
95
        Service $service,
96
        BuildedParameterResolver $parameterResolver,
97
        Application $application
98
    ) {
99
        $application->singleton(
100
            $service->getName(),
101
            function (Application $app) use ($service, $parameterResolver) {
102
                $constructor = $service->getClass();
103
                $resolvedArguments = $this->resolveArguments($service, $parameterResolver, $app);
104
105
                return new $constructor(...$resolvedArguments);
106
            }
107
        );
108
        $application->bind($service->getClass(), $service->getName());
109
        $this->bindAutowiringTypes($service, $application);
110
        $this->tagService($service, $application);
111
    }
112
113
    /**
114
     * @param Service                  $service
115
     * @param BuildedParameterResolver $parameterResolver
116
     * @param Application              $application
117
     *
118
     * @return array
119
     * @throws ServiceNotFoundException
120
     */
121
    private function resolveArguments(
122
        Service $service,
123
        BuildedParameterResolver $parameterResolver,
124
        Application $application
125
    ) {
126
        $resolvedArguments = [];
127
        foreach ($service->getArguments() as $argument) {
0 ignored issues
show
Bug introduced by
The expression $service->getArguments() of type array<integer,object<Fid...inition\Argument>>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
128
            if ($argument instanceof Reference) {
129
                $resolvedArguments[] = $this->referenceResolver->resolve($argument, $application);
130
131
                continue;
132
            }
133
134
            $resolvedArguments[] = $parameterResolver->resolve($argument);
135
        }
136
137
        return $resolvedArguments;
138
    }
139
140
    private function bindAutowiringTypes(Service $service, Application $application)
141
    {
142
        foreach ($service->getAutowiringTypes() as $binding) {
143
            $application->bind($binding, $service->getName());
144
        }
145
    }
146
147
    private function tagService(Service $service, Application $application)
148
    {
149
        $application->tag($service->getName(), array_keys($service->getTags()));
150
    }
151
}
152