Completed
Push — master ( 047943...ada7af )
by Lee
05:25
created

DeleteElement::execute()   B

Complexity

Conditions 4
Paths 12

Size

Total Lines 31
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 4.0186

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 31
ccs 17
cts 19
cp 0.8947
rs 8.5806
cc 4
eloc 20
nc 12
nop 0
crap 4.0186
1
<?php
2
/**
3
 * This file is part of the Drest package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 *
8
 * @author Lee Davis
9
 * @copyright Copyright (c) Lee Davis <@leedavis81>
10
 * @link https://github.com/leedavis81/drest/blob/master/LICENSE
11
 * @license http://opensource.org/licenses/MIT The MIT X License (MIT)
12
 */
13
namespace Drest\Service\Action;
14
15
use Doctrine\ORM;
16
use DrestCommon\Response\Response;
17
use DrestCommon\ResultSet;
18
19
/**
20
 *
21
 * Delete an element action
22
 * @author Lee
23
 *
24
 * Rather than selecting then deleting: We could possibly just delete on supplied parameters
25
 */
26
class DeleteElement extends AbstractAction
27
{
28
29 2
    public function execute()
30
    {
31 2
        $matchedRoute = $this->getMatchedRoute();
32 2
        $classMetaData = $matchedRoute->getClassMetaData();
33 2
        $elementName = $classMetaData->getEntityAlias();
34
35 2
        $em = $this->getEntityManager();
36
37 2
        $qb = $em->createQueryBuilder()->select($elementName)->from($classMetaData->getClassName(), $elementName);
38 2
        foreach ($matchedRoute->getRouteParams() as $key => $value) {
39 2
            $qb->andWhere($elementName . '.' . $key . ' = :' . $key);
40 2
            $qb->setParameter($key, $value);
41 2
        }
42
43
        try {
44 2
            $object = $qb->getQuery()->getSingleResult(ORM\Query::HYDRATE_OBJECT);
45 2
        } catch (\Exception $e) {
46 1
            return $this->handleError($e, Response::STATUS_CODE_404);
47
        }
48
49
        try {
50 1
            $em->remove($object);
51 1
            $em->flush();
52
53 1
            $this->getResponse()->setStatusCode(Response::STATUS_CODE_200);
54
55 1
            return ResultSet::create(['successfully deleted'], 'response');
56
        } catch (\Exception $e) {
57
            return $this->handleError($e, Response::STATUS_CODE_500);
58
        }
59
    }
60
}
61