Passed
Push — develop ( 51f67e...bde052 )
by Andrea
12:00
created

FiApiCoreCrudInlineControllerTrait::updateinline()   B

Complexity

Conditions 8
Paths 13

Size

Total Lines 49
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 32
nc 13
nop 3
dl 0
loc 49
rs 8.1635
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
8
use function count;
9
10
use DateTime;
11
use Exception;
12
use Symfony\Component\HttpFoundation\JsonResponse;
13
use Symfony\Component\HttpFoundation\Request;
14
use Symfony\Component\PropertyAccess\PropertyAccess;
15
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
16
17
/**
18
 * @codeCoverageIgnore
19
 */
20
trait FiApiCoreCrudInlineControllerTrait
21
{
22
    private function checkAggiornaRight($id, $token)
23
    {
24
        if (0 === $id) {
25
            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

25
            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

25
            if (!$this->getPermessi()->canCreate($this->/** @scrutinizer ignore-call */ getController())) {
Loading history...
26
                throw new AccessDeniedException('Non si hanno i permessi per creare questo contenuto');
27
            }
28
        } else {
29
            if (!$this->getPermessi()->canUpdate($this->getController())) {
30
                throw new AccessDeniedException('Non si hanno i permessi per modificare questo contenuto');
31
            }
32
        }
33
        $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

33
        /** @scrutinizer ignore-call */ 
34
        $isValidToken = $this->isCsrfTokenValid($id, $token);
Loading history...
34
35
        if (!$isValidToken) {
36
            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

36
            throw $this->/** @scrutinizer ignore-call */ createNotFoundException('Token non valido');
Loading history...
37
        }
38
    }
39
40
    /**
41
     * Inline existing table entity.
42
     */
43
    public function aggiorna(Request $request, $id, $token)
44
    {
45
        $this->checkAggiornaRight($id, $token);
46
        $values = $request->get('values');
47
48
        if (0 == $id) {
49
            $risultato = $this->insertinline($values, $token);
50
        } else {
51
            $risultato = $this->updateinline($id, $values, $token);
52
        }
53
54
        return $risultato;
55
    }
56
57
    protected function insertinline($values, $token)
58
    {
59
        $this->checkAggiornaRight(0, $token);
60
61
        $controller = $this->getController();
62
        /** @phpstan-ignore-next-line */
63
        $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

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