Completed
Pull Request — 3.x (#5937)
by Peter
05:08 queued 01:40
created

DataTransformerResolver   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 101
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 3
dl 0
loc 101
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A addCustomGlobalTransformer() 0 4 1
B resolve() 0 54 8
A getOutputTimezone() 0 14 3
A hasFieldDescriptionAssociationWithClass() 0 8 3
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\AdminBundle\Form;
15
16
use Sonata\AdminBundle\Admin\FieldDescriptionInterface;
17
use Sonata\AdminBundle\Form\DataTransformer\ModelToIdTransformer;
18
use Sonata\AdminBundle\Model\ModelManagerInterface;
19
use Sonata\AdminBundle\Templating\TemplateRegistry;
20
use Symfony\Component\Form\DataTransformerInterface;
21
use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer;
22
23
/**
24
 * @author Peter Gribanov <[email protected]>
25
 */
26
final class DataTransformerResolver implements DataTransformerResolverInterface
27
{
28
    /**
29
     * @var array<string, DataTransformerInterface>
30
     */
31
    private $globalCustomTransformers = [];
32
33
    /**
34
     * @param array<string, DataTransformerInterface> $customGlobalTransformers
35
     */
36
    public function __construct(array $customGlobalTransformers = [])
37
    {
38
        foreach ($customGlobalTransformers as $fieldType => $dataTransformer) {
39
            $this->addCustomGlobalTransformer($fieldType, $dataTransformer);
40
        }
41
    }
42
43
    public function addCustomGlobalTransformer(string $fieldType, DataTransformerInterface $dataTransformer): void
44
    {
45
        $this->globalCustomTransformers[$fieldType] = $dataTransformer;
46
    }
47
48
    public function resolve(
49
        FieldDescriptionInterface $fieldDescription,
50
        ModelManagerInterface $modelManager
51
    ): ?DataTransformerInterface {
52
        $dataTransformer = $fieldDescription->getOption('data_transformer');
53
54
        // allow override predefined transformers for 'date', 'boolean' and 'choice' field types
55
        if ($dataTransformer instanceof DataTransformerInterface) {
56
            return $dataTransformer;
57
        }
58
59
        $fieldType = (string) $fieldDescription->getType();
60
61
        // allow override predefined transformers on a global level
62
        if (\array_key_exists($fieldType, $this->globalCustomTransformers)) {
63
            return $this->globalCustomTransformers[$fieldType];
64
        }
65
66
        // Handle date type has setter expect a DateTime object
67
        if (TemplateRegistry::TYPE_DATE === $fieldType) {
68
            $this->globalCustomTransformers[$fieldType] = new DateTimeToStringTransformer(
69
                null,
70
                $this->getOutputTimezone($fieldDescription),
71
                'Y-m-d'
72
            );
73
74
            return $this->globalCustomTransformers[$fieldType];
75
        }
76
77
        // Handle datetime type has setter expect a DateTime object
78
        if (TemplateRegistry::TYPE_DATETIME === $fieldType) {
79
            $this->globalCustomTransformers[$fieldType] = new DateTimeToStringTransformer(
80
                null,
81
                $this->getOutputTimezone($fieldDescription),
82
                'Y-m-d H:i:s'
83
            );
84
85
            return $this->globalCustomTransformers[$fieldType];
86
        }
87
88
        // Handle entity choice association type, transforming the value into entity
89
        if (TemplateRegistry::TYPE_CHOICE === $fieldType) {
90
            $className = $fieldDescription->getOption('class');
91
92
            if (null !== $className &&
93
                // NEXT_MAJOR: Replace this call with "$className === $fieldDescription->getTargetModel()".
94
                $this->hasFieldDescriptionAssociationWithClass($fieldDescription, $className)
95
            ) {
96
                return new ModelToIdTransformer($modelManager, $className);
97
            }
98
        }
99
100
        return null;
101
    }
102
103
    private function getOutputTimezone(FieldDescriptionInterface $fieldDescription): ?string
104
    {
105
        $outputTimezone = $fieldDescription->getOption('timezone');
106
107
        if (!$outputTimezone) {
108
            return null;
109
        }
110
111
        if ($outputTimezone instanceof \DateTimeZone) {
112
            return $outputTimezone->getName();
113
        }
114
115
        return $outputTimezone;
116
    }
117
118
    private function hasFieldDescriptionAssociationWithClass(
119
        FieldDescriptionInterface $fieldDescription,
120
        string $class
121
    ): bool {
122
        return (
123
            method_exists($fieldDescription, 'getTargetModel') && $class === $fieldDescription->getTargetModel()
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Sonata\AdminBundle\Admin\FieldDescriptionInterface as the method getTargetModel() does only exist in the following implementations of said interface: Sonata\AdminBundle\Tests...\Admin\FieldDescription, Sonata\AdminBundle\Tests...\Admin\FieldDescription.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
124
        ) || $class === $fieldDescription->getTargetEntity();
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...face::getTargetEntity() has been deprecated with message: since sonata-project/admin-bundle 3.69. Use `getTargetModel()` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
125
    }
126
}
127