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

ParametersBuilder::build()   B

Complexity

Conditions 6
Paths 27

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
c 2
b 0
f 2
dl 0
loc 23
rs 8.5906
cc 6
eloc 16
nc 27
nop 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\Resolver\BaseParametersResolver;
15
use Fidry\LaravelYaml\DependencyInjection\Resolver\ParametersResolverInterface;
16
use Fidry\LaravelYaml\Exception\DependencyInjection\Exception;
17
use Fidry\LaravelYaml\Exception\DependencyInjection\Resolver\Exception as ResolverException;
18
use Illuminate\Contracts\Config\Repository as ConfigRepository;
19
use Illuminate\Contracts\Container\BindingResolutionException;
20
use Illuminate\Contracts\Foundation\Application;
21
22
/**
23
 * @author Théo FIDRY <[email protected]>
24
 */
25
final class ParametersBuilder implements BuilderInterface
26
{
27
    /**
28
     * @var array
29
     */
30
    private $parameters;
31
32
    /**
33
     * @var ParametersResolverInterface|null
34
     */
35
    private $resolver;
36
37
    /**
38
     * @param array                            $parameters
39
     * @param ParametersResolverInterface|null $resolver
40
     */
41
    public function __construct(array $parameters, ParametersResolverInterface $resolver = null)
42
    {
43
        $this->parameters = $parameters;
44
        $this->resolver = $resolver;
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     *
50
     * @return array
51
     */
52
    public function build(Application $application)
53
    {
54
        try {
55
            $configRepository = $application->make(ConfigRepository::class);
56
            $resolver = (null === $this->resolver)
57
                ? new BaseParametersResolver($configRepository)
58
                : $this->resolver
59
            ;
60
61
            $parameters = $resolver->resolve($this->parameters);
62
            foreach ($parameters as $key => $value) {
63
                $application->bind($key, $value);
64
            }
65
66
            return $this->parameters;
67
        } catch (BindingResolutionException $exception) {
68
            throw new Exception(sprintf('Could not load "%s" class', ConfigRepository::class), 0, $exception);
69
        } catch (ResolverException $exception) {
70
            throw new Exception('Could not resolve the parameters', 0, $exception);
71
        } catch (\Exception $exception) {
72
            throw new Exception('Could not build the parameters', 0, $exception);
73
        }
74
    }
75
}
76