ContactController::fixRequestAttributes()   D
last analyzed

Complexity

Conditions 9
Paths 18

Size

Total Lines 43
Code Lines 24

Duplication

Lines 6
Ratio 13.95 %

Importance

Changes 0
Metric Value
dl 6
loc 43
rs 4.909
c 0
b 0
f 0
cc 9
eloc 24
nc 18
nop 1
1
<?php
2
3
namespace Oro\Bundle\ContactBundle\Controller\Api\Rest;
4
5
use FOS\RestBundle\Controller\Annotations\NamePrefix;
6
use FOS\RestBundle\Controller\Annotations\QueryParam;
7
use FOS\RestBundle\Controller\Annotations\RouteResource;
8
use FOS\RestBundle\Routing\ClassResourceInterface;
9
10
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
11
12
use Symfony\Component\Form\FormInterface;
13
use Symfony\Component\HttpFoundation\Response;
14
15
use Oro\Bundle\AddressBundle\Utils\AddressApiUtils;
16
use Oro\Bundle\SecurityBundle\Annotation\Acl;
17
use Oro\Bundle\SecurityBundle\Annotation\AclAncestor;
18
use Oro\Bundle\SoapBundle\Controller\Api\Rest\RestController;
19
use Oro\Bundle\SoapBundle\Entity\Manager\ApiEntityManager;
20
use Oro\Bundle\SoapBundle\Form\Handler\ApiFormHandler;
21
use Oro\Bundle\SoapBundle\Request\Parameters\Filter\HttpDateTimeParameterFilter;
22
use Oro\Bundle\SoapBundle\Request\Parameters\Filter\IdentifierToReferenceFilter;
23
use Oro\Bundle\ContactBundle\Entity\Contact;
24
use Oro\Bundle\ContactBundle\Form\Type\ContactApiType;
25
26
/**
27
 * @RouteResource("contact")
28
 * @NamePrefix("oro_api_")
29
 *
30
 * @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
31
 */
