Completed
Pull Request — master (#8)
by Jeremy
06:38 queued 04:13
created

Preparation   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 172
Duplicated Lines 8.14 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 1 Features 3
Metric Value
wmc 20
c 4
b 1
f 3
lcom 1
cbo 8
dl 14
loc 172
ccs 87
cts 87
cp 1
rs 10

9 Methods

Rating   Name   Duplication   Size   Complexity  
A prepare() 0 5 1
B createBlind() 0 24 3
A createExperiments() 0 12 3
A createMethodExperiment() 7 22 3
A createPropertyExperiment() 7 22 3
A createPropertyCallable() 0 14 2
A createMissingPropertyCallable() 0 6 1
A createMissingMethodCallable() 0 6 1
A addInterfaceMethods() 0 18 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
4
namespace Scientist\Blind;
5
6
use ReflectionClass;
7
use ReflectionProperty;
8
use Scientist\Blind;
9
use Scientist\Experiment;
10
use Scientist\SideEffects\MissingMethod;
11
use Scientist\SideEffects\MissingProperty;
12
use Scientist\Study;
13
use Zend\Code\Generator\ClassGenerator;
14
use Zend\Code\Generator\MethodGenerator;
15
use Zend\Code\Reflection\ClassReflection;
16
17
class Preparation
18
{
19
    /**
20
     * @param Study $study
21
     * @param mixed $control
22
     * @param mixed[] $trials
23
     * @param string[] $interfaces that blind should satisfy
24
     * @return Blind
25
     */
26 10
    public function prepare(Study $study, $control, array $trials, array $interfaces = [])
27
    {
28 10
        $experiments = $this->createExperiments($study, $control, $trials);
29 10
        return $this->createBlind($study, $control, $experiments, $interfaces);
30
    }
31
32
    /**
33
     * @param $study
34
     * @param mixed $control
35
     * @param Experiment[] $experiments
36
     * @param string[] $interfaces
37
     * @return Blind
38
     */
39 10
    private function createBlind($study, $control, array $experiments, array $interfaces = [])
0 ignored issues
show
Unused Code introduced by
The parameter $control is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
40
    {
41 10
        $blind_name = sprintf("Blind_%s", str_replace('.', '', uniqid('', true)));
42
43 10
        array_push($interfaces, Blind::class);
44
45 10
        foreach ($interfaces as &$interface) {
46 10
            if (strpos($interface, '\\') !== 0) {
47 10
                $interface = '\\'.$interface;
48 10
            }
49 10
        }
50
51 10
        $generator = new ClassGenerator($blind_name, 'Scientist\Blind');
52 10
        $generator->setImplementedInterfaces($interfaces);
53 10
        $generator->addTrait('\\'.DecoratorTrait::class);
54
55 10
        $this->addInterfaceMethods($generator, $interfaces);
56
57 10
        $code = $generator->generate();
58 10
        eval($code);
0 ignored issues
show
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
59
60 10
        $class_name = sprintf('Scientist\Blind\%s', $blind_name);
61 10
        return new $class_name($study, $experiments);
62
    }
63
64
    /**
65
     * @param $study
66
     * @param $control
67
     * @param array $trials
68
     * @return array
69
     */
70 10
    private function createExperiments(Study $study, $control, array $trials)
71 1
    {
72 10
        $experiments = [];
73 10
        $reflection = new ReflectionClass($control);
74 10
        foreach ($reflection->getMethods() as $method) {
75 10
            $experiments[] = $this->createMethodExperiment($method->getName(), $study, $control, $trials);
0 ignored issues
show
Bug introduced by
Consider using $method->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
76 10
        }
77 10
        foreach ($reflection->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
78 10
            $experiments[] = $this->createPropertyExperiment($property->getName(), $study, $control, $trials);
79 10
        }
80 10
        return $experiments;
81
    }
82
83
    /**
84
     * @param string $name
85
     * @param Study $study
86
     * @param mixed $control
87
     * @param mixed[] $trials
88
     * @return Experiment
89
     */
90 10
    private function createMethodExperiment($name, Study $study, $control, array $trials)
91
    {
92 10
        $experiment_name = sprintf('%s::%s', $study->getName(), $name);
93
        /** @var Experiment $experiment */
94 10
        $experiment = $study->getLaboratory()
95 10
            ->experiment($experiment_name);
96
97 10
        $experiment->control([$control, $name]);
98
99 10 View Code Duplication
        foreach ($trials as $trial_name => $trial) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
100 10
            if (method_exists($trial, $name)) {
101 8
                $experiment->trial($trial_name, [$trial, $name]);
102 8
            } else {
103 2
                $experiment->trial($trial_name, $this->createMissingMethodCallable($trial, $name));
104
            }
105 10
        }
106
107 10
        $experiment->matcher($study->getMatcher());
108 10
        $experiment->chance($study->getChance());
109 10
        $study->addExperiment($experiment);
110 10
        return $experiment;
111
    }
112
113 10
    private function createPropertyExperiment($name, Study $study, $control, array $trials)
114
    {
115 10
        $experiment_name = sprintf('%s::$%s', $study->getName(), $name);
116
        /** @var Experiment $experiment */
117 10
        $experiment = $study->getLaboratory()
118 10
            ->experiment($experiment_name);
119
120 10
        $experiment->control($this->createPropertyCallable($control, $name));
121
122 10 View Code Duplication
        foreach ($trials as $trial_name => $trial) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
123 10
            if (property_exists($trial, $name)) {
124 7
                $experiment->trial($trial_name, $this->createPropertyCallable($trial, $name));
125 7
            } else {
126 3
                $experiment->trial($trial_name, $this->createMissingPropertyCallable($trial, $name));
127
            }
128 10
        }
129
130 10
        $experiment->matcher($study->getMatcher());
131 10
        $experiment->chance($study->getChance());
132 10
        $study->addExperiment($experiment);
133 10
        return $experiment;
134
    }
