Passed
Push — master ( a74354...254a60 )
by Andrea
18:29 queued 11s
created

FiApiCoreCrudInlineControllerTrait::updateinline()   B

Complexity

Conditions 8
Paths 13

Size

Total Lines 50
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 33
nc 13
nop 3
dl 0
loc 50
ccs 0
cts 32
cp 0
crap 72
rs 8.1475
c 1
b 0
f 0
1
<?php
2
3
namespace Cdf\BiCoreBundle\Controller;
4
5
use Cdf\BiCoreBundle\Utils\Entity\EntityUtils;
6
use Cdf\BiCoreBundle\Utils\Entity\Finder;
7
use function count;
8
use DateTime;
9
use Doctrine\ORM\EntityManager;
10
use Exception;
11
use Symfony\Component\HttpFoundation\JsonResponse;
12
use Symfony\Component\HttpFoundation\Request;
13
use Symfony\Component\PropertyAccess\PropertyAccess;
14
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
15
16
trait FiApiCoreCrudInlineControllerTrait
17
{
18
    private function checkAggiornaRight($id, $token)
19
    {
20
        if (0 === $id) {
21
            if (!$this->getPermessi()->canCreate($this->getController())) {
0 ignored issues
show
Bug introduced by
It seems like getPermessi() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

21
            if (!$this->/** @scrutinizer ignore-call */ getPermessi()->canCreate($this->getController())) {
Loading history...
Bug introduced by
It seems like getController() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

21
            if (!$this->getPermessi()->canCreate($this->/** @scrutinizer ignore-call */ getController())) {
Loading history...
22
                throw new AccessDeniedException('Non si hanno i permessi per creare questo contenuto');
23
            }
24
        } else {
25
            if (!$this->getPermessi()->canUpdate($this->getController())) {
26
                throw new AccessDeniedException('Non si hanno i permessi per modificare questo contenuto');
27
            }
28
        }
29
        $isValidToken = $this->isCsrfTokenValid($id, $token);
0 ignored issues
show
Bug introduced by
It seems like isCsrfTokenValid() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

29
        /** @scrutinizer ignore-call */ 
30
        $isValidToken = $this->isCsrfTokenValid($id, $token);
Loading history...
30
31
        if (!$isValidToken) {
32
            throw $this->createNotFoundException('Token non valido');
0 ignored issues
show
Bug introduced by
It seems like createNotFoundException() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

32
            throw $this->/** @scrutinizer ignore-call */ createNotFoundException('Token non valido');
Loading history...
33
        }
34
    }
35
36
    /**
37
     * Inline existing table entity.
38
     */
39
    public function aggiorna(Request $request, $id, $token)
40
    {
41
        $this->checkAggiornaRight($id, $token);
42
        $values = $request->get('values');
43
44
        if (0 == $id) {
45
            $risultato = $this->insertinline($values, $token);
46
        } else {
47
            $risultato = $this->updateinline($id, $values, $token);
48
        }
49
50
        return $risultato;
51
    }
52
53
    protected function insertinline($values, $token)
54
    {
55
        $this->checkAggiornaRight(0, $token);
56
57
        /* @var $em EntityManager */
58
        $controller = $this->getController();
59
        $entityclass = $this->getEntityClassName();
0 ignored issues
show
Bug introduced by
It seems like getEntityClassName() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

59
        /** @scrutinizer ignore-call */ 
60
        $entityclass = $this->getEntityClassName();
Loading history...
60
61
        $em = $this->getDoctrine()->getManager();
0 ignored issues
show
Bug introduced by
It seems like getDoctrine() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

61
        $em = $this->/** @scrutinizer ignore-call */ getDoctrine()->getManager();
Loading history...
62
63
        //Insert
64
        $entity = new $entityclass();
65
66
        $accessor = PropertyAccess::createPropertyAccessor();
67
        foreach ($values as $value) {
68
            $fieldpieces = explode('.', $value['fieldname']);
69
            $table = $fieldpieces[0];
70
            //Si prende in considerazione solo i campi strettamente legati a questa entity
71
            if ($table == $controller && 2 == count($fieldpieces)) {
72
                $field = ucfirst($fieldpieces[1]);
73
                $fieldvalue = $this->getValueAggiorna($value);
74
                if ('join' == $value['fieldtype']) {
75
                    $entityfinder = new Finder($em);
76
                    $joinclass = $entityfinder->getClassNameFromEntityName($field);
77
                    $fieldvalue = $em->getRepository($joinclass)->find($fieldvalue);
78
                }
79
80
                if ($accessor->isWritable($entity, $field)) {
81
                    $accessor->setValue($entity, $field, $fieldvalue);
82
                } else {
83
                    throw new Exception($field.' non modificabile');
84
                }
85
            } else {
86
                continue;
87
            }
88
        }
89
        $em->persist($entity);
90
        $em->flush();
91
        $em->clear();
92
93
        return new JsonResponse(['errcode' => 0, 'message' => 'Registrazione eseguita']);
94
    }
95
96
    protected function updateinline($id, $values, $token)
97
    {
98
        $this->checkAggiornaRight($id, $token);
99
100
        /* @var $em EntityManager */
101
        $controller = $this->getController();
102
        $entityclass = $this->getEntityClassName();
103
104
        $em = $this->getDoctrine()->getManager();
105
        $queryBuilder = $em->createQueryBuilder();
106
107
        //Update
108
        $entity = $em->getRepository($entityclass)->find($id);
109
        if (!$entity) {
110
            throw $this->createNotFoundException('Impossibile trovare l\'entità '.$controller.' per il record con id '.$id);
111
        }
112
        $queryBuilder
113
                ->update($entityclass, 'u')
114
                ->where('u.id = :id')
115
                ->setParameter('id', $id);
116
117
        $querydaeseguire = false;
118
119
        foreach ($values as $value) {
120
            $fieldpieces = explode('.', $value['fieldname']);
121
            $table = $fieldpieces[0];
122
            //Si prende in considerazione solo i campi strettamente legati a questa entity
123
            if ($table == $controller && 2 == count($fieldpieces)) {
124
                $field = $fieldpieces[1];
125
                if ('join' == $value['fieldtype']) {
126
                    $field = lcfirst($field.'_id');
127
                }
128
                $entityutils = new EntityUtils($em);
129
                $property = $entityutils->getEntityProperties($field, $entity);
130
                $nomefunzioneget = $property['get'];
131
                if ($nomefunzioneget != $value['fieldvalue']) {
132
                    $querydaeseguire = true;
133
                    $fieldvalue = $this->getValueAggiorna($value);
134
                    $queryBuilder->set('u.'.$field, ':'.$field);
135
                    $queryBuilder->setParameter($field, $fieldvalue);
136
                }
137
            } else {
138
                continue;
139
            }
140
        }
141
        if ($querydaeseguire) {
142
            $queryBuilder->getQuery()->execute();
143
        }
144
145
        return new JsonResponse(['errcode' => 0, 'message' => 'Registrazione eseguita']);
146
    }
147
148
    private function getValueAggiorna($field)
149
    {
150
        $fieldvalue = $field['fieldvalue'];
151
        if ('' == $fieldvalue) {
152
            $fieldvalue = null;
153
        } else {
154
            $fieldtype = $field['fieldtype'];
155
            if ('boolean' == $fieldtype) {
156
                $fieldvalue = !('false' === $field['fieldvalue']);
157
            }
158
            if ('date' == $fieldtype) {
159
                $fieldvalue = DateTime::createFromFormat('d/m/Y', $field['fieldvalue']);
160
                if (false === $fieldvalue) {
161
                    throw new Exception('Formato data non valido');
162
                }
163
            }
164
            if ('datetime' == $fieldtype) {
165
                $fieldvalue = DateTime::createFromFormat('d/m/Y H:i', $field['fieldvalue']);
166
                if (false === $fieldvalue) {
167
                    throw new Exception('Formato data ora non valido');
168
                }
169
            }
170
        }
171
172
        return $fieldvalue;
173
    }
174
}
175