Completed
Push — master ( cdc419...060bfa )
by Mikaël
49:47
created

AbstractModel::toJsonSerialize()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
ccs 0
cts 0
cp 0
c 0
b 0
f 0
nc 1
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
    private $name = '';
27
    /**
28
     * Values associated to the operation
29
     * @var string[]
30
     */
31
    private $meta = array();
32
    /**
33
     * Define the inheritance of a struct by the name of the parent struct or type
34
     * @var string
35
     */
36
    private $inheritance = '';
37
    /**
38
     * Store the object which owns the current model
39
     * @var AbstractModel
40
     */
41
    private $owner = null;
42
    /**
43
     * Indicates that the current elemen 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
    private $isAbstract = false;
49
    /**
50
     * Replaced keywords time in order to generate unique new keyword
51
     * @var array
52
     */
53
    private static $replacedPhpReservedKeywords = array();
54
    /**
55
     * Replaced methods time in order to generate unique new method
56
     * @var array
57
     */
58
    private $replacedReservedMethods = array();
59
    /**
60
     * Unique name generated in order to ensure unique naming (for struct constructor and setters/getters even for different case attribute name whith same value)
61
     * @var array
62
     */
63
    private static $uniqueNames = array();
64
    /**
65
     * Main constructor
66
     * @uses AbstractModel::setName()
67
     * @param Generator $generator
68
     * @param string $name the original name
69
     */
70 1704
    public function __construct(Generator $generator, $name)
71
    {
72 1704
        parent::__construct($generator);
73 1704
        $this->setName($name);
74 1704
    }
75
    /**
76
     * @uses AbstractModel::getInheritedModel()
77
     * @uses AbstractModel::getPackagedName()
78
     * @uses AbstractModel::getExtends()
79
     * @uses Struct::isStruct()
80
     * @return string
81
     */
82 354
    public function getExtendsClassName()
83
    {
84 354
        $extends = '';
85 354
        if (($model = $this->getInheritedModel()) instanceof Struct && $model->isStruct()) {
86 30
            $extends = $model->getPackagedName($model->isRestriction());
87 20
        }
88 354
        if (empty($extends)) {
89 336
            $extends = $this->getExtends(true);
90 224
        }
91 354
        return $extends;
92
    }
93
    /**
94
     * Returns the name of the class the current class inherits from
95
     * @return string
96
     */
97 498
    public function getInheritance()
