Passed
Push — task/2976_TYPO3.11_compatibili... ( 4d1a77...3b9190 )
by Rafael
03:39
created

LastSearchesRepository   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 125
Duplicated Lines 0 %

Test Coverage

Coverage 98.18%

Importance

Changes 0
Metric Value
wmc 10
eloc 53
dl 0
loc 125
ccs 54
cts 55
cp 0.9818
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A resolveNextSequenceIdForGivenLimit() 0 16 2
A getLastSearchesResultSet() 0 13 1
A add() 0 21 2
A findAllKeywords() 0 13 3
A update() 0 15 2
1
<?php
2
namespace ApacheSolrForTypo3\Solr\Domain\Search\LastSearches;
3
4
/***************************************************************
5
 *  Copyright notice
6
 *
7
 *  (c) 2010-2017 dkd Internet Service GmbH <[email protected]>
8
 *  All rights reserved
9
 *
10
 *  This script is part of the TYPO3 project. The TYPO3 project is
11
 *  free software; you can redistribute it and/or modify
12
 *  it under the terms of the GNU General Public License as published by
13
 *  the Free Software Foundation; either version 3 of the License, or
14
 *  (at your option) any later version.
15
 *
16
 *  The GNU General Public License can be found at
17
 *  http://www.gnu.org/copyleft/gpl.html.
18
 *
19
 *  This script is distributed in the hope that it will be useful,
20
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 *  GNU General Public License for more details.
23
 *
24
 *  This copyright notice MUST APPEAR in all copies of the script!
25
 ***************************************************************/
26
27
use ApacheSolrForTypo3\Solr\System\Records\AbstractRepository;
28
29
class LastSearchesRepository extends AbstractRepository
30
{
31
    /**
32
     * @var string
33
     */
34
    protected $table = 'tx_solr_last_searches';
35
36
    /**
37
     * Finds the last searched keywords from the database
38
     *
39
     * @param int $limit
40
     * @return array An array containing the last searches of the current user
41
     */
42 7
    public function findAllKeywords($limit = 10) : array
43
    {
44 7
        $lastSearchesResultSet = $this->getLastSearchesResultSet($limit);
45 7
        if (empty($lastSearchesResultSet)) {
46 1
            return [];
47
        }
48
49 6
        $lastSearches = [];
50 6
        foreach ($lastSearchesResultSet as $row) {
51 6
            $lastSearches[] = html_entity_decode($row['keywords'], ENT_QUOTES, 'UTF-8');
52
        }
53
54 6
        return $lastSearches;
55
    }
56
57
    /**
58
     * Returns all last searches
59
     *
60
     * @param $limit
61
     * @return array
62
     */
63 6
    protected function getLastSearchesResultSet($limit) : array
64
    {
65 6
        $queryBuilder = $this->getQueryBuilder();
66
        return $queryBuilder
0 ignored issues
show
Deprecated Code introduced by
The function Doctrine\DBAL\ForwardCom...lity\Result::fetchAll() has been deprecated: Use fetchAllNumeric(), fetchAllAssociative() or fetchFirstColumn() instead. ( Ignorable by Annotation )

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

66
        return /** @scrutinizer ignore-deprecated */ $queryBuilder

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
67 6
            ->select('keywords')
68 6
            ->addSelectLiteral(
69 6
                $queryBuilder->expr()->max('tstamp','maxtstamp')
70
            )
71 6
            ->from($this->table)
72
            // There is no support for DISTINCT, a ->groupBy() has to be used instead.
73 6
            ->groupBy('keywords')
74 6
            ->orderBy('maxtstamp', 'DESC')
75 6
            ->setMaxResults($limit)->execute()->fetchAll();
76
    }
77
78
    /**
79
     * Adds keywords to last searches or updates the oldest row by given limit.
80
     *
81
     * @param string $lastSearchesKeywords
82
     * @param int $lastSearchesLimit
83
     * @return void
84
     */
85 4
    public function add(string $lastSearchesKeywords, int $lastSearchesLimit)
86
    {
87 4
        $nextSequenceId = $this->resolveNextSequenceIdForGivenLimit($lastSearchesLimit);
88 4
        $rowsCount = $this->count();
89 4
        if ($nextSequenceId < $rowsCount) {
90 2
            $this->update([
91 2
                'sequence_id' => $nextSequenceId,
92 2
                'keywords' => $lastSearchesKeywords
93
            ]);
94 2
            return;
95
        }
96
97 2
        $queryBuilder = $this->getQueryBuilder();
98
        $queryBuilder
99 2
            ->insert($this->table)
100 2
            ->values([
101 2
                'sequence_id' => $nextSequenceId,
102 2
                'keywords' => $lastSearchesKeywords,
103 2
                'tstamp' => time()
104
            ])
105 2
            ->execute();
106 2
    }
107
108
    /**
109
     * Resolves next sequence id by given last searches limit.
110
     *
111
     * @param int $lastSearchesLimit
112
     * @return int
113
     */
114 4
    protected function resolveNextSequenceIdForGivenLimit(int $lastSearchesLimit) : int
115
    {
116 4
        $nextSequenceId = 0;
117
118 4
        $queryBuilder = $this->getQueryBuilder();
119 4
        $result = $queryBuilder->select('sequence_id')
0 ignored issues
show
Deprecated Code introduced by
The function Doctrine\DBAL\ForwardCompatibility\Result::fetch() has been deprecated: Use fetchNumeric(), fetchAssociative() or fetchOne() instead. ( Ignorable by Annotation )

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

119
        $result = /** @scrutinizer ignore-deprecated */ $queryBuilder->select('sequence_id')

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
120 4
            ->from($this->table)
121 4
            ->orderBy('tstamp', 'DESC')
122 4
            ->setMaxResults(1)
123 4
            ->execute()->fetch();
124
125 4
        if (!empty($result)) {
126 4
            $nextSequenceId = ($result['sequence_id'] + 1) % $lastSearchesLimit;
127
        }
128
129 4
        return $nextSequenceId;
130
    }
131
132
    /**
133
     * Updates last searches row by using sequence_id from given $lastSearchesRow array
134
     *
135
     * @param array $lastSearchesRow
136
     * @return void
137
     * @throws \InvalidArgumentException
138
     */
139 2
    protected function update(array $lastSearchesRow)
140
    {
141 2
        $queryBuilder = $this->getQueryBuilder();
142
143 2
        $affectedRows = $queryBuilder
144 2
            ->update($this->table)
145 2
            ->where(
146 2
                $queryBuilder->expr()->eq('sequence_id', $queryBuilder->createNamedParameter($lastSearchesRow['sequence_id']))
0 ignored issues
show
Bug introduced by
$queryBuilder->expr()->e...hesRow['sequence_id'])) of type string is incompatible with the type Doctrine\DBAL\Query\Expr...on|array<integer,mixed> expected by parameter $predicates of TYPO3\CMS\Core\Database\...y\QueryBuilder::where(). ( Ignorable by Annotation )

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

146
                /** @scrutinizer ignore-type */ $queryBuilder->expr()->eq('sequence_id', $queryBuilder->createNamedParameter($lastSearchesRow['sequence_id']))
Loading history...
147
            )
148 2
            ->set('tstamp', time())
149 2
            ->set('keywords', $lastSearchesRow['keywords'])
150 2
            ->execute();
151
152 2
        if ($affectedRows < 1) {
153
            throw new \InvalidArgumentException(vsprintf('By trying to update last searches row with values "%s" nothing was updated, make sure the given "sequence_id" exists in database.', [\json_encode($lastSearchesRow)]), 1502717923);
154
        }
155 2
    }
156
}
157