Completed
Push — class-metadata-visitor ( 7b4c97...bdf9cb )
by Nate
02:01
created

GsonBuilder   A

Complexity

Total Complexity 35

Size/Duplication

Total Lines 506
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 128
dl 0
loc 506
rs 9.6
c 2
b 0
f 0
wmc 35

21 Methods

Rating   Name   Duplication   Size   Complexity  
B build() 0 47 7
A enableCache() 0 5 1
A setMethodNamingStrategy() 0 5 1
A setVersion() 0 5 1
A setPropertyNamingPolicy() 0 5 1
A serializeNull() 0 5 1
A addDiscriminator() 0 10 1
A requireExclusionCheckAnnotation() 0 5 1
A registerType() 0 27 6
A setCache() 0 5 1
A getTypeAdapterFactories() 0 24 1
A requireExposeAnnotation() 0 5 1
A setDateTimeFormat() 0 5 1
A addClassMetadataVisitor() 0 5 1
A setPropertyNamingStrategy() 0 5 1
A addTypeAdapterFactory() 0 5 1
A addExclusion() 0 17 4
A setExcludedModifier() 0 5 1
A addInstanceCreator() 0 6 1
A setCacheDir() 0 5 1
A addExclusionStrategy() 0 7 1
1
<?php
2
/*
3
 * Copyright (c) Nate Brunette.
4
 * Distributed under the MIT License (http://opensource.org/licenses/MIT)
5
 */
6
7
declare(strict_types=1);
8
9
namespace Tebru\Gson;
10
11
use DateTime;
12
use Doctrine\Common\Annotations\AnnotationReader;
13
use InvalidArgumentException;
14
use LogicException;
15
use Psr\SimpleCache\CacheInterface;
16
use ReflectionProperty;
17
use Symfony\Component\Cache\Simple\ArrayCache;
18
use Symfony\Component\Cache\Simple\ChainCache;
19
use Symfony\Component\Cache\Simple\NullCache;
20
use Symfony\Component\Cache\Simple\PhpFilesCache;
21
use Tebru\AnnotationReader\AnnotationReaderAdapter;
22
use Tebru\Gson\Annotation\ExclusionCheck;
23
use Tebru\Gson\Exclusion\DeserializationExclusionDataAware;
24
use Tebru\Gson\Exclusion\ExclusionStrategy;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Tebru\Gson\ExclusionStrategy. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
25
use Tebru\Gson\Exclusion\SerializationExclusionDataAware;
26
use Tebru\Gson\ExclusionStrategy as DeprecatedExclusionStrategy;
27
use Tebru\Gson\Internal\AccessorMethodProvider;
28
use Tebru\Gson\Internal\AccessorStrategyFactory;
29
use Tebru\Gson\Internal\ConstructorConstructor;
30
use Tebru\Gson\Internal\Data\ClassMetadataFactory;
31
use Tebru\Gson\Internal\Data\ReflectionPropertySetFactory;
32
use Tebru\Gson\Internal\DiscriminatorDeserializer;
33
use Tebru\Gson\Internal\Excluder;
34
use Tebru\Gson\Internal\ExclusionStrategyAdapter;
35
use Tebru\Gson\Internal\Naming\DefaultPropertyNamingStrategy;
36
use Tebru\Gson\Internal\Naming\PropertyNamer;
37
use Tebru\Gson\Internal\Naming\UpperCaseMethodNamingStrategy;
38
use Tebru\Gson\Internal\TypeAdapter\Factory\ArrayTypeAdapterFactory;
39
use Tebru\Gson\Internal\TypeAdapter\Factory\BooleanTypeAdapterFactory;
40
use Tebru\Gson\Internal\TypeAdapter\Factory\CustomWrappedTypeAdapterFactory;
41
use Tebru\Gson\Internal\TypeAdapter\Factory\DateTimeTypeAdapterFactory;
42
use Tebru\Gson\Internal\TypeAdapter\Factory\FloatTypeAdapterFactory;
43
use Tebru\Gson\Internal\TypeAdapter\Factory\IntegerTypeAdapterFactory;
44
use Tebru\Gson\Internal\TypeAdapter\Factory\JsonElementTypeAdapterFactory;
45
use Tebru\Gson\Internal\TypeAdapter\Factory\NullTypeAdapterFactory;
46
use Tebru\Gson\Internal\TypeAdapter\Factory\ReflectionTypeAdapterFactory;
47
use Tebru\Gson\Internal\TypeAdapter\Factory\StringTypeAdapterFactory;
48
use Tebru\Gson\Internal\TypeAdapter\Factory\WildcardTypeAdapterFactory;
49
use Tebru\Gson\Internal\TypeAdapter\Factory\WrappedTypeAdapterFactory;
50
use Tebru\Gson\Internal\TypeAdapterProvider;
51
use Tebru\Gson\Internal\TypeTokenFactory;
52
use Tebru\PhpType\TypeToken;
53
54
/**
55
 * Class GsonBuilder
56
 *
57
 * @author Nate Brunette <[email protected]>
58
 */
