Completed
Push — 1.9 ( 30c3e5...ca8b96 )
by
unknown
42:25
created

ContactController::fixRequestAttributes()   D

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 OroCRM\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
24
use OroCRM\Bundle\ContactBundle\Entity\Contact;
25
use OroCRM\Bundle\ContactBundle\Form\Type\ContactApiType;
26
27
/**
28
 * @RouteResource("contact")
29
 * @NamePrefix("oro_api_")
30
 *
31
 * @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
32
 */
33
class ContactController extends RestController implements ClassResourceInterface
34
{
35
    /**
36
     * REST GET list
37
     *
38
     * @QueryParam(
39
     *     name="page", requirements="\d+", nullable=true, description="Page number, starting from 1. Defaults to 1."
40
     * )
41
     * @QueryParam(
42
     *     name="limit", requirements="\d+", nullable=true, description="Number of items per page. defaults to 10."
43
     * )
44
     * @QueryParam(
45
     *     name="createdAt",
46
     *     requirements="\d{4}(-\d{2}(-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|([-+]\d{2}(:?\d{2})?))?)?)?)?",
47
     *     nullable=true,
48
     *     description="Date in RFC 3339 format. For example: 2009-11-05T13:15:30Z, 2008-07-01T22:35:17+08:00"
49
     * )
50
     * @QueryParam(
51
     *     name="updatedAt",
52
     *     requirements="\d{4}(-\d{2}(-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|([-+]\d{2}(:?\d{2})?))?)?)?)?",
53
     *     nullable=true,
54
     *     description="Date in RFC 3339 format. For example: 2009-11-05T13:15:30Z, 2008-07-01T22:35:17+08:00"
55
     * )
56
     * @QueryParam(
57
     *     name="ownerId",
58
     *     requirements="\d+",
59
     *     nullable=true,
60
     *     description="Id of owner user"
61
     * )
62
     * @QueryParam(
63
     *     name="ownerUsername",
64
     *     requirements=".+",
65
     *     nullable=true,
66
     *     description="Username of owner user"
67
     * )
68
     * @QueryParam(
69
     *     name="phone",
70
     *     requirements=".+",
71
     *     nullable=true,
72
     *     description="Phone number of contact"
73
     * )
74
     * @QueryParam(
75
     *     name="assigneeId",
76
     *     requirements="\d+",
77
     *     nullable=true,
78
     *     description="Id of assignee"
79
     * )
80
     * @QueryParam(
81
     *     name="assigneeUsername",
82
     *     requirements=".+",
83
     *     nullable=true,
84
     *     description="Username of assignee"
85
     * )
86
     * @ApiDoc(
87
     *      description="Get all contacts items",
88
     *      resource=true
89
     * )
90
     * @AclAncestor("orocrm_contact_view")
91
     *
92
     * @throws \Exception
93
     * @return Response
94
     */
95
    public function cgetAction()
96
    {
97
        $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...
98
        $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...
99
100
        $dateParamFilter  = new HttpDateTimeParameterFilter();
101
        $userIdFilter     = new IdentifierToReferenceFilter($this->getDoctrine(), 'OroUserBundle:User');
102
        $userNameFilter   = new IdentifierToReferenceFilter($this->getDoctrine(), 'OroUserBundle:User', 'username');
103
104
        $filterParameters = [
105
            'createdAt'        => $dateParamFilter,
106
            'updatedAt'        => $dateParamFilter,
107
            'ownerId'          => $userIdFilter,
108
            'ownerUsername'    => $userNameFilter,
109
            'assigneeId'       => $userIdFilter,
110
            'assigneeUsername' => $userNameFilter,
111
        ];
112
        $map              = [
113
            'ownerId'          => 'owner',
114
            'ownerUsername'    => 'owner',
115
            'assigneeId'       => 'assignedTo',
116
            'assigneeUsername' => 'assignedTo',
117
            'phone'            => 'phones.phone'
118
        ];
119
        $joins            = [
120
            'phones'
121
        ];
122
        $criteria = $this->getFilterCriteria($this->getSupportedQueryParameters('cgetAction'), $filterParameters, $map);
123
124
        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...
125
    }
126
127
    /**
128
     * REST GET item
129
     *
130
     * @param string $id
131
     *
132
     * @ApiDoc(
133
     *      description="Get contact item",
134
     *      resource=true
135
     * )
136
     * @AclAncestor("orocrm_contact_view")
137
     * @return Response
138
     */
139
    public function getAction($id)
140
    {
141
        return $this->handleGetRequest($id);
142
    }
143
144
    /**
145
     * REST PUT
146
     *
147
     * @param int $id Contact item id
148
     *
149
     * @ApiDoc(
150
     *      description="Update contact",
151
     *      resource=true
152
     * )
153
     * @AclAncestor("orocrm_contact_update")
154
     * @return Response
155
     */
156
    public function putAction($id)
157
    {
158
        return $this->handleUpdateRequest($id);
159
    }
160
161
    /**
162
     * Create new contact
163
     *
164
     * @ApiDoc(
165
     *      description="Create new contact",
166
     *      resource=true
167
     * )
168
     * @AclAncestor("orocrm_contact_create")
169
     */
170
    public function postAction()
171
    {
172
        return $this->handleCreateRequest();
173
    }
174
175
    /**
176
     * REST DELETE
177
     *
178
     * @param int $id
179
     *
180
     * @ApiDoc(
181
     *      description="Delete Contact",
182
     *      resource=true
183
     * )
184
     * @Acl(
185
     *      id="orocrm_contact_delete",
186
     *      type="entity",
187
     *      permission="DELETE",
188
     *      class="OroCRMContactBundle:Contact"
189
     * )
190
     * @return Response
191
     */
192
    public function deleteAction($id)
193
    {
194
        return $this->handleDeleteRequest($id);
195
    }
196
197
    /**
198
     * Get entity Manager
199
     *
200
     * @return ApiEntityManager
201
     */
202
    public function getManager()
203
    {
204
        return $this->get('orocrm_contact.contact.manager.api');
205
    }
206
207
    /**
208
     * @return FormInterface
209
     */
210
    public function getForm()
211
    {
212
        return $this->get('orocrm_contact.form.contact.api');
213
    }
214
215
    /**
216
     * @return ApiFormHandler
217
     */
218
    public function getFormHandler()
219
    {
220
        return $this->get('orocrm_contact.form.handler.contact.api');
221
    }
222
223
    /**
224
     * @param Contact $entity
225
     *
226
     * @SuppressWarnings(PHPMD.NPathComplexity)
227
     */
228
    protected function fixRequestAttributes($entity)
229
    {
230
        $formAlias = $this->getFormAlias();
231
        $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...
232
233
        if (array_key_exists('accounts', $contactData)) {
234
            $accounts = $contactData['accounts'];
235
            $appendAccounts = array_key_exists('appendAccounts', $contactData)
236
                ? $contactData['appendAccounts']
237
                : array();
238
            $removeAccounts = array_key_exists('removeAccounts', $contactData)
239
                ? $contactData['removeAccounts']
240
                : array();
241
242
            if ($entity->getId()) {
243
                foreach ($entity->getAccounts() as $account) {
244
                    if (!in_array($account->getId(), $accounts)) {
245
                        $removeAccounts[] = $account->getId();
246
                    }
247
                }
248
            }
249
250
            $contactData['appendAccounts'] = array_merge($appendAccounts, $accounts);
251
            $contactData['removeAccounts'] = $removeAccounts;
252
            unset($contactData['accounts']);
253
254
            $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...
255
        }
256
257
        // @todo: just a temporary workaround until new API is implemented
258
        // - convert country name to country code (as result we accept both the code and the name)
259
        //   also it will be good to accept ISO3 code in future, need to be discussed with product owners
260
        // - convert region name to region code (as result we accept the combined code, code and name)
261
        // - move region name to region_text field for unknown region
262 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...
263
            foreach ($contactData['addresses'] as &$address) {
264
                AddressApiUtils::fixAddress($address, $this->get('doctrine.orm.entity_manager'));
265
            }
266
            $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...
267
        }
268
269
        parent::fixRequestAttributes($entity);
270
    }
271
272
    /**
273
     * @return string
274
     */
275
    protected function getFormAlias()
276
    {
277
        return ContactApiType::NAME;
278
    }
279
280
    /**
281
     * {@inheritDoc}
282
     */
283
    protected function fixFormData(array &$data, $entity)
284
    {
285
        /** @var Contact $entity */
286
        parent::fixFormData($data, $entity);
287
288
        unset($data['id']);
289
        unset($data['updatedAt']);
290
        unset($data['email']);
291
        unset($data['createdBy']);
292
        unset($data['updatedBy']);
293
294
        return true;
295
    }
296
}
297