Completed
Push — release/3.0.0 ( f549c4...0d47aa )
by Mikaël
114:39 queued 110:45
created

AbstractModel::replaceReservedMethod()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5.0187

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 10
cts 11
cp 0.9091
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 13
nc 6
nop 2
crap 5.0187
1
<?php
2
3
namespace WsdlToPhp\PackageGenerator\Model;
4
5
use WsdlToPhp\PackageGenerator\ConfigurationReader\GeneratorOptions;
6
use WsdlToPhp\PackageGenerator\ConfigurationReader\PhpReservedKeyword;
7
use WsdlToPhp\PackageGenerator\ConfigurationReader\AbstractReservedWord;
8
use WsdlToPhp\PackageGenerator\Generator\Generator;
9
use WsdlToPhp\PackageGenerator\Generator\Utils as GeneratorUtils;
10
use WsdlToPhp\PackageGenerator\Generator\AbstractGeneratorAware;
11
12
/**
13
 * Class AbstractModel defines the basic properties and methods to operations and structs extracted from the WSDL
14
 */
15
abstract class AbstractModel extends AbstractGeneratorAware implements \JsonSerializable
16
{
17
    /**
18
     * Constant used to define the key to store documentation value in meta
19
     * @var string
20
     */
21
    const META_DOCUMENTATION = 'documentation';
22
    /**
23
     * Original name od the element
24
     * @var string
25
     */
26
    protected $name = '';
27
    /**
28
     * Values associated to the operation
29
     * @var string[]
30
     */
31
    protected $meta = [];
32
    /**
33
     * Define the inheritance of a struct by the name of the parent struct or type
34
     * @var string
35
     */
36
    protected $inheritance = '';
37
    /**
38
     * Store the object which owns the current model
39
     * @var AbstractModel
40
     */
41
    protected $owner = null;
42
    /**
43
     * Indicates that the current element is an abstract element.
44
     * It allows to generated an abstract class.
45
     * This will happen for element/complexType that are defined with abstract="true"
46
     * @var bool
47
     */
48
    protected $isAbstract = false;
49
    /**
50
     * Replaced keywords time in order to generate unique new keyword
51
     * @var array
52
     */
53
    protected static $replacedPhpReservedKeywords = [];
54
    /**
55
     * Replaced methods time in order to generate unique new method
56
     * @var array
57
     */
58
    protected $replacedReservedMethods = [];
59
    /**
60
     * Unique name generated in order to ensure unique naming (for struct constructor and setters/getters even for different case attribute name with same value)
61
     * @var array
62
     */
63
    protected static $uniqueNames = [];
64
    /**
65
     * Main constructor
66
     * @uses AbstractModel::setName()
67
     * @param Generator $generator
68
     * @param string $name the original name
69
     */
70 1515
    public function __construct(Generator $generator, $name)
71
    {
72 1515
        parent::__construct($generator);
73 1515
        $this->setName($name);
74 1515
    }
75
    /**
76
     * @uses AbstractModel::getInheritedModel()
77
     * @uses AbstractModel::getPackagedName()
78
     * @uses AbstractModel::getExtends()
79
     * @uses Struct::isStruct()
80
     * @return string
81
     */
82 305
    public function getExtendsClassName()
83
    {
84 305
        $extends = '';
85 305
        if (($model = $this->getInheritedModel()) instanceof Struct && $model->isStruct()) {
86 25
            $extends = $model->getPackagedName($model->isRestriction());
87 15
        }
88 305
        if (empty($extends)) {
89 290
            $extends = $this->getExtends(true);
90 174
        }
91 305
        return $extends;
92
    }
93
    /**
94
     * Returns the name of the class the current class inherits from
95
     * @return string
96
     */
97 450
    public function getInheritance()
98
    {
99 450
        return $this->inheritance;
100
    }
101
    /**
102
     * Sets the name of the class the current class inherits from
103
     * @param string $inheritance
104
     * @return AbstractModel
105
     */
106 445
    public function setInheritance($inheritance = '')
107
    {
108 445
        $this->inheritance = $inheritance;
109 445
        return $this;
110
    }
111
    /**
112
     * @uses AbstractGeneratorAware::getGenerator()
113
     * @uses Generator::getStruct()
114
     * @uses AbstractModel::getInheritance()
115
     * @return Struct
116
     */
117 305
    public function getInheritedModel()
118
    {
119 305
        return $this->getGenerator()->getStruct($this->getInheritance());
120
    }
121
    /**
122
     * Returns the meta
123
     * @return string[]
124
     */
125 425
    public function getMeta()
126
    {
127 425
        return $this->meta;
128
    }
129
    /**
130
     * Sets the meta
131
     * @param string[] $meta
132
     * @return AbstractModel
133
     */
134 385
    public function setMeta(array $meta = [])
135
    {
136 385
        $this->meta = $meta;
137 385
        return $this;
138
    }
139
    /**
140
     * Add meta information to the operation
141
     * @uses AbstractModel::getMeta()
142
     * @throws \InvalidArgumentException
143
     * @param string $metaName
144
     * @param mixed $metaValue
145
     * @return AbstractModel
146
     */
147 155
    public function addMeta($metaName, $metaValue)
148
    {
149 155
        if (!is_scalar($metaName) || (!is_scalar($metaValue) && !is_array($metaValue))) {
150 10
            throw new \InvalidArgumentException(sprintf('Invalid meta name "%s" or value "%s". Please provide scalar meta name and scalar or array meta value.', gettype($metaName), gettype($metaValue)), __LINE__);
151
        }
152 145
        $metaValue = is_scalar($metaValue) ? trim($metaValue) : $metaValue;
153 145
        if ((is_scalar($metaValue) && $metaValue !== '') || is_array($metaValue)) {
154 145
            if (!array_key_exists($metaName, $this->meta)) {
155 145
                $this->meta[$metaName] = $metaValue;
156 101
            } elseif (is_array($this->meta[$metaName]) && is_array($metaValue)) {
157 20
                $this->meta[$metaName] = array_merge($this->meta[$metaName], $metaValue);
158 27
            } elseif (is_array($this->meta[$metaName])) {
159 5
                array_push($this->meta[$metaName], $metaValue);
160 3
            } else {
161 10
                $this->meta[$metaName] = $metaValue;
162 3
            }
163 145
            ksort($this->meta);
164 87
        }
165 145
        return $this;
166
    }
167
    /**
168
     * Sets the documentation meta value.
169
     * Documentation is set as an array so if multiple documentation nodes are set for an unique element, it will gather them.
170
     * @uses AbstractModel::META_DOCUMENTATION
171
     * @uses AbstractModel::addMeta()
172
     * @param string $documentation the documentation from the WSDL
173
     * @return AbstractModel
174
     */
175 25
    public function setDocumentation($documentation)
176
    {
177 25
        return $this->addMeta(self::META_DOCUMENTATION, is_array($documentation) ? $documentation : [
178 25
            $documentation,
179 15
        ]);
180
    }
181
    /**
182
     * Returns a meta value according to its name
183
     * @uses AbstractModel::getMeta()
184
     * @param string $metaName the meta information name
185
     * @param mixed $fallback the fallback value if unset
186
     * @return mixed the meta information value
187
     */
188 330
    public function getMetaValue($metaName, $fallback = null)
189
    {
190 330
        $meta = $this->getMeta();
191 330
        return array_key_exists($metaName, $meta) ? $meta[$metaName] : $fallback;
192
    }
193
    /**
194
     * Returns the value of the first meta value assigned to the name
195
     * @param string[] $names the meta names to check
196
     * @param mixed $fallback the fallback value if anyone is set
197
     * @return mixed the meta information value
198
     */
199 195
    public function getMetaValueFirstSet(array $names, $fallback = null)
200
    {
201 195
        $meta = $this->getMeta();
202 195
        foreach ($names as $name) {
203 195
            if (array_key_exists($name, $meta)) {
204 165
                return $meta[$name];
205
            }
206 96
        }
207 145
        return $fallback;
208
    }
209
    /**
210
     * Returns the original name extracted from the WSDL
211
     * @return string
212
     */
213 955
    public function getName()
214
    {
215 955
        return $this->name;
216
    }
217
    /**
218
     * Sets the original name extracted from the WSDL
219
     * @param string $name
220
     * @return AbstractModel
221
     */
222 1515
    public function setName($name)
223
    {
224 1515
        $this->name = $name;
225 1515
        return $this;
226
    }
227
    /**
228
     * Returns a valid clean name for PHP
229
     * @uses AbstractModel::getName()
230
     * @uses AbstractModel::cleanString()
231
     * @param bool $keepMultipleUnderscores optional, allows to keep the multiple consecutive underscores
232
     * @return string
233
     */
234 780
    public function getCleanName($keepMultipleUnderscores = true)
235
    {
236 780
        return self::cleanString($this->getName(), $keepMultipleUnderscores);
237
    }
238
    /**
239
     * Returns the owner model object
240
     * @return AbstractModel
241
     */
242 740
    public function getOwner()
243
    {
244 740
        return $this->owner;
245
    }
246
    /**
247
     * Sets the owner model object
248
     * @param AbstractModel $owner object the owner of the current model
249
     * @return AbstractModel
250
     */
251 1275
    public function setOwner(AbstractModel $owner = null)
252
    {
253 1275
        $this->owner = $owner;
254 1275
        return $this;
255
    }
256
    /**
257
     * @return bool
258
     */
259 310
    public function isAbstract()
260
    {
261 310
        return $this->isAbstract;
262
    }
263
    /**
264
     * @param bool $isAbstract
265
     * @return AbstractModel
266
     */
267 385
    public function setAbstract($isAbstract)
268
    {
269 385
        $this->isAbstract = $isAbstract;
270 385
        return $this;
271
    }
272
    /**
273
     * Returns true if the original name is safe to use as a PHP property, variable name or class name
274
     * @uses AbstractModel::getName()
275
     * @uses AbstractModel::getCleanName()
276
     * @return bool
277
     */
278 260
    public function nameIsClean()
279
    {
280 260
        return ($this->getName() !== '' && $this->getName() === $this->getCleanName());
281
    }
282
    /**
283
     * Returns the packaged name
284
     * @uses AbstractModel::getNamespace()
285
     * @uses AbstractModel::getCleanName()
286
     * @uses AbstractModel::getContextualPart()
287
     * @uses AbstractModel::uniqueName()
288
     * @uses AbstractModel::replacePhpReservedKeyword()
289
     * @uses AbstractGeneratorAware::getGenerator()
290
     * @uses Generator::getOptionPrefix()
291
     * @uses Generator::getOptionSuffix()
292
     * @uses AbstractModel::uniqueName() to ensure unique naming of struct case sensitively
293
     * @param bool $namespaced
294
     * @return string
295
     */
296 725
    public function getPackagedName($namespaced = false)
297
    {
298 725
        $nameParts = [];
299 725
        if ($namespaced && $this->getNamespace() !== '') {
300 290
            $nameParts[] = sprintf('\%s\\', $this->getNamespace());
301 174
        }
302 725
        $cleanName = $this->getCleanName();
303 725
        if ($this->getGenerator()->getOptionPrefix() !== '') {
304 460
            $nameParts[] = $this->getGenerator()->getOptionPrefix();
305 276
        } else {
306 310
            $cleanName = self::replacePhpReservedKeyword($cleanName);
307
        }
308 725
        $nameParts[] = ucfirst(self::uniqueName($cleanName, $this->getContextualPart()));
309 725
        if ($this->getGenerator()->getOptionSuffix() !== '') {
310 30
            $nameParts[] = $this->getGenerator()->getOptionSuffix();
311 18
        }
312 725
        return implode('', $nameParts);
313
    }
314
    /**
315
     * Allows to define the contextual part of the class name for the package
316
     * @return string
317
     */
318 115
    public function getContextualPart()
319
    {
320 115
        return '';
321
    }
322
    /**
323
     * Allows to define from which class the current model extends
324
     * @param bool $short
325
     * @return string|null
326
     */
327 55
    public function getExtends($short = false)
328
    {
329 55
        return '';
330
    }
331
    /**
332
     * @uses AbstractGeneratorAware::getGenerator()
333
     * @uses Generator::getOptionNamespacePrefix()
334
     * @uses Generator::getOptionPrefix()
335
     * @uses Generator::getOptionSuffix()
336
     * @uses AbstractModel::getSubDirectory()
337
     * @return string
338
     */
339 360
    public function getNamespace()
340
    {
341 360
        $namespaces = [];
342 360
        $namespace = $this->getGenerator()->getOptionNamespacePrefix();
343 360
        if (empty($namespace)) {
344 350
            if ($this->getGenerator()->getOptionPrefix() !== '') {
345 280
                $namespaces[] = $this->getGenerator()->getOptionPrefix();
346 238
            } elseif ($this->getGenerator()->getOptionSuffix() !== '') {
347 146
                $namespaces[] = $this->getGenerator()->getOptionSuffix();
348 6
            }
349 210
        } else {
350 10
            $namespaces[] = $namespace;
351
        }
352 360
        if ($this->getSubDirectory() !== '') {
353 335
            $namespaces[] = $this->getSubDirectory();
354 201
        }
355 360
        return implode('\\', $namespaces);
356
    }
357
    /**
358
     * Returns directory where to store class and create it if needed
359
     * @uses AbstractGeneratorAware::getGenerator()
360
     * @uses AbstractModel::getOptionCategory()
361
     * @uses AbstractGeneratorAware::getContextualPart()
362
     * @uses GeneratorOptions::VALUE_CAT
363
     * @return string
364
     */
365 390
    public function getSubDirectory()
366
    {
367 390
        $subDirectory = '';
368 390
        if ($this->getGenerator()->getOptionCategory() === GeneratorOptions::VALUE_CAT) {
369 385
            $subDirectory = $this->getContextualPart();
370 231
        }
371 390
        return $subDirectory;
372
    }
373
    /**
374
     * Returns the sub package name which the model belongs to
375
     * Must be overridden by sub classes
376
     * @return array
377
     */
378 5
    public function getDocSubPackages()
379
    {
380 5
        return [];
381
    }
382
    /**
383
     * Clean a string to make it valid as PHP variable
384
     * @uses GeneratorUtils::cleanString()
385
     * @param string $string the string to clean
386
     * @param bool $keepMultipleUnderscores optional, allows to keep the multiple consecutive underscores
387
     * @return string
388
     */
389 785
    public static function cleanString($string, $keepMultipleUnderscores = true)
390
    {
391 785
        return GeneratorUtils::cleanString($string, $keepMultipleUnderscores);
392
    }
393
    /**
394
     * Returns a usable keyword for a original keyword
395
     * @uses PhpReservedKeyword::instance()
396
     * @uses PhpReservedKeyword::is()
397
     * @param string $keyword the keyword
398
     * @param string $context the context
399
     * @return string
400
     */
401 720
    public static function replacePhpReservedKeyword($keyword, $context = null)
402
    {
403 720
        if (PhpReservedKeyword::instance()->is($keyword)) {
404 170
            if ($context !== null) {
405 95
                $keywordKey = $keyword . '_' . $context;
406 95
                if (!array_key_exists($keywordKey, self::$replacedPhpReservedKeywords)) {
407 60
                    self::$replacedPhpReservedKeywords[$keywordKey] = 0;
408 36
                } else {
409 35
                    self::$replacedPhpReservedKeywords[$keywordKey]++;
410
                }
411 95
                return '_' . $keyword . (self::$replacedPhpReservedKeywords[$keywordKey] ? '_' . self::$replacedPhpReservedKeywords[$keywordKey] : '');
412
            } else {
413 130
                return '_' . $keyword;
414
            }
415
        } else {
416 720
            return $keyword;
417
        }
418
    }
419
    /**
420
     * @throws \InvalidArgumentException
421
     * @param $filename
422
     * @return AbstractReservedWord
423
     */
424 5
    public function getReservedMethodsInstance($filename = null)
425
    {
426 5
        throw new \InvalidArgumentException(sprintf('The method %s should be defined in the class %s', __FUNCTION__, get_called_class(), __LINE__));
427
    }
428
    /**
429
     * Returns a usable method for a original method
430
     * @uses PhpReservedKeywords::instance()
431
     * @uses PhpReservedKeywords::is()
432
     * @param string $methodName the method name
433
     * @param string $context the context
434
     * @return string
435
     */
436 720
    public function replaceReservedMethod($methodName, $context = null)
437
    {
438 720
        if ($this->getReservedMethodsInstance()->is($methodName)) {
439 5
            if ($context !== null) {
440 5
                $methodKey = $methodName . '_' . $context;
441 5
                if (!array_key_exists($methodKey, $this->replacedReservedMethods)) {
442 5
                    $this->replacedReservedMethods[$methodKey] = 0;
443 3
                } else {
444
                    $this->replacedReservedMethods[$methodKey]++;
445
                }
446 5
                return '_' . $methodName . ($this->replacedReservedMethods[$methodKey] ? '_' . $this->replacedReservedMethods[$methodKey] : '');
447
            } else {
448 5
                return '_' . $methodName;
449
            }
450
        } else {
451 715
            return $methodName;
452
        }
453
    }
454
    /**
455
     * Static method which returns a unique name case sensitively
456
     * Useful to name methods case sensitively distinct, see http://the-echoplex.net/log/php-case-sensitivity
457
     * @param string $name the original name
458
     * @param string $context the context where the name is needed unique
459
     * @return string
460
     */
461 730
    protected static function uniqueName($name, $context)
462
    {
463 730
        $insensitiveKey = strtolower($name . '_' . $context);
464 730
        $sensitiveKey = $name . '_' . $context;
465 730
        if (array_key_exists($sensitiveKey, self::$uniqueNames)) {
466 725
            return self::$uniqueNames[$sensitiveKey];
467 615
        } elseif (!array_key_exists($insensitiveKey, self::$uniqueNames)) {
468 610
            self::$uniqueNames[$insensitiveKey] = 0;
469 366
        } else {
470 45
            self::$uniqueNames[$insensitiveKey]++;
471
        }
472 615
        $uniqueName = $name . (self::$uniqueNames[$insensitiveKey] ? '_' . self::$uniqueNames[$insensitiveKey] : '');
473 615
        self::$uniqueNames[$sensitiveKey] = $uniqueName;
474 615
        return $uniqueName;
475
    }
476
    /**
477
     * Gives the availability for test purpose and multiple package generation to purge unique names
478
     */
479 415
    public static function purgeUniqueNames()
480
    {
481 415
        self::$uniqueNames = [];
482 415
    }
483
    /**
484
     * Gives the availability for test purpose and multiple package generation to purge reserved keywords usage
485
     */
486 385
    public static function purgePhpReservedKeywords()
487
    {
488 385
        self::$replacedPhpReservedKeywords = [];
489 385
    }
490
    /**
491
     * Should return the properties of the inherited class
492
     * @return array
493
     */
494
    abstract protected function toJsonSerialize();
495
    /**
496
     * {@inheritDoc}
497
     * @see JsonSerializable::jsonSerialize()
498
     */
499 15
    public function jsonSerialize()
500
    {
501 15
        return array_merge($this->toJsonSerialize(), [
502 15
            'inheritance' => $this->inheritance,
503 15
            'abstract' => $this->isAbstract,
504 15
            'meta' => $this->meta,
505 15
            'name' => $this->name,
506 15
            '__CLASS__' => get_called_class(),
507 9
        ]);
508
    }
509
    /**
510
     * @param Generator $generator
511
     * @param array $args
512
     * @return AbstractModel
513
     */
514 380
    public static function instanceFromSerializedJson(Generator $generator, array $args)
515
    {
516 380
        self::checkSerializedJson($args);
517 380
        $class = $args['__CLASS__'];
518 380
        $instance = new $class($generator, $args['name']);
519 380
        unset($args['name'], $args['__CLASS__']);
520 380
        foreach ($args as $arg => $value) {
521 380
            $setFromSerializedJson = sprintf('set%sFromSerializedJson', ucfirst($arg));
522 380
            $set = sprintf('set%s', ucfirst($arg));
523 380
            if (method_exists($instance, $setFromSerializedJson)) {
524 380
                $instance->$setFromSerializedJson($value);
525 380
            } elseif (method_exists($instance, $set)) {
526 380
                $instance->$set($value);
527 228
            }
528 228
        }
529 380
        return $instance;
530
    }
531
    /**
532
     * @param array $args
533
     * @throws \InvalidArgumentException
534
     */
535 380
    protected static function checkSerializedJson(array $args)
536
    {
537 380
        if (!array_key_exists('__CLASS__', $args)) {
538
            throw new \InvalidArgumentException(sprintf('__CLASS__ key is missing from', var_export($args, true)));
539
        }
540 380
        if (!class_exists($args['__CLASS__'])) {
541
            throw new \InvalidArgumentException(sprintf('Class %s is unknown', $args['__CLASS__']));
542
        }
543 380
        if (!array_key_exists('name', $args)) {
544
            throw new \InvalidArgumentException(sprintf('name key is missing from', var_export($args, true)));
545
        }
546 380
    }
547
}
548