Completed
Push — master ( d2c9b2...2cde9b )
by
unknown
08:05 queued 04:31
created

DeleteAction::_deleteMany()   B

Complexity

Conditions 4
Paths 1

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 16
nc 1
nop 1
dl 0
loc 29
ccs 18
cts 18
cp 1
crap 4
rs 8.5806
c 0
b 0
f 0
1
<?php
2
/**
3
 * Copyright 2016 - 2017, Cake Development Corporation (http://cakedc.com)
4
 *
5
 * Licensed under The MIT License
6
 * Redistributions of files must retain the above copyright notice.
7
 *
8
 * @copyright Copyright 2016 - 2017, Cake Development Corporation (http://cakedc.com)
9
 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
10
 */
11
12
namespace CakeDC\Api\Service\Action\Collection;
13
14
use CakeDC\Api\Exception\ValidationException;
15
use Cake\ORM\Entity;
16
use Cake\Utility\Hash;
17
18
/**
19
 * Class DeleteAction, uses POST and an array of entity ids to delete
20
 *
21
 * @package CakeDC\Api\Service\Action\Collection
22
 */
23
class DeleteAction extends CollectionAction
24
{
25
26
    /**
27
     * {@inheritdoc}
28
     */
29 2
    public function validates()
30
    {
31 2
        $datas = $this->data();
32 2
        $this->_validateDataIsArray($datas);
33 2
        $index = 0;
34 2
        $pkKey = $this->getTable()->getPrimaryKey();
35
        $errors = collection($datas)->reduce(function ($errors, $data) use ($pkKey, &$index) {
36 2
            $error = null;
37 2
            if (empty(Hash::get($data, $pkKey))) {
38
                $error = [
39 1
                    $pkKey => ['_empty' => 'Missing id'],
40 1
                ];
41 1
            }
42 2
            if ($error) {
43 1
                $errors[$index] = $error;
44 1
            }
45
46 2
            $index++;
47
48 2
            return $errors;
49 2
        }, []);
50
51 2
        if (!empty($errors)) {
52 1
            throw new ValidationException(__('Validation failed, some keys missing for delete action'), 0, null, $errors);
53
        }
54
55 1
        return true;
56
    }
57
58
    /**
59
     * Execute action. Returns the array of deleted id's
60
     *
61
     * @return mixed
62
     */
63 5
    public function execute()
64
    {
65 5
        $entities = $this->_newEntities([
66 5
            'accessibleFields' => [$this->getTable()->getPrimaryKey() => true
67 5
            ]]);
68
69 2
        return $this->_deleteMany($entities);
70
    }
71
72
    /**
73
     * Delete many entities, atomic
74
     *
75
     * @param array $entities entities
76
     * @return array
77
     */
78 2
    protected function _deleteMany($entities)
79
    {
80 2
        $deleted = [];
81 2
        $this->getTable()->getConnection()->transactional(function () use ($entities, &$deleted) {
82 2
            $errors = [];
83 2
            foreach ($entities as $index => $entity) {
84
                /**
85
                 * @var Entity $entity
86
                 */
87 2
                $entity->isNew(false);
88
                try {
89 2
                    $this->getTable()->deleteOrFail($entity, ['atomic' => false]);
90 2
                } catch (\InvalidArgumentException $ex) {
91 1
                    $errors[$index] = [
92 1
                        $entity->id => $ex->getMessage()
93 1
                    ];
94
                }
95 2
                $deleted[] = $entity->get($this->getTable()->getPrimaryKey());
0 ignored issues
show
Bug introduced by
It seems like $this->getTable()->getPrimaryKey() targeting Cake\ORM\Table::getPrimaryKey() can also be of type array; however, Cake\Datasource\EntityTrait::get() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
96 2
            }
97
98 2
            if ($errors) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errors of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
99 1
                throw new ValidationException(__('Validation failed'), 0, null, $errors);
100
            }
101
102 1
            return true;
103 2
        });
104
105 1
        return $deleted;
106
    }
107
}
108