98
    {
99 498
        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 294
    public function setInheritance($inheritance = '')
107
    {
108 294
        $this->inheritance = $inheritance;
109 294
        return $this;
110
    }
111
    /**
112
     * @uses AbstractGeneratorAware::getGenerator()
113
     * @uses Generator::getStruct()
114
     * @uses AbstractModel::getInheritance()
115
     * @return Struct
116
     */
117 354
    public function getInheritedModel()
118
    {
119 354
        return $this->getGenerator()->getStruct($this->getInheritance());
120
    }
121
    /**
122
     * Returns the meta
123
     * @return string[]
124
     */
125 480
    public function getMeta()
126
    {
127 480
        return $this->meta;
128
    }
129
    /**
130
     * Sets the meta
131
     * @param string[] $meta
132
     * @return AbstractModel
133
     */
134 6
    public function setMeta(array $meta = array())
135
    {
136 6
        $this->meta = $meta;
137 6
        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 600
    public function addMeta($metaName, $metaValue)
148
    {
149 600
        if (!is_scalar($metaName) || (!is_scalar($metaValue) && !is_array($metaValue))) {
150 12
            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 588
        $metaValue = is_scalar($metaValue) ? trim($metaValue) : $metaValue;
153 588
        if ((is_scalar($metaValue) && $metaValue !== '') || is_array($metaValue)) {
154 588
            if (!array_key_exists($metaName, $this->meta)) {
155 576
                $this->meta[$metaName] = $metaValue;
156 444
            } elseif (is_array($this->meta[$metaName]) && is_array($metaValue)) {
157 126
                $this->meta[$metaName] = array_merge($this->meta[$metaName], $metaValue);
158 118
            } elseif (is_array($this->meta[$metaName])) {
159 6
                array_push($this->meta[$metaName], $metaValue);
160 4
            } else {
161 40
                $this->meta[$metaName] = $metaValue;
162
            }
163 588
            ksort($this->meta);
164 392
        }
165 588
        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 198
    public function setDocumentation($documentation)
176
    {
177 198
        return $this->addMeta(self::META_DOCUMENTATION, is_array($documentation) ? $documentation : array(
178 198
            $documentation,
179 132
        ));
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 396
    public function getMetaValue($metaName, $fallback = null)
189
    {
190 396
        $meta = $this->getMeta();
191 396
        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 186
    public function getMetaValueFirstSet(array $names, $fallback = null)
200
    {
201 186
        $meta = $this->getMeta();
202 186
        foreach ($names as $name) {
203 186
            if (array_key_exists($name, $meta)) {
204 156
                return $meta[$name];
205
            }
206 96
        }
207 144
        return $fallback;
208
    }
209
    /**
210
     * Returns the original name extracted from the WSDL
211
     * @return string
212
     */
213 1086
    public function getName()
214
    {
215 1086
        return $this->name;
216
    }
217
    /**
218
     * Sets the original name extracted from the WSDL
219
     * @param string $name
220
     * @return AbstractModel
221
     */
222 1704
    public function setName($name)
223
    {
224 1704
        $this->name = $name;
225 1704
        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 882
    public function getCleanName($keepMultipleUnderscores = true)
235
    {
236 882
        return self::cleanString($this->getName(), $keepMultipleUnderscores);
237
    }
238
    /**
239
     * Returns the owner model object
240
     * @return AbstractModel
241
     */
242 834
    public function getOwner()
243
    {
244 834
        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 1392
    public function setOwner(AbstractModel $owner = null)
252
    {
253 1392
        $this->owner = $owner;
254 1392
        return $this;
255
    }
256
    /**
257
     * @return bool
258
     */
259 360
    public function isAbstract()
260
    {
261 360
        return $this->isAbstract;
262
    }
263
    /**
264
     * @param bool $isAbstract
265
     * @return AbstractModel
266
     */
267 36
    public function setAbstract($isAbstract)
268
    {
269 36
        $this->isAbstract = $isAbstract;
270 36
        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 300
    public function nameIsClean()
279
    {
280 300
        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
     * @return string
294
     */
295 816
    public function getPackagedName($namespaced = false)
296
    {
297 816
        $nameParts = array();
298 816
        if ($namespaced && $this->getNamespace() !== '') {
299 330
            $nameParts[] = sprintf('\%s\\', $this->getNamespace());
300 220
        }
301 816
        $cleanName = $this->getCleanName();
302 816
        if ($this->getGenerator()->getOptionPrefix() !== '') {
303 438
            $nameParts[] = $this->getGenerator()->getOptionPrefix();
304 292
        } else {
305 432
            $cleanName = self::replacePhpReservedKeyword($cleanName);
306
        }
307 816
        $nameParts[] = ucfirst(self::uniqueName($cleanName, $this->getContextualPart()));
308 816
        if ($this->getGenerator()->getOptionSuffix() !== '') {
309 36
            $nameParts[] = $this->getGenerator()->getOptionSuffix();
310 24
        }
311 816
        return implode('', $nameParts);
312
    }
313
    /**
314
     * Allows to define the contextual part of the class name for the package
315
     * @return string
316
     */
317 132
    public function getContextualPart()
318
    {
319 132
        return '';
320
    }
321
    /**
322
     * Allows to define from which class the curent model extends
323
     * @param bool $short
324
     * @return string|null
325
     */
326 66
    public function getExtends($short = false)
327
    {
328 66
        return '';
329
    }
330
    /**
331
     * @uses AbstractGeneratorAware::getGenerator()
332
     * @uses Generator::getOptionNamespacePrefix()
333
     * @uses Generator::getOptionPrefix()
334
     * @uses Generator::getOptionSuffix()
335
     * @uses AbstractModel::getSubDirectory()
336
     * @return string
337
     */
338 414
    public function getNamespace()
339
    {
340 414
        $namespaces = array();
341 414
        $namespace = $this->getGenerator()->getOptionNamespacePrefix();
342 414
        if (empty($namespace)) {
343 402
            if ($this->getGenerator()->getOptionPrefix() !== '') {
344 318
                $namespaces[] = $this->getGenerator()->getOptionPrefix();
345 296
            } elseif ($this->getGenerator()->getOptionSuffix() !== '') {
346 77
                $namespaces[] = $this->getGenerator()->getOptionSuffix();
347 8
            }
348 268
        } else {
349 12
            $namespaces[] = $namespace;
350
        }
351 414
        if ($this->getSubDirectory() !== '') {
352 384
            $namespaces[] = $this->getSubDirectory();
353 256
        }
354 414
        return implode('\\', $namespaces);
355
    }
356
    /**
357
     * Returns directory where to store class and create it if needed
358
     * @uses AbstractGeneratorAware::getGenerator()
359
     * @uses AbstractModel::getOptionCategory()
360
     * @uses AbstractGeneratorAware::getContextualPart()
361
     * @uses GeneratorOptions::VALUE_CAT
362
     * @return string
363
     */
364 450
    public function getSubDirectory()
365
    {
366 450
        $subDirectory = '';
367 450
        if ($this->getGenerator()->getOptionCategory() === GeneratorOptions::VALUE_CAT) {
368 444
            $subDirectory = $this->getContextualPart();
369 296
        }
370 450
        return $subDirectory;
371
    }
372
    /**
373
     * Returns the sub package name which the model belongs to
374
     * Must be overridden by sub classes
375
     * @return array
376
     */
377 6
    public function getDocSubPackages()
378
    {
379 6
        return array();
380
    }
381
    /**
382
     * Clean a string to make it valid as PHP variable
383
     * @uses GeneratorUtils::cleanString()
384
     * @param string $string the string to clean
385
     * @param bool $keepMultipleUnderscores optional, allows to keep the multiple consecutive underscores
386
     * @return string
387
     */
388 888
    public static function cleanString($string, $keepMultipleUnderscores = true)
389
    {
390 888
        return GeneratorUtils::cleanString($string, $keepMultipleUnderscores);
391
    }
392
    /**
393
     * Returns a usable keyword for a original keyword
394
     * @uses PhpReservedKeyword::instance()
395
     * @uses PhpReservedKeyword::is()
396
     * @param string $keyword the keyword
397
     * @param string $context the context
398
     * @return string
399
     */
400 798
    public static function replacePhpReservedKeyword($keyword, $context = null)
401
    {
402 798
        if (PhpReservedKeyword::instance()->is($keyword)) {
403 192
            if ($context !== null) {
404 102
                $keywordKey = $keyword . '_' . $context;
405 102
                if (!array_key_exists($keywordKey, self::$replacedPhpReservedKeywords)) {
406 60
                    self::$replacedPhpReservedKeywords[$keywordKey] = 0;
407 40
                } else {
408 42
                    self::$replacedPhpReservedKeywords[$keywordKey]++;
409
                }
410 102
                return '_' . $keyword . (self::$replacedPhpReservedKeywords[$keywordKey] ? '_' . self::$replacedPhpReservedKeywords[$keywordKey] : '');
411
            } else {
412 156
                return '_' . $keyword;
413
            }
414
        } else {
415 798
            return $keyword;
416
        }
417
    }
418
    /**
419
     * @throws \InvalidArgumentException
420
     * @param $filename
421
     * @return AbstractReservedWord
422
     */
423 6
    public function getReservedMethodsInstance($filename = null)
424
    {
425 6
        throw new \InvalidArgumentException(sprintf('The method %s should be defined in the class %s', __FUNCTION__, get_called_class(), __LINE__));
426
    }
427
    /**
428
     * Returns a usable method for a original method
429
     * @uses PhpReservedKeywords::instance()
430
     * @uses PhpReservedKeywords::is()
431
     * @param string $methodName the method name
432
     * @param string $context the context
433
     * @return string
434
     */
435 816
    public function replaceReservedMethod($methodName, $context = null)
436
    {
437 816
        if ($this->getReservedMethodsInstance()->is($methodName)) {
438 6
            if ($context !== null) {
439 6
                $methodKey = $methodName . '_' . $context;
440 6
                if (!array_key_exists($methodKey, $this->replacedReservedMethods)) {
441 6
                    $this->replacedReservedMethods[$methodKey] = 0;
442 4
                } else {
443
                    $this->replacedReservedMethods[$methodKey]++;
444
                }
445 6
                return '_' . $methodName . ($this->replacedReservedMethods[$methodKey] ? '_' . $this->replacedReservedMethods[$methodKey] : '');
446
            } else {
447 6
                return '_' . $methodName;
448
            }
449
        } else {
450 810
            return $methodName;
451
        }
452
    }
453
    /**
454
     * Static method wich returns a unique name case sensitively
455
     * Useful to name methods case sensitively distinct, see http://the-echoplex.net/log/php-case-sensitivity
456
     * @param string $name the original name
457
     * @param string $context the context where the name is needed unique
458
     * @return string
459
     */
460 822
    protected static function uniqueName($name, $context)
461
    {
462 822
        $insensitiveKey = strtolower($name . '_' . $context);
463 822
        $sensitiveKey = $name . '_' . $context;
464 822
        if (array_key_exists($sensitiveKey, self::$uniqueNames)) {
465 816
            return self::$uniqueNames[$sensitiveKey];
466 696
        } elseif (!array_key_exists($insensitiveKey, self::$uniqueNames)) {
467 690
            self::$uniqueNames[$insensitiveKey] = 0;
468 460
        } else {
469 48
            self::$uniqueNames[$insensitiveKey]++;
470
        }
471 696
        $uniqueName = $name . (self::$uniqueNames[$insensitiveKey] ? '_' . self::$uniqueNames[$insensitiveKey] : '');
472 696
        self::$uniqueNames[$sensitiveKey] = $uniqueName;
473 696
        return $uniqueName;
474
    }
475
    /**
476
     * Gives the availability for test purpose and multiple package generation to purge unique names
477
     */
478 462
    public static function purgeUniqueNames()
479
    {
480 462
        self::$uniqueNames = array();
481 462
    }
482
    /**
483
     * Gives the availability for test purpose and multiple package generation to purge reserved keywords usage
484
     */
485 426
    public static function purgePhpReservedKeywords()
486
    {
487 426
        self::$replacedPhpReservedKeywords = array();
488 426
    }
489
    /**
490
     * Should return the properties of the inherited class
491
     * @return array
492
     */
493
    abstract protected function toJsonSerialize();
494
    /**
495
     * {@inheritDoc}
496
     * @see JsonSerializable::jsonSerialize()
497
     */
498
    public function jsonSerialize()
499
    {
500
        return array_merge($this->toJsonSerialize(), array(
501
            'inheritance' => $this->inheritance,
502
            'abstract' => $this->isAbstract,
503
            'meta' => $this->meta,
504
            'name' => $this->name,
505
            '__CLASS__' => get_called_class(),
506
        ));
507
    }
508
    /**
509
     * @param Generator $generator
510
     * @param array $args
511
     * @return AbstractModel
512
     */
513
    public static function instanceFromSerializedJson(Generator $generator, array $args)
514
    {
515
        self::checkSerializedJson($args);
516
        $class = $args['__CLASS__'];
517
        $instance = new $class($generator, $args['name']);
518
        unset($args['name'], $args['__CLASS__']);
519
        foreach ($args as $arg => $value) {
520
            $setFromSerializedJson = sprintf('set%sFromSerializedJson', ucfirst($arg));
521
            $set = sprintf('set%s', ucfirst($arg));
522
            if (method_exists($instance, $setFromSerializedJson)) {
523
                $instance->$setFromSerializedJson($value);
524
            } elseif (method_exists($instance, $set)) {
525
                $instance->$set($value);
526
            }
527
        }
528
        return $instance;
529
    }
530
    /**
531
     * @param array $args
532
     * @throws \InvalidArgumentException
533
     */
534
    private static function checkSerializedJson(array $args)
535
    {
536
        if (!array_key_exists('__CLASS__', $args)) {
537
            throw new \InvalidArgumentException(sprintf('__CLASS__ key is missing from', var_export($args, true)));
538
        }
539
        if (!class_exists($args['__CLASS__'])) {
540
            throw new \InvalidArgumentException(sprintf('Class %s is unknown', $args['__CLASS__']));
541
        }
542
        if (!array_key_exists('name', $args)) {
543
            throw new \InvalidArgumentException(sprintf('name key is missing from', var_export($args, true)));
544
        }
545
    }
546
}
547