Completed
Push — 3.x ( 31e7c2...dbd908 )
by Jordi Sala
03:57
created

hasFieldDescriptionAssociationWithClass()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 2
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\Action;
15
16
use Sonata\AdminBundle\Admin\FieldDescriptionInterface;
17
use Sonata\AdminBundle\Admin\Pool;
18
use Sonata\AdminBundle\Twig\Extension\SonataAdminExtension;
19
use Symfony\Component\HttpFoundation\JsonResponse;
20
use Symfony\Component\HttpFoundation\Request;
21
use Symfony\Component\HttpFoundation\Response;
22
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
23
use Symfony\Component\PropertyAccess\PropertyPath;
24
use Symfony\Component\Validator\Validator\ValidatorInterface;
25
use Twig\Environment;
26
27
final class SetObjectFieldValueAction
28
{
29
    /**
30
     * @var Pool
31
     */
32
    private $pool;
33
34
    /**
35
     * @var Environment
36
     */
37
    private $twig;
38
39
    /**
40
     * @var ValidatorInterface
41
     */
42
    private $validator;
43
44
    public function __construct(Environment $twig, Pool $pool, $validator)
45
    {
46
        // NEXT_MAJOR: Move ValidatorInterface check to method signature
47
        if (!($validator instanceof ValidatorInterface)) {
48
            throw new \InvalidArgumentException(sprintf(
49
                'Argument 3 is an instance of %s, expecting an instance of %s',
50
                \get_class($validator),
51
                ValidatorInterface::class
52
            ));
53
        }
54
        $this->pool = $pool;
55
        $this->twig = $twig;
56
        $this->validator = $validator;
57
    }
58
59
    /**
60
     * @throws NotFoundHttpException
61
     */
62
    public function __invoke(Request $request): JsonResponse
63
    {
64
        $field = $request->get('field');
65
        $code = $request->get('code');
66
        $objectId = $request->get('objectId');
67
        $value = $originalValue = $request->get('value');
68
        $context = $request->get('context');
69
70
        $admin = $this->pool->getInstance($code);
71
        $admin->setRequest($request);
72
73
        // alter should be done by using a post method
74
        if (!$request->isXmlHttpRequest()) {
75
            return new JsonResponse('Expected an XmlHttpRequest request header', Response::HTTP_METHOD_NOT_ALLOWED);
76
        }
77
78
        if (Request::METHOD_POST !== $request->getMethod()) {
79
            return new JsonResponse(sprintf(
80
                'Invalid request method given "%s", %s expected',
81
                $request->getMethod(),
82
                Request::METHOD_POST
83
            ), Response::HTTP_METHOD_NOT_ALLOWED);
84
        }
85
86
        $rootObject = $object = $admin->getObject($objectId);
87
88
        if (!$object) {
89
            return new JsonResponse('Object does not exist', Response::HTTP_NOT_FOUND);
90
        }
91
92
        // check user permission
93
        if (false === $admin->hasAccess('edit', $object)) {
94
            return new JsonResponse('Invalid permissions', Response::HTTP_FORBIDDEN);
95
        }
96
97
        if ('list' === $context) {
98
            $fieldDescription = $admin->getListFieldDescription($field);
99
        } else {
100
            return new JsonResponse('Invalid context', Response::HTTP_BAD_REQUEST);
101
        }
102
103
        if (!$fieldDescription) {
104
            return new JsonResponse('The field does not exist', Response::HTTP_BAD_REQUEST);
105
        }
106
107
        if (!$fieldDescription->getOption('editable')) {
108
            return new JsonResponse('The field cannot be edited, editable option must be set to true', Response::HTTP_BAD_REQUEST);
109
        }
110
111
        $propertyPath = new PropertyPath($field);
112
113
        // If property path has more than 1 element, take the last object in order to validate it
114
        if ($propertyPath->getLength() > 1) {
115
            $object = $this->pool->getPropertyAccessor()->getValue($object, $propertyPath->getParent());
0 ignored issues
show
Bug introduced by
It seems like $propertyPath->getParent() can be null; however, getValue() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
116
117
            $elements = $propertyPath->getElements();
118
            $field = end($elements);
119
            $propertyPath = new PropertyPath($field);
120
        }
121
122
        // Handle date and datetime types have setter expecting a DateTime object
123
        if ('' !== $value && \in_array($fieldDescription->getType(), ['date', 'datetime'], true)) {
124
            $value = new \DateTime($value);
125
        }
126
127
        // Handle boolean type transforming the value into a boolean
128
        if ('' !== $value && 'boolean' === $fieldDescription->getType()) {
129
            $value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
130
        }
131
132
        // Handle entity choice association type, transforming the value into entity
133
        if ('' !== $value
134
            && 'choice' === $fieldDescription->getType()
135
            && null !== $fieldDescription->getOption('class')
136
            // NEXT_MAJOR: Replace this call with "$fieldDescription->getOption('class') === $fieldDescription->getTargetModel()".
137
            && $this->hasFieldDescriptionAssociationWithClass($fieldDescription, $fieldDescription->getOption('class'))
138
        ) {
139
            $value = $admin->getModelManager()->find($fieldDescription->getOption('class'), $value);
140
141
            if (!$value) {
142
                return new JsonResponse(sprintf(
143
                    'Edit failed, object with id: %s not found in association: %s.',
144
                    $originalValue,
145
                    $field
146
                ), Response::HTTP_NOT_FOUND);
147
            }
148
        }
149
150
        $this->pool->getPropertyAccessor()->setValue($object, $propertyPath, '' !== $value ? $value : null);
151
152
        $violations = $this->validator->validate($object);
153
154
        if (\count($violations)) {
155
            $messages = [];
156
157
            foreach ($violations as $violation) {
158
                $messages[] = $violation->getMessage();
159
            }
160
161
            return new JsonResponse(implode("\n", $messages), Response::HTTP_BAD_REQUEST);
162
        }
163
164
        $admin->update($object);
0 ignored issues
show
Bug introduced by
It seems like $object can also be of type array; however, Sonata\AdminBundle\Admin...iderInterface::update() does only seem to accept object, 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...
165
166
        // render the widget
167
        // todo : fix this, the twig environment variable is not set inside the extension ...
168
        $extension = $this->twig->getExtension(SonataAdminExtension::class);
169
        \assert($extension instanceof SonataAdminExtension);
170
171
        $content = $extension->renderListElement($this->twig, $rootObject, $fieldDescription);
0 ignored issues
show
Bug introduced by
It seems like $rootObject defined by $object = $admin->getObject($objectId) on line 86 can also be of type null; however, Sonata\AdminBundle\Twig\...on::renderListElement() does only seem to accept object, 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...
172
173
        return new JsonResponse($content, Response::HTTP_OK);
174
    }
175
176
    private function hasFieldDescriptionAssociationWithClass(FieldDescriptionInterface $fieldDescription, string $class): bool
177
    {
178
        return (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...
179
            || $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...
180
    }
181
}
182