59
class GsonBuilder
60
{
61
    /**
62
     * Array of type adapter factories
63
     *
64
     * @var TypeAdapterFactory[]
65
     */
66
    private $typeAdapterFactories = [];
67
68
    /**
69
     * @var InstanceCreator[]
70
     */
71
    private $instanceCreators = [];
72
73
    /**
74
     * List of visitors to manipulate class metadata
75
     *
76
     * @var ClassMetadataVisitor[]
77
     */
78
    private $classMetadataVisitors = [];
79
80
    /**
81
     * Strategy for converting property names to serialized names
82
     *
83
     * @var PropertyNamingStrategy
84
     */
85
    private $propertyNamingStrategy;
86
87
    /**
88
     * Property naming policy
89
     *
90
     * Defaults to converting camel case to snake case
91
     *
92
     * @var string
93
     */
94
    private $propertyNamingPolicy = PropertyNamingPolicy::LOWER_CASE_WITH_UNDERSCORES;
95
96
    /**
97
     * Strategy for converting property names to method names
98
     *
99
     * @var MethodNamingStrategy
100
     */
101
    private $methodNamingStrategy;
102
103
    /**
104
     * The version that should be used with Since/Until annotations
105
     *
106
     * @var string
107
     */
108
    private $version;
109
110
    /**
111
     * Modifiers from [@see ReflectionProperty] that should be excluded
112
     *
113
     * @var int
114
     */
115
    private $excludedModifiers = ReflectionProperty::IS_STATIC;
116
117
    /**
118
     * True if the [@see Expose] annotation is required for serialization/deserialization
119
     *
120
     * @var bool
121
     */
122
    private $requireExpose = false;
123
124
    /**
125
     * True if the [@see ExclusionCheck] annotation is required to use non-cached exclusion strategies
126
     *
127
     * @var bool
128
     */
129
    private $requireExclusionCheck = false;
130
131
    /**
132
     * An array of [@see ExclusionStrategy] objects
133
     *
134
     * @var ExclusionStrategy[]
135
     */
136
    private $exclusionStrategies = [];
137
138
    /**
139
     * An array of Cacheable [@see ExclusionStrategy] objects
140
     *
141
     * @var ExclusionStrategy[]
142
     */
143
    private $cachedExclusionStrategies = [];
144
145
    /**
146
     * If we should serialize nulls, defaults to false
147
     *
148
     * @var bool
149
     */
150
    private $serializeNull = false;
151
152
    /**
153
     * Default format for DateTimes
154
     *
155
     * @var string
156
     */
157
    private $dateTimeFormat = DateTime::ATOM;
158
159
    /**
160
     * A cache interface to be used in place of defaults
161
     *
162
     * If this is set, [@see GsonBuilder::$enableCache] will be ignored
163
     *
164
     * @var CacheInterface
165
     */
166
    private $cache;
167
168
    /**
169
     * True if we should be caching
170
     *
171
     * @var bool
172
     */
173
    private $enableCache = false;
174
175
    /**
176
     * Cache directory, if set this enabled filesystem caching
177
     *
178
     * @var string
179
     */
180
    private $cacheDir;
181
182
    /**
183
     * Add a custom type adapter
184
     *
185
     * @param TypeAdapterFactory $typeAdapterFactory
186
     * @return GsonBuilder
187
     */
188
    public function addTypeAdapterFactory(TypeAdapterFactory $typeAdapterFactory): GsonBuilder
189
    {
190
        $this->typeAdapterFactories[] = $typeAdapterFactory;
191
192
        return $this;
193
    }
194
195
    /**
196
     * Adds a [@see Discriminator] as a type adapter factory
197
     *
198
     * @param string $type
199
     * @param Discriminator $discriminator
200
     * @return GsonBuilder
201
     */
202
    public function addDiscriminator(string $type, Discriminator $discriminator): GsonBuilder
203
    {
204
        $this->typeAdapterFactories[] = new CustomWrappedTypeAdapterFactory(
205
            TypeToken::create($type),
206
            true,
207
            null,
208
            new DiscriminatorDeserializer($discriminator)
209
        );
210
211
        return $this;
212
    }
213
214
    /**
215
     * Add custom handling for a specific type
216
     *
217
     * Handler objects may be of types: TypeAdapter, JsonSerializer, or JsonDeserializer. Passing
218
     * $strict=true will match the specified type exactly, as opposed to checking anywhere in the
219
     * inheritance chain.
220
     *
221
     * @param string $type
222
     * @param $handler
223
     * @param bool $strict
224
     * @return GsonBuilder
225
     */
226
    public function registerType(string $type, $handler, bool $strict = false): GsonBuilder
227
    {
228
        if ($handler instanceof TypeAdapter) {
229
            $this->typeAdapterFactories[] = new WrappedTypeAdapterFactory($handler, TypeToken::create($type), $strict);
230
231
            return $this;
232
        }
233
234
        if ($handler instanceof JsonSerializer && $handler instanceof JsonDeserializer) {
235
            $this->typeAdapterFactories[] = new CustomWrappedTypeAdapterFactory(TypeToken::create($type), $strict, $handler, $handler);
236
237
            return $this;
238
        }
239
240
        if ($handler instanceof JsonSerializer) {
241
            $this->typeAdapterFactories[] = new CustomWrappedTypeAdapterFactory(TypeToken::create($type), $strict, $handler);
242
243
            return $this;
244
        }
245
246
        if ($handler instanceof JsonDeserializer) {
247
            $this->typeAdapterFactories[] = new CustomWrappedTypeAdapterFactory(TypeToken::create($type), $strict, null, $handler);
248
249
            return $this;
250
        }
251
252
        throw new InvalidArgumentException(\sprintf('Handler of type "%s" is not supported', \get_class($handler)));
253
    }
254
255
    /**
256
     * Add an [@see InstanceCreator] for a given type
257
     *
258
     * @param string $type
259
     * @param InstanceCreator $instanceCreator
260
     * @return GsonBuilder
261
     */
262
    public function addInstanceCreator(string $type, InstanceCreator $instanceCreator): GsonBuilder
263
    {
264
        $phpType = TypeToken::create($type);
265
        $this->instanceCreators[$phpType->getRawType()] = $instanceCreator;
266
267
        return $this;
268
    }
269
270
    public function addClassMetadataVisitor(ClassMetadataVisitor $propertyCollectionVisitor): GsonBuilder
271
    {
272
        $this->classMetadataVisitors[] = $propertyCollectionVisitor;
273
274
        return $this;
275
    }
276
277
    /**
278
     * Set the version to be used with [@see Since] and [@see Until] annotations
279
     *
280
     * @param string $version
281
     * @return GsonBuilder
282
     */
283
    public function setVersion(string $version): GsonBuilder
284
    {
285
        $this->version = $version;
286
287
        return $this;
288
    }
289
290
    /**
291
     * Set the property modifiers that should be excluded based on [@see \ReflectionProperty]
292
     *
293
     * This number is a bitmap, so ReflectionProperty::IS_STATIC will exclude all static properties.
294
     * Likewise, passing (ReflectionProperty::IS_STATIC | ReflectionProperty::IS_PRIVATE) will exclude
295
     * all static and private properties.
296
     *
297
     * @param int $modifiers
298
     * @return GsonBuilder
299
     */
300
    public function setExcludedModifier(int $modifiers): GsonBuilder
301
    {
302
        $this->excludedModifiers = $modifiers;
303
304
        return $this;
305
    }
306
307
    /**
308
     * Require the [@see Expose] annotation to serialize or deserialize property
309
     *
310
     * @return GsonBuilder
311
     */
312
    public function requireExposeAnnotation(): GsonBuilder
313
    {
314
        $this->requireExpose = true;
315
316
        return $this;
317
    }
318
319
    /**
320
     * Require the [@see ExclusionCheck] annotation to use non-cached exclusion strategies
321
     *
322
     * @return GsonBuilder
323
     */
324
    public function requireExclusionCheckAnnotation(): GsonBuilder
325
    {
326
        $this->requireExclusionCheck = true;
327
328
        return $this;
329
    }
330
331
    /**
332
     * Add an exclusion strategy that should be used during serialization/deserialization
333
     *
334
     * @param DeprecatedExclusionStrategy $strategy
335
     * @param bool $serialization
336
     * @param bool $deserialization
337
     * @return GsonBuilder
338
     * @deprecated Since v0.6.0 to be removed in v0.7.0. Use GsonBuilder::addExclusion() instead.
339
     */
340
    public function addExclusionStrategy(DeprecatedExclusionStrategy $strategy, bool $serialization, bool $deserialization): GsonBuilder
341
    {
342
        @trigger_error('Gson: GsonBuilder::addExclusionStrategy() is deprecated since v0.6.0 and will be removed in v0.7.0. Use GsonBuilder::addExclusion() instead.', E_USER_DEPRECATED);
343
344
        $this->addExclusion(new ExclusionStrategyAdapter($strategy, $serialization, $deserialization));
345
346
        return $this;
347
    }
348
349
    /**
350
     * Add an [@see ExclusionStrategy]
351
     *
352
     * @param ExclusionStrategy $exclusionStrategy
353
     * @return GsonBuilder
354
     */
355
    public function addExclusion(ExclusionStrategy $exclusionStrategy): GsonBuilder
356
    {
357
        if (!$exclusionStrategy->shouldCache()) {
358
            $this->exclusionStrategies[] = $exclusionStrategy;
359
            return $this;
360
        }
361
362
        if (
363
            $exclusionStrategy instanceof SerializationExclusionDataAware
364
            || $exclusionStrategy instanceof DeserializationExclusionDataAware
365
        ) {
366
            throw new LogicException('Gson: Cacheable exclusion strategies must not implement *DataAware interfaces');
367
        }
368
369
        $this->cachedExclusionStrategies[] = $exclusionStrategy;
370
371
        return $this;
372
    }
373
374
    /**
375
     * Set a custom property naming strategy
376
     *
377
     * @param PropertyNamingStrategy $propertyNamingStrategy
378
     * @return GsonBuilder
379
     */
380
    public function setPropertyNamingStrategy(PropertyNamingStrategy $propertyNamingStrategy): GsonBuilder
381
    {
382
        $this->propertyNamingStrategy = $propertyNamingStrategy;
383
384
        return $this;
385
    }
386
387
    /**
388
     * Set one of [@see PropertyNamingPolicy]
389
     *
390
     * @param string $policy
391
     * @return GsonBuilder
392
     */
393
    public function setPropertyNamingPolicy(string $policy): GsonBuilder
394
    {
395
        $this->propertyNamingPolicy = $policy;
396
397
        return $this;
398
    }
399
400
    /**
401
     * Set a custom method naming strategy
402
     *
403
     * @param MethodNamingStrategy $methodNamingStrategy
404
     * @return GsonBuilder
405
     */
406
    public function setMethodNamingStrategy(MethodNamingStrategy $methodNamingStrategy): GsonBuilder
407
    {
408
        $this->methodNamingStrategy = $methodNamingStrategy;
409
410
        return $this;
411
    }
412
413
    /**
414
     * Set whether we should serialize null
415
     *
416
     * @return GsonBuilder
417
     */
418
    public function serializeNull(): GsonBuilder
419
    {
420
        $this->serializeNull = true;
421
422
        return $this;
423
    }
424
425
    /**
426
     * Set the default datetime format
427
     *
428
     * @param string $format
429
     * @return GsonBuilder
430
     */
431
    public function setDateTimeFormat(string $format): GsonBuilder
432
    {
433
        $this->dateTimeFormat = $format;
434
435
        return $this;
436
    }
437
438
    /**
439
     * Override default cache adapters
440
     *
441
     * @param CacheInterface $cache
442
     * @return GsonBuilder
443
     */
444
    public function setCache(CacheInterface $cache): GsonBuilder
445
    {
446
        $this->cache = $cache;
447
448
        return $this;
449
    }
450
451
452
    /**
453
     * Set whether caching is enabled
454
     *
455
     * @param bool $enableCache
456
     * @return GsonBuilder
457
     */
458
    public function enableCache(bool $enableCache): GsonBuilder
459
    {
460
        $this->enableCache = $enableCache;
461
462
        return $this;
463
    }
464
465
    /**
466
     * Setting a cache directory will turn on filesystem caching
467
     *
468
     * @param string $cacheDir
469
     * @return GsonBuilder
470
     */
471
    public function setCacheDir(string $cacheDir): GsonBuilder
472
    {
473
        $this->cacheDir = $cacheDir.'/gson';
474
475
        return $this;
476
    }
477
478
    /**
479
     * Builds a new [@see Gson] object based on configuration set
480
     *
481
     * @return Gson
482
     * @throws \LogicException
483
     */
484
    public function build(): Gson
485
    {
486
        if (null === $this->cacheDir && true === $this->enableCache) {
487
            throw new LogicException('Cannot enable cache without a cache directory');
488
        }
489
490
        $propertyNamingStrategy = $this->propertyNamingStrategy ?? new DefaultPropertyNamingStrategy($this->propertyNamingPolicy);
491
        $methodNamingStrategy = $this->methodNamingStrategy ?? new UpperCaseMethodNamingStrategy();
492
493
        if ($this->cache === null) {
494
            $this->cache = false === $this->enableCache
495
                ? new ArrayCache(0, false)
496
                : new ChainCache([new ArrayCache(0, false), new PhpFilesCache('', 0, $this->cacheDir)]);
497
        }
498
499
        // no need to cache the annotations as they get cached with the class/properties
500
        $annotationReader = new AnnotationReaderAdapter(new AnnotationReader(), new NullCache());
501
        $excluder = new Excluder();
502
        $excluder->setVersion($this->version);
503
        $excluder->setExcludedModifiers($this->excludedModifiers);
504
        $excluder->setRequireExpose($this->requireExpose);
505
506
        foreach ($this->exclusionStrategies as $strategy) {
507
            $excluder->addExclusionStrategy($strategy);
508
        }
509
510
        foreach ($this->cachedExclusionStrategies as $strategy) {
511
            $excluder->addCachedExclusionStrategy($strategy);
512
        }
513
514
        $classMetadataFactory = new ClassMetadataFactory(
515
            new ReflectionPropertySetFactory(),
516
            $annotationReader,
517
            new PropertyNamer($propertyNamingStrategy),
518
            new AccessorMethodProvider($methodNamingStrategy),
519
            new AccessorStrategyFactory(),
520
            new TypeTokenFactory(),
521
            $excluder,
522
            $this->cache
523
        );
524
        $constructorConstructor = new ConstructorConstructor($this->instanceCreators);
525
        $typeAdapterProvider = new TypeAdapterProvider(
526
            $this->getTypeAdapterFactories($classMetadataFactory, $excluder, $constructorConstructor),
527
            $constructorConstructor
528
        );
529
530
        return new Gson($typeAdapterProvider, $this->serializeNull);
531
    }
532
533
    /**
534
     * Merges default factories with user provided factories
535
     *
536
     * @param ClassMetadataFactory $classMetadataFactory
537
     * @param Excluder $excluder
538
     * @param ConstructorConstructor $constructorConstructor
539
     * @return array|TypeAdapterFactory[]
540
     */
541
    private function getTypeAdapterFactories(
542
        ClassMetadataFactory $classMetadataFactory,
543
        Excluder $excluder,
544
        ConstructorConstructor $constructorConstructor
545
    ): array {
546
        return \array_merge(
547
            $this->typeAdapterFactories,
548
            [
549
                new StringTypeAdapterFactory(),
550
                new IntegerTypeAdapterFactory(),
551
                new FloatTypeAdapterFactory(),
552
                new BooleanTypeAdapterFactory(),
553
                new NullTypeAdapterFactory(),
554
                new DateTimeTypeAdapterFactory($this->dateTimeFormat),
555
                new ArrayTypeAdapterFactory(),
556
                new JsonElementTypeAdapterFactory(),
557
                new ReflectionTypeAdapterFactory(
558
                    $constructorConstructor,
559
                    $classMetadataFactory,
560
                    $excluder,
561
                    $this->requireExclusionCheck,
562
                    $this->classMetadataVisitors
563
                ),
564
                new WildcardTypeAdapterFactory(),
565
            ]
566
        );
567
    }
568
}
569