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

CachesController::getCachesForSearchField()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 24
rs 9.536
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 = '0';
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 === '0') {
47
            return $this->render('backend/caches/index.html.twig', ['cachesForm' => $form->createView()]);
48
        } else {
49
            return $this->render(
50
                'backend/caches/basicsearch.html.twig', [
51
                                                          'cachesForm' => $form->createView(),
52
                                                          'caches_by_searchfield' => $fetchedCaches
53
                                                      ]
54
            );
55
        }
56
    }
57
58
    /**
59
     * @Route("/cache/{wpID}", name="cache_by_wp_oc_gc")
60
     */
61
    public function search_by_cache_wp(Connection $connection, string $wpID)
62
    : Response {
63
        $fetchedCaches = $this->getCacheDetails($connection, $wpID);
64
65
        return $this->render('backend/caches/detailsearch.html.twig', ['cache_by_id' => $fetchedCaches]);
66
    }
67
68
    /**
69
     *
70
     */
71
    function getCachesForSearchField(Connection $connection, string $searchtext)
72
    : array {
73
        //      so sieht die SQL-Vorlage aus..
74
        //        SELECT cache_id, name, wp_oc, user.username
75
        //        FROM caches
76
        //        INNER JOIN user ON caches.user_id = user.user_id
77
        //        WHERE wp_oc         =       "' . $searchtext . '"
78
        //        OR wp_gc            =       "' . $searchtext . '"
79
        //        OR caches.name     LIKE    "%' . $searchtext . '%"'
80
        $qb = $connection->createQueryBuilder();
81
        $qb
82
            ->select('caches.cache_id', 'caches.name', 'caches.wp_oc', 'caches.wp_gc', 'user.username')
83
            ->from('caches')
84
            ->innerJoin('caches', 'user', 'user', 'caches.user_id = user.user_id')
85
            ->where('caches.wp_oc = :searchTerm')
86
            ->orWhere('caches.wp_gc = :searchTerm')
87
            ->orWhere('caches.name LIKE :searchTermLIKE')
88
            ->setParameters(['searchTerm' => $searchtext, 'searchTermLIKE' => '%' . $searchtext . '%'])
89
            ->orderBy('caches.wp_oc', 'ASC');
90
91
        $result = $qb->execute()->fetchAll();
92
93
        return $result;
94
    }
95
96
    /**
97
     * getCacheDetails_Nr3: Suche mittels Suchtext (Wegpunkte, Cachename) oder cache_id
98
     * Grundidee: diese Funktion holt sich die Daten über die fetch-Funktionen im Repository und
99
     *            ergänzt weitere Angaben aus anderen Tabellen, indem in den Entitys Beziehungen zwischen den Tabellen
100
     *            geknüpft werden (ManyToOne, OneToMany, ..)
101
     * Das konnte ich aber nicht wie gewollt implementieren.
102
     */
103
    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...
104
    : array {
105
        $fetchedCaches = [];
106
//        $fetchedCache = [];
107
//
108
//        if ($cacheId != 0) {
109
//            $request = new CachesRepository($connection);
110
//
111
//            $fetchedCache = $request->fetchOneBy(['cache_id' => $cacheId]);
112
//
113
//            if ($fetchedCache) {
114
//                $wpID = $fetchedCache->getOCid();
115
//            }
116
//        }
117
//
118
//        if ($wpID != "") {
119
//            $request = new CachesRepository($connection);
120
//            $fetchedCache = $request->fetchOneBy(['wp_OC' => $wpID]);
121
//
122
//            if ($fetchedCache) {
123
//                $fetchedCaches = $fetchedCache->convertEntityToArray();
124
//            }
125
//        }
126
127
//        dd($fetchedCaches);
128
//        die();
129
130
        return $fetchedCaches;
131
    }
132
133
    /**
134
     * getCacheDetails_Nr2: Suche mittels der cache_id
135
     * Alternative zu getCacheDetails() ??
136
     */
137
    function getCacheDetails_Nr2(Connection $connection, int $id)
138
    : array {
139
        $fetchedCache = [];
140
        $securityRolesRepository = new SecurityRolesRepository($connection);
141
142
        if ($id != 0) {
143
            $requestCache = new CachesRepository($connection);
144
            $fetchedCache = $requestCache->fetchOneBy(['cache_id' => $id]);
145
146
            if ($fetchedCache) {
147
                // ersetze caches.user_id mit user.username
148
                $requestUser = new UserRepository($connection, $securityRolesRepository);
149
                $fetchedUser = $requestUser->fetchOneById(intval($fetchedCache->cacheId));
150
151
                $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...
152
153
                // ersetze caches.status mit cache_status.name
154
                // ..
155
156
                // ersetze caches.type mit cache_type.name
157
                // ..
158
159
                // ersetze caches.size mit cache_size.name
160
                // ..
161
162
                // ?? ..
163
            }
164
        }
165
166
        dd($fetchedCache);
167
        die();
168
169
        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...
170
    }