32
class ContactController extends RestController implements ClassResourceInterface
33
{
34
    /**
35
     * REST GET list
36
     *
37
     * @QueryParam(
38
     *     name="page", requirements="\d+", nullable=true, description="Page number, starting from 1. Defaults to 1."
39
     * )
40
     * @QueryParam(
41
     *     name="limit", requirements="\d+", nullable=true, description="Number of items per page. defaults to 10."
42
     * )
43
     * @QueryParam(
44
     *     name="createdAt",
45
     *     requirements="\d{4}(-\d{2}(-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|([-+]\d{2}(:?\d{2})?))?)?)?)?",
46
     *     nullable=true,
47
     *     description="Date in RFC 3339 format. For example: 2009-11-05T13:15:30Z, 2008-07-01T22:35:17+08:00"
48
     * )
49
     * @QueryParam(
50
     *     name="updatedAt",
51
     *     requirements="\d{4}(-\d{2}(-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|([-+]\d{2}(:?\d{2})?))?)?)?)?",
52
     *     nullable=true,
53
     *     description="Date in RFC 3339 format. For example: 2009-11-05T13:15:30Z, 2008-07-01T22:35:17+08:00"
54
     * )
55
     * @QueryParam(
56
     *     name="ownerId",
57
     *     requirements="\d+",
58
     *     nullable=true,
59
     *     description="Id of owner user"
60
     * )
61
     * @QueryParam(
62
     *     name="ownerUsername",
63
     *     requirements=".+",
64
     *     nullable=true,
65
     *     description="Username of owner user"
66
     * )
67
     * @QueryParam(
68
     *     name="phone",
69
     *     requirements=".+",
70
     *     nullable=true,
71
     *     description="Phone number of contact"
72
     * )
73
     * @QueryParam(
74
     *     name="assigneeId",
75
     *     requirements="\d+",
76
     *     nullable=true,
77
     *     description="Id of assignee"
78
     * )
79
     * @QueryParam(
80
     *     name="assigneeUsername",
81
     *     requirements=".+",
82
     *     nullable=true,
83
     *     description="Username of assignee"
84
     * )
85
     * @ApiDoc(
86
     *      description="Get all contacts items",
87
     *      resource=true
88
     * )
89
     * @AclAncestor("oro_contact_view")
90
     *
91
     * @throws \Exception
92
     * @return Response
93
     */
94
    public function cgetAction()
95
    {
96
        $page  = (int)$this->getRequest()->get('page', 1);
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Bundle\Framework...ontroller::getRequest() has been deprecated with message: since version 2.4, to be removed in 3.0. Ask Symfony to inject the Request object into your controller method instead by type hinting it in the method's signature.

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...
97
        $limit = (int)$this->getRequest()->get('limit', self::ITEMS_PER_PAGE);
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Bundle\Framework...ontroller::getRequest() has been deprecated with message: since version 2.4, to be removed in 3.0. Ask Symfony to inject the Request object into your controller method instead by type hinting it in the method's signature.

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...
98
99
        $dateParamFilter  = new HttpDateTimeParameterFilter();
100
        $userIdFilter     = new IdentifierToReferenceFilter($this->getDoctrine(), 'OroUserBundle:User');
101
        $userNameFilter   = new IdentifierToReferenceFilter($this->getDoctrine(), 'OroUserBundle:User', 'username');
102
103
        $filterParameters = [
104
            'createdAt'        => $dateParamFilter,
105
            'updatedAt'        => $dateParamFilter,
106
            'ownerId'          => $userIdFilter,
107
            'ownerUsername'    => $userNameFilter,
108
            'assigneeId'       => $userIdFilter,
109
            'assigneeUsername' => $userNameFilter,
110
        ];
111
        $map              = [
112
            'ownerId'          => 'owner',
113
            'ownerUsername'    => 'owner',
114
            'assigneeId'       => 'assignedTo',
115
            'assigneeUsername' => 'assignedTo',
116
            'phone'            => 'phones.phone'
117
        ];
118
        $joins            = [
119
            'phones'
120
        ];
121
        $criteria = $this->getFilterCriteria($this->getSupportedQueryParameters('cgetAction'), $filterParameters, $map);
122
123
        return $this->handleGetListRequest($page, $limit, $criteria, $joins);
0 ignored issues
show
Documentation introduced by
$criteria is of type object<Doctrine\Common\Collections\Criteria>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
124
    }
125
126
    /**
127
     * REST GET item
128
     *
129
     * @param string $id
130
     *
131
     * @ApiDoc(
132
     *      description="Get contact item",
133
     *      resource=true
134
     * )
135
     * @AclAncestor("oro_contact_view")
136
     * @return Response
137
     */
138
    public function getAction($id)
139
    {
140
        return $this->handleGetRequest($id);
141
    }
142
143
    /**
144
     * REST PUT
145
     *
146
     * @param int $id Contact item id
147
     *
148
     * @ApiDoc(
149
     *      description="Update contact",
150
     *      resource=true
151
     * )
152
     * @AclAncestor("oro_contact_update")
153
     * @return Response
154
     */
155
    public function putAction($id)
156
    {
157
        return $this->handleUpdateRequest($id);
158
    }
159
160
    /**
161
     * Create new contact
162
     *
163
     * @ApiDoc(
164
     *      description="Create new contact",
165
     *      resource=true
166
     * )
167
     * @AclAncestor("oro_contact_create")
168
     */
169
    public function postAction()
170
    {
171
        return $this->handleCreateRequest();
172
    }
173
174
    /**
175
     * REST DELETE
176
     *
177
     * @param int $id
178
     *
179
     * @ApiDoc(
180
     *      description="Delete Contact",
181
     *      resource=true
182
     * )
183
     * @Acl(
184
     *      id="oro_contact_delete",
185
     *      type="entity",
186
     *      permission="DELETE",
187
     *      class="OroContactBundle:Contact"
188
     * )
189
     * @return Response
190
     */
191
    public function deleteAction($id)
192
    {
193
        return $this->handleDeleteRequest($id);
194
    }
195
196
    /**
197
     * Get entity Manager
198
     *
199
     * @return ApiEntityManager
200
     */
201
    public function getManager()
202
    {
203
        return $this->get('oro_contact.contact.manager.api');
204
    }
205
206
    /**
207
     * @return FormInterface
208
     */
209
    public function getForm()
210
    {
211
        return $this->get('oro_contact.form.contact.api');
212
    }
213
214
    /**
215
     * @return ApiFormHandler
216
     */
217
    public function getFormHandler()
218
    {
219
        return $this->get('oro_contact.form.handler.contact.api');
220
    }
221
222
    /**
223
     * @param Contact $entity
224
     *
225
     * @SuppressWarnings(PHPMD.NPathComplexity)
226
     */
227
    protected function fixRequestAttributes($entity)
228
    {
229
        $formAlias = $this->getFormAlias();
230
        $contactData = $this->getRequest()->request->get($formAlias);
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Bundle\Framework...ontroller::getRequest() has been deprecated with message: since version 2.4, to be removed in 3.0. Ask Symfony to inject the Request object into your controller method instead by type hinting it in the method's signature.

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...
231
232
        if (array_key_exists('accounts', $contactData)) {
233
            $accounts = $contactData['accounts'];
234
            $appendAccounts = array_key_exists('appendAccounts', $contactData)
235
                ? $contactData['appendAccounts']
236
                : array();
237
            $removeAccounts = array_key_exists('removeAccounts', $contactData)
238
                ? $contactData['removeAccounts']
239
                : array();
240
241
            if ($entity->getId()) {
242
                foreach ($entity->getAccounts() as $account) {
243
                    if (!in_array($account->getId(), $accounts)) {
244
                        $removeAccounts[] = $account->getId();
245
                    }
246
                }
247
            }
248
249
            $contactData['appendAccounts'] = array_merge($appendAccounts, $accounts);
250
            $contactData['removeAccounts'] = $removeAccounts;
251
            unset($contactData['accounts']);
252
253
            $this->getRequest()->request->set($formAlias, $contactData);
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Bundle\Framework...ontroller::getRequest() has been deprecated with message: since version 2.4, to be removed in 3.0. Ask Symfony to inject the Request object into your controller method instead by type hinting it in the method's signature.

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...
254
        }
255
256
        // @todo: just a temporary workaround until new API is implemented
257
        // - convert country name to country code (as result we accept both the code and the name)
258
        //   also it will be good to accept ISO3 code in future, need to be discussed with product owners
259
        // - convert region name to region code (as result we accept the combined code, code and name)
260
        // - move region name to region_text field for unknown region
261 View Code Duplication
        if (array_key_exists('addresses', $contactData)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
262
            foreach ($contactData['addresses'] as &$address) {
263
                AddressApiUtils::fixAddress($address, $this->get('doctrine.orm.entity_manager'));
264
            }
265
            $this->getRequest()->request->set($formAlias, $contactData);
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Bundle\Framework...ontroller::getRequest() has been deprecated with message: since version 2.4, to be removed in 3.0. Ask Symfony to inject the Request object into your controller method instead by type hinting it in the method's signature.

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...
266
        }
267
268
        parent::fixRequestAttributes($entity);
269
    }
270
271
    /**
272
     * @return string
273
     */
274
    protected function getFormAlias()
275
    {
276
        return ContactApiType::NAME;
277
    }
278
279
    /**
280
     * {@inheritDoc}
281
     */
282
    protected function fixFormData(array &$data, $entity)
283
    {
284
        /** @var Contact $entity */
285
        parent::fixFormData($data, $entity);
286
287
        unset($data['id']);
288
        unset($data['updatedAt']);
289
        unset($data['email']);
290
        unset($data['createdBy']);
291
        unset($data['updatedBy']);
292
293
        return true;
294
    }
295
}
296