Completed
Pull Request — development (#812)
by
unknown
04:28
created

CachesController::getCachesForSearchField()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 26
rs 9.504
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Oc\Controller\Backend;
6
7
use Doctrine\DBAL\Connection;
8
use Form\CachesFormType;
9
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\Response;
12
use Symfony\Component\Routing\Annotation\Route;
13
use Oc\Repository\Exception\RecordAlreadyExistsException;
14
use Oc\Repository\Exception\RecordNotFoundException;
15
use Oc\Repository\Exception\RecordNotPersistedException;
16
use Oc\Repository\Exception\RecordsNotFoundException;
17
use Oc\Repository\CachesRepository;
18
use Oc\Repository\UserRepository;
19
use Oc\Repository\SecurityRolesRepository;
20
use Oc\Entity\CachesEntity;
21
22
class CachesController extends AbstractController
23
{
24
    /**
25
     * @Route("/caches", name="caches_index")
26
     */
27
    public function index(Connection $connection, Request $request)
28
    : Response {
29
        $fetchedCaches = '';
30
31
        // create input field for caches_by_searchfield
32
        $form = $this->createForm(CachesFormType::class);
33
34
        // see: https://symfonycasts.com/screencast/symfony-forms/form-submit
35
        // handles the request (submit-button of the form), but only if there is a POST request
36
        $form->handleRequest($request);
37
        // if is true only if there is a request submitted and it is valid
38
        if ($form->isSubmitted() && $form->isValid()) {
39
            // read content of form input field
40
            $inputData = $form->getData();
41
42
            // send request to DB
43
            $fetchedCaches = $this->getCachesForSearchField($connection, $inputData["content_caches_searchfield"]);
44
        }
45
46
        if ($fetchedCaches === '') {
47
            return $this->render(
48
                'backend/caches/index.html.twig', [
49
                                                    'cachesForm' => $form->createView(),
50
                                                ]
51
            );
52
        } else {
53
            return $this->render(
54
                'backend/caches/basicview.html.twig', [
55
                                                          'cachesForm' => $form->createView(),
56
                                                          'caches_by_searchfield' => $fetchedCaches
57
                                                      ]
58
            );
59
        }
60
    }
61
62
    /**
63
     * @Route("/cache/{wpID}", name="cache_by_wp_oc_gc")
64
     */
65
    public function search_by_cache_wp(Connection $connection, string $wpID)
66
    : Response {
67
        $fetchedCaches = $this->getCacheDetails($connection, $wpID);
68
69
        return $this->render('backend/caches/detailview.html.twig', ['cache_by_id' => $fetchedCaches]);
70
    }
71
72
    /**
73
     *
74
     */
75
    function getCachesForSearchField(Connection $connection, string $searchtext)
76
    : array {
77
        //      so sieht die SQL-Vorlage aus..
78
        //        SELECT cache_id, name, wp_oc, user.username
79
        //        FROM caches
80
        //        INNER JOIN user ON caches.user_id = user.user_id
81
        //        WHERE wp_oc         =       "' . $searchtext . '"
82
        //        OR wp_gc            =       "' . $searchtext . '"
83
        //        OR caches.name     LIKE    "%' . $searchtext . '%"'
84
        //        OR user.username   LIKE    "%' . $searchtext . '%"'
85
        $qb = $connection->createQueryBuilder();
86
        $qb
87
            ->select('caches.cache_id', 'caches.name', 'caches.wp_oc', 'caches.wp_gc', 'user.username')
88
            ->from('caches')
89
            ->innerJoin('caches', 'user', 'user', 'caches.user_id = user.user_id')
90
            ->where('caches.wp_oc = :searchTerm')
91
            ->orWhere('caches.wp_gc = :searchTerm')
92
            ->orWhere('caches.name LIKE :searchTermLIKE')
93
            ->orWhere('user.username LIKE :searchTermLIKE')
94
            ->setParameters(['searchTerm' => $searchtext, 'searchTermLIKE' => '%' . $searchtext . '%'])
95
            ->orderBy('caches.wp_oc', 'ASC');
96
97
        $result = $qb->execute()->fetchAll();
98
99
        return $result;
100
    }
101
102
    /**
103
     * getCacheDetails_Nr3: Suche mittels Suchtext (Wegpunkte, Cachename) oder cache_id
104
     * Grundidee: diese Funktion holt sich die Daten über die fetch-Funktionen im Repository und
105
     *            ergänzt weitere Angaben aus anderen Tabellen, indem in den Entitys Beziehungen zwischen den Tabellen
106
     *            geknüpft werden (ManyToOne, OneToMany, ..)
107
     * Das konnte ich aber nicht wie gewollt implementieren.
108
     */
109
    function getCacheDetails_Nr3(Connection $connection, string $wpID = "", int $cacheId = 0)
0 ignored issues
show
Unused Code introduced by
The parameter $connection is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $wpID is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $cacheId is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
110
    : array {
111
        $fetchedCaches = [];
112
        //        $fetchedCache = [];
113
        //
114
        //        if ($cacheId != 0) {
115
        //            $request = new CachesRepository($connection);
116
        //
117
        //            $fetchedCache = $request->fetchOneBy(['cache_id' => $cacheId]);
118
        //
119
        //            if ($fetchedCache) {
120
        //                $wpID = $fetchedCache->getOCid();
121
        //            }
122
        //        }
123
        //
124
        //        if (!empty($wpID)) {
125
        //            $request = new CachesRepository($connection);
126
        //            $fetchedCache = $request->fetchOneBy(['wp_OC' => $wpID]);
127
        //
128
        //            if ($fetchedCache) {
129
        //                $fetchedCaches = $fetchedCache->convertEntityToArray();
130
        //            }
131
        //        }
132
133
        //        dd($fetchedCaches);
134
        //        die();
135
136
        return $fetchedCaches;
137
    }
138
139
    /**
140
     * getCacheDetails_Nr2: Suche mittels der cache_id
141
     * Alternative zu getCacheDetails() ??
142
     */
143
    function getCacheDetails_Nr2(Connection $connection, $searchText = '', int $id = 0)
0 ignored issues
show
Unused Code introduced by
The parameter $searchText is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
144
    : array {
145
        $fetchedCache = [];
146
        $securityRolesRepository = new SecurityRolesRepository($connection);
147
148
        if ($id != 0) {
149
            $requestCache = new CachesRepository($connection);
150
            $fetchedCache = $requestCache->fetchOneBy(['cache_id' => $id]);
151
152
            if ($fetchedCache) {
153
                // ersetze caches.user_id mit user.username
154
                $requestUser = new UserRepository($connection, $securityRolesRepository);
155
                $fetchedUser = $requestUser->fetchOneById(intval($fetchedCache->cacheId));
156
157
                $fetchedCache->userId = $fetchedUser->getUsername();
0 ignored issues
show
Documentation Bug introduced by
The property $userId was declared of type integer, but $fetchedUser->getUsername() is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
158
159
                // ersetze caches.status mit cache_status.name
160
                // ..
161
162
                // ersetze caches.type mit cache_type.name
163
                // ..
164
165
                // ersetze caches.size mit cache_size.name
166
                // ..
167
168
                // ?? ..
169
            }
170
        }
171
172
        dd($fetchedCache);
173
        die();
174
175
        return $fetchedCache;
0 ignored issues
show
Unused Code introduced by
return $fetchedCache; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
176
    }
177
178
    /**
179
     * getCacheDetails: Suche mittels Suchtext (Wegpunkte, Cachename) oder cache_id
180
     * Grundidee: diese Funktion baut sich die SQL-Anweisung selbst zusammen und holt die Daten aus der DB.
181
     */
182
    function getCacheDetails(Connection $connection, string $searchText = '', int $id = 0)
183
    : array {
184
        $fetchedCaches = [];
185
186
        if ($id != 0) {
187
            $request = new CachesRepository($connection);
188
189
            $fetchedCache = $request->fetchOneBy(['cache_id' => $id]);
190
191
            if ($fetchedCache) {
192
                $searchText = $fetchedCache->wpOc;
193
            }
194
        }
195
196
        if (!empty($searchText)) {
197
            //      so sieht die SQL-Vorlage aus..
198
            //            SELECT caches.cache_id, caches.name, caches.wp_oc, caches.wp_gc,
199
            //                   caches.date_hidden, caches.date_created, caches.is_publishdate, caches.latitude, caches.longitude,
200
            //                   caches.difficulty, caches.terrain, caches.size, caches.logpw,
201
            //                   cache_status.name as cache_status_name, cache_type.icon_large as cache_type_picture,
202
            //                   cache_size.name as cache_size_name, user.username
203
            //            FROM caches
204
            //            INNER JOIN user ON caches.user_id = user.user_id
205
            //            INNER JOIN cache_status ON caches.status = cache_status.id
206
            //            INNER JOIN cache_type ON caches.type = cache_type.id
207
            //            INNER JOIN cache_size ON caches.size = cache_size.id
208
            //            WHERE caches.wp_oc         = "' . $searchtext . '"
209
            $qb = $connection->createQueryBuilder();
210
            $qb
211
                ->select('caches.cache_id', 'caches.name', 'caches.wp_oc', 'caches.wp_gc')
212
                ->addSelect('caches.date_hidden', 'caches.date_created', 'caches.is_publishdate', 'caches.latitude', 'caches.longitude')
213
                ->addSelect('caches.difficulty', 'caches.terrain', 'caches.size', 'caches.logpw')
214
                ->addSelect('cache_status.name as cache_status_name', 'cache_type.icon_large as cache_type_picture')
215
                ->addSelect('cache_size.name as cache_size_name', 'user.username')
216
                ->from('caches')
217
                ->innerJoin('caches', 'user', 'user', 'caches.user_id = user.user_id')
218
                ->innerJoin('caches', 'cache_status', 'cache_status', 'caches.status = cache_status.id')
219
                ->innerJoin('caches', 'cache_type', 'cache_type', 'caches.type = cache_type.id')
220
                ->innerJoin('caches', 'cache_size', 'cache_size', 'caches.size = cache_size.id')
221
                ->where('caches.wp_oc = :searchTerm')
222
                ->setParameters(['searchTerm' => $searchText])
223
                ->orderBy('caches.wp_oc', 'DESC');
224
225
            $fetchedCaches = $qb->execute()->fetchAll();
226
227
            $array_size = count($fetchedCaches);
228
            for ($i = 0; $i < $array_size; $i ++) {
229
                // replace existing log passwords with something different
230
                if ($fetchedCaches[$i]["logpw"] != '') {
231
                    $fetchedCaches[$i]["logpw"] = 1;
232
                } else {
233
                    $fetchedCaches[$i]["logpw"] = 0;
234
                }
235
            }
236
        }
237
238
        return $fetchedCaches;
239
    }
240
}
241