ProviderChain::__call()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 5
nop 2
dl 0
loc 14
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
namespace Sugarcrm\UpgradeSpec\Data;
4
5
use Sugarcrm\UpgradeSpec\Data\Exception\WrongProviderException;
6
use Sugarcrm\UpgradeSpec\Data\Provider\ProviderInterface;
7
8
/**
9
 * @method mixed getVersions($flav)
10
 * @method mixed getReleaseNotes($flav, array $versions)
11
 * @method mixed getHealthCheckInfo($version)
12
 * @method mixed getUpgraderInfo($version)
13
 */
14
class ProviderChain
15
{
16
    /**
17
     * @var array
18
     */
19
    private $providers = [];
20
21
    /**
22
     * ProviderChain constructor.
23
     *
24
     * @param mixed $providers
25
     */
26
    public function __construct($providers)
27
    {
28
        $this->addProviders($providers);
29
    }
30
31
    /**
32
     * @param $name
33
     * @param $arguments
34
     *
35
     * @return mixed
36
     */
37
    public function __call($name, $arguments)
38
    {
39
        foreach ($this->providers as $provider) {
40
            try {
41
                if (method_exists($provider, $name)) {
42
                    return call_user_func_array([$provider, $name], $arguments);
43
                }
44
            } catch (WrongProviderException $e) {
45
                continue;
46
            }
47
        }
48
49
        throw new \RuntimeException(sprintf('There is no provider with method: %s', $name));
50
    }
51
52
    /**
53
     * Adds providers to the chain.
54
     *
55
     * @param mixed $providers
56
     */
57 View Code Duplication
    public function addProviders($providers)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
58
    {
59
        if (!is_array($providers) && !$providers instanceof \Traversable) {
60
            throw new \InvalidArgumentException(sprintf('Argument is not traversable: %s', $providers));
61
        }
62
63
        $providers = is_array($providers) ? $providers : iterator_to_array($providers);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $providers. This often makes code more readable.
Loading history...
64
65
        foreach ($providers as $provider) {
66
            if (!is_a($provider, ProviderInterface::class)) {
67
                throw new \InvalidArgumentException('ProviderChain expects ProviderInterface[]');
68
            }
69
        }
70
71
        $this->providers = array_merge($this->providers, $providers);
72
    }
73
}
74