171
172
    /**
173
     * getCacheDetails: Suche mittels Suchtext (Wegpunkte, Cachename) oder cache_id
174
     * Grundidee: diese Funktion baut sich die SQL-Anweisung selbst zusammen und holt die Daten aus der DB.
175
     */
176
    function getCacheDetails(Connection $connection, string $searchText = "", int $id = 0)
177
    : array {
178
        $fetchedCaches = [];
179
180
        if ($id != 0) {
181
            $request = new CachesRepository($connection);
182
183
            $fetchedCache = $request->fetchOneBy(['cache_id' => $id]);
184
185
            if ($fetchedCache) {
186
                $searchText = $fetchedCache->wpOc;
187
            }
188
        }
189
190
        if ($searchText != "") {
191
            //      so sieht die SQL-Vorlage aus..
192
            //            SELECT caches.cache_id, caches.name, caches.wp_oc, caches.wp_gc,
193
            //                   caches.date_hidden, caches.date_created, caches.is_publishdate, caches.latitude, caches.longitude,
194
            //                   caches.difficulty, caches.terrain, caches.size, caches.logpw,
195
            //                   cache_status.name as cache_status_name, cache_type.icon_large as cache_type_picture,
196
            //                   cache_size.name as cache_size_name, user.username
197
            //            FROM caches
198
            //            INNER JOIN user ON caches.user_id = user.user_id
199
            //            INNER JOIN cache_status ON caches.status = cache_status.id
200
            //            INNER JOIN cache_type ON caches.type = cache_type.id
201
            //            INNER JOIN cache_size ON caches.size = cache_size.id
202
            //            WHERE caches.wp_oc         = "' . $searchtext . '"
203
            $qb = $connection->createQueryBuilder();
204
            $qb
205
                ->select('caches.cache_id', 'caches.name', 'caches.wp_oc', 'caches.wp_gc')
206
                ->addSelect('caches.date_hidden', 'caches.date_created', 'caches.is_publishdate', 'caches.latitude', 'caches.longitude')
207
                ->addSelect('caches.difficulty', 'caches.terrain', 'caches.size', 'caches.logpw')
208
                ->addSelect('cache_status.name as cache_status_name', 'cache_type.icon_large as cache_type_picture')
209
                ->addSelect('cache_size.name as cache_size_name', 'user.username')
210
                ->from('caches')
211
                ->innerJoin('caches', 'user', 'user', 'caches.user_id = user.user_id')
212
                ->innerJoin('caches', 'cache_status', 'cache_status', 'caches.status = cache_status.id')
213
                ->innerJoin('caches', 'cache_type', 'cache_type', 'caches.type = cache_type.id')
214
                ->innerJoin('caches', 'cache_size', 'cache_size', 'caches.size = cache_size.id')
215
                ->where('caches.wp_oc = :searchTerm')
216
                ->setParameters(['searchTerm' => $searchText])
217
                ->orderBy('caches.wp_oc', 'DESC');
218
219
            $fetchedCaches = $qb->execute()->fetchAll();
220
221
            $array_size = count($fetchedCaches);
222
            for ($i = 0; $i < $array_size; $i ++) {
223
                // replace existing log passwords with something different
224
                // nur der Teil mit den Bilderzuweisungen müsste nochmal überdacht werden..
225
                if ($fetchedCaches[$i]["logpw"] != "") {
226
                    $fetchedCaches[$i]["logpw"] = 1;
227
                } else {
228
                    $fetchedCaches[$i]["logpw"] = 0;
229
                }
230
231
                // replace cache type information with picture links
232
                // auch hier müsste die Bildzuweisung nochmal überarbeitet werden..
233
                $fetchedCaches[$i]["cache_type_picture"] =
234
                    "https://www.opencaching.de/resource2/ocstyle/images/cacheicon/"
235
                    . $fetchedCaches[$i]["cache_type_picture"];
236
            }
237
        }
238
239
        //dd($fetchedCaches);
240
        //die();
241
242
        return $fetchedCaches;
243
    }
244
}
245