Completed
Pull Request — master (#1219)
by Maciej
24:36
created

getParameterNamesForDecoratedCall()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 19
rs 9.4285
cc 3
eloc 10
nc 1
nop 1
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Doctrine\ODM\MongoDB\PersistentCollection;
21
22
use Doctrine\ODM\MongoDB\Configuration;
23
24
/**
25
 * Default generator for custom PersistentCollection classes.
26
 *
27
 * @since 1.1
28
 */
29
final class DefaultPersistentCollectionGenerator implements PersistentCollectionGenerator
30
{
31
    /**
32
     * The namespace that contains all persistent collection classes.
33
     *
34
     * @var string
35
     */
36
    private $collectionNamespace;
37
38
    /**
39
     * The directory that contains all persistent collection classes.
40
     *
41
     * @var string
42
     */
43
    private $collectionDir;
44
45
    /**
46
     * @param string $collectionDir
47
     * @param string $collectionNs
48
     */
49
    public function __construct($collectionDir, $collectionNs)
50
    {
51
        $this->collectionDir = $collectionDir;
52
        $this->collectionNamespace = $collectionNs;
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function generateClass($class, $dir)
59
    {
60
        $collClassName = str_replace('\\', '', $class) . 'Persistent';
61
        $className = $this->collectionNamespace . '\\' . $collClassName;
62
        $fileName = $dir . DIRECTORY_SEPARATOR . $collClassName . '.php';
63
        $this->generateCollectionClass($class, $className, $fileName);
64
    }
65
66
    /**
67
     * {@inheritdoc}
68
     */
69
    public function loadClass($collectionClass, $autoGenerate)
70
    {
71
        // These checks are not in __construct() because of BC and should be moved for 2.0
72
        if ( ! $this->collectionDir) {
73
            throw PersistentCollectionException::directoryRequired();
74
        }
75
        if ( ! $this->collectionNamespace) {
76
            throw PersistentCollectionException::namespaceRequired();
77
        }
78
79
        $collClassName = str_replace('\\', '', $collectionClass) . 'Persistent';
80
        $className = $this->collectionNamespace . '\\' . $collClassName;
81 View Code Duplication
        if ( ! class_exists($className, false)) {
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...
82
            $fileName = $this->collectionDir . DIRECTORY_SEPARATOR . $collClassName . '.php';
83
            switch ($autoGenerate) {
84
                case Configuration::AUTOGENERATE_NEVER:
85
                    require $fileName;
86
                    break;
87
88
                case Configuration::AUTOGENERATE_ALWAYS:
89
                    $this->generateCollectionClass($collectionClass, $className, $fileName);
90
                    require $fileName;
91
                    break;
92
93
                case Configuration::AUTOGENERATE_FILE_NOT_EXISTS:
94
                    if ( ! file_exists($fileName)) {
95
                        $this->generateCollectionClass($collectionClass, $className, $fileName);
96
                    }
97
                    require $fileName;
98
                    break;
99
100
                case Configuration::AUTOGENERATE_EVAL:
101
                    $this->generateCollectionClass($collectionClass, $className, false);
102
                    break;
103
            }
104
        }
105
106
        return $className;
107
    }
108
109
    private function generateCollectionClass($for, $targetFqcn, $fileName)
110
    {
111
        $exploded = explode('\\', $targetFqcn);
112
        $class = array_pop($exploded);
113
        $namespace = join('\\', $exploded);
114
        $code = <<<CODE
115
<?php
116
117
namespace $namespace;
118
119
use Doctrine\Common\Collections\Collection as BaseCollection;
120
use Doctrine\ODM\MongoDB\DocumentManager;
121
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
122
use Doctrine\ODM\MongoDB\MongoDBException;
123
use Doctrine\ODM\MongoDB\UnitOfWork;
124
use Doctrine\ODM\MongoDB\Utility\CollectionHelper;
125
126
/**
127
 * DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE\'S PERSISTENT COLLECTION GENERATOR
128
 */
129
class $class extends \\$for implements \\Doctrine\\ODM\\MongoDB\\PersistentCollection\\PersistentCollectionInterface
130
{
131
    use \\Doctrine\\ODM\\MongoDB\\PersistentCollection\\PersistentCollectionTrait;
132
133
    /**
134
     * @param BaseCollection \$coll
135
     * @param DocumentManager \$dm
136
     * @param UnitOfWork \$uow
137
     */
138
    public function __construct(BaseCollection \$coll, DocumentManager \$dm, UnitOfWork \$uow)
139
    {
140
        \$this->coll = \$coll;
141
        \$this->dm = \$dm;
142
        \$this->uow = \$uow;
143
    }
144
145
CODE;
146
        $rc = new \ReflectionClass($for);
147
        $rt = new \ReflectionClass('Doctrine\\ODM\\MongoDB\\PersistentCollection\\PersistentCollectionTrait');
148
        foreach ($rc->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
149
            if (
150
                $rt->hasMethod($method->name) ||
151
                $method->isConstructor() ||
152
                $method->isFinal() ||
153
                $method->isStatic()
154
            ) {
155
                continue;
156
            }
157
            $code .= $this->generateMethod($method);
158
        }
159
        $code .= "}\n";
160
161
        if ($fileName === false) {
162
            if ( ! class_exists($targetFqcn)) {
163
                eval(substr($code, 5));
164
            }
165 View Code Duplication
        } else {
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...
166
            $parentDirectory = dirname($fileName);
167
168
            if ( ! is_dir($parentDirectory) && (false === @mkdir($parentDirectory, 0775, true))) {
169
                throw PersistentCollectionException::directoryNotWritable();
170
            }
171
172
            if ( ! is_writable($parentDirectory)) {
173
                throw PersistentCollectionException::directoryNotWritable();
174
            }
175
176
            $tmpFileName = $fileName . '.' . uniqid('', true);
177
            file_put_contents($tmpFileName, $code);
178
            rename($tmpFileName, $fileName);
179
        }
180
    }
181
182
    private function generateMethod(\ReflectionMethod $method)
183
    {
184
        $parametersString = $this->buildParametersString($method);
185
        $callParamsString = implode(', ', $this->getParameterNamesForDecoratedCall($method->getParameters()));
186
187
        $method = <<<CODE
188
189
    /**
190
     * {@inheritDoc}
191
     */
192
    public function {$method->name}($parametersString)
193
    {
194
        \$this->initialize();
195
        return \$this->coll->{$method->name}($callParamsString);
196
    }
197
198
CODE;
199
        return $method;
200
    }
201
202
    /**
203
     * @param \ReflectionMethod $method
204
     *
205
     * @return string
206
     */
207
    private function buildParametersString(\ReflectionMethod $method)
208
    {
209
        $parameters = $method->getParameters();
210
        $parameterDefinitions = array();
211
212
        /* @var $param \ReflectionParameter */
213
        foreach ($parameters as $param) {
214
            $parameterDefinition = '';
215
216
            if ($parameterType = $this->getParameterType($param)) {
0 ignored issues
show
Bug introduced by
It seems like $param defined by $param on line 213 can also be of type string; however, Doctrine\ODM\MongoDB\Per...tor::getParameterType() does only seem to accept object<ReflectionParameter>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
217
                $parameterDefinition .= $parameterType . ' ';
218
            }
219
220
            if ($param->isPassedByReference()) {
221
                $parameterDefinition .= '&';
222
            }
223
224
            if (method_exists($param, 'isVariadic')) {
225
                if ($param->isVariadic()) {
226
                    $parameterDefinition .= '...';
227
                }
228
            }
229
230
            $parameters[]     = '$' . $param->name;
231
            $parameterDefinition .= '$' . $param->name;
232
233
            if ($param->isDefaultValueAvailable()) {
234
                $parameterDefinition .= ' = ' . var_export($param->getDefaultValue(), true);
235
            }
236
237
            $parameterDefinitions[] = $parameterDefinition;
238
        }
239
240
        return implode(', ', $parameterDefinitions);
241
    }
242
243
    /**
244
     * @param \ReflectionParameter $parameter
245
     *
246
     * @return string|null
247
     */
248
    private function getParameterType(\ReflectionParameter $parameter)
249
    {
250
        // We need to pick the type hint class too
251
        if ($parameter->isArray()) {
252
            return 'array';
253
        }
254
255
        if (method_exists($parameter, 'isCallable') && $parameter->isCallable()) {
256
            return 'callable';
257
        }
258
259
        try {
260
            $parameterClass = $parameter->getClass();
261
262
            if ($parameterClass) {
263
                return '\\' . $parameterClass->name;
264
            }
265
        } catch (\ReflectionException $previous) {
266
            // @todo ProxyGenerator throws specialized exceptions
267
            throw $previous;
268
        }
269
270
        return null;
271
    }
272
273
    /**
274
     * @param \ReflectionParameter[] $parameters
275
     *
276
     * @return string[]
277
     */
278
    private function getParameterNamesForDecoratedCall(array $parameters)
279
    {
280
        return array_map(
281
            function (\ReflectionParameter $parameter) {
282
                $name = '';
283
284
                if (method_exists($parameter, 'isVariadic')) {
285
                    if ($parameter->isVariadic()) {
286
                        $name .= '...';
287
                    }
288
                }
289
290
                $name .= '$' . $parameter->name;
291
292
                return $name;
293
            },
294
            $parameters
295
        );
296
    }
297
}
298