135
136
    /**
137
     * @param mixed $instance
138
     * @param string $name
139
     * @return callable
140
     */
141 10
    private function createPropertyCallable($instance, $name)
142
    {
143
        return function () use ($instance, $name) {
144 3
            $args = func_get_args();
145
            // __set
146 3
            if (count($args) > 1) {
147 2
                list($name, $value) = $args;
148 2
                return $instance->{$name} = $value;
149
            }
150
            // __get
151 1
            $name = $args[0];
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $name, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
152 1
            return $instance->{$name};
153 10
        };
154
    }
155
156 3
    private function createMissingPropertyCallable($instance, $name)
157
    {
158
        return function () use ($instance, $name) {
159 2
            throw new MissingProperty($instance, $name);
160 3
        };
161
    }
162
163
    private function createMissingMethodCallable($instance, $name)
164
    {
165 2
        return function () use ($instance, $name) {
166 1
            throw new MissingMethod($instance, $name);
167 2
        };
168
    }
169
170 10
    private function addInterfaceMethods(Classgenerator $classGenerator, array $interfaces)
171
    {
172
        $template = <<<'PHP'
173 1
    $arguments = func_get_args();
174
    $experiment = $this->getExperiment($this->getExperimentNameForMethod('%s'));
175
    return call_user_func_array([$experiment, 'run'], $arguments);
176 10
PHP;
177
178 10
        foreach ($interfaces as $interface) {
179 10
            $reflection = new ClassReflection($interface);
180 10
            foreach ($reflection->getMethods() as $method) {
181 3
                $generator = MethodGenerator::fromReflection($method);
182 3
                $generator->setInterface(false);
183 3
                $generator->setBody(sprintf($template, $method->getName()));
0 ignored issues
show
Bug introduced by
Consider using $method->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
184 3
                $classGenerator->addMethodFromGenerator($generator);
185 10
            }
186 10
        }
187 10
    }
188
}
189