firefly-iii/app/Support/Search/Search.php

315 lines
10 KiB
PHP
Raw Normal View History

2015-02-27 04:09:23 -06:00
<?php
/**
* Search.php
2017-10-21 01:40:00 -05:00
* Copyright (c) 2017 thegrumpydictator@gmail.com
*
2017-10-21 01:40:00 -05:00
* This file is part of Firefly III.
*
2017-10-21 01:40:00 -05:00
* Firefly III is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Firefly III is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
2017-12-17 07:44:05 -06:00
* along with Firefly III. If not, see <http://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
2015-02-27 04:09:23 -06:00
namespace FireflyIII\Support\Search;
2017-10-30 11:28:43 -05:00
use Carbon\Carbon;
use FireflyIII\Helpers\Collector\TransactionCollectorInterface;
2017-04-28 13:08:25 -05:00
use FireflyIII\Helpers\Filter\InternalTransferFilter;
2016-11-06 07:52:31 -06:00
use FireflyIII\Models\Transaction;
use FireflyIII\User;
2015-03-20 12:21:14 -05:00
use Illuminate\Support\Collection;
2016-11-06 07:52:31 -06:00
use Log;
2015-02-27 04:09:23 -06:00
/**
2017-11-15 05:25:49 -06:00
* Class Search.
2015-02-27 04:09:23 -06:00
*/
class Search implements SearchInterface
{
2016-11-06 07:52:31 -06:00
/** @var int */
private $limit = 100;
/** @var Collection */
private $modifiers;
2017-11-15 05:25:49 -06:00
/** @var string */
private $originalQuery = '';
2016-11-06 07:52:31 -06:00
/** @var User */
private $user;
/** @var array */
2018-04-02 07:50:17 -05:00
private $validModifiers;
2017-11-15 05:25:49 -06:00
/** @var array */
private $words = [];
/**
* Search constructor.
*/
public function __construct()
{
$this->modifiers = new Collection;
2017-07-07 01:09:42 -05:00
$this->validModifiers = (array)config('firefly.search_modifiers');
if ('testing' === config('app.env')) {
Log::warning(sprintf('%s should not be instantiated in the TEST environment!', \get_class($this)));
}
}
/**
* @return string
*/
public function getWordsAsString(): string
{
2018-04-02 07:50:17 -05:00
$string = implode(' ', $this->words);
2018-07-26 22:03:37 -05:00
if ('' === $string) {
2018-04-27 23:23:13 -05:00
return \is_string($this->originalQuery) ? $this->originalQuery : '';
}
2017-03-30 11:43:12 -05:00
return $string;
}
/**
* @return bool
*/
public function hasModifiers(): bool
{
return $this->modifiers->count() > 0;
}
/**
* @param string $query
*/
2018-07-26 22:03:37 -05:00
public function parseQuery(string $query): void
{
$filteredQuery = $query;
$this->originalQuery = $query;
$pattern = '/[a-z_]*:[0-9a-z-.]*/i';
$matches = [];
preg_match_all($pattern, $query, $matches);
foreach ($matches[0] as $match) {
$this->extractModifier($match);
$filteredQuery = str_replace($match, '', $filteredQuery);
}
$filteredQuery = trim(str_replace(['"', "'"], '', $filteredQuery));
2018-04-27 23:23:13 -05:00
if (\strlen($filteredQuery) > 0) {
2017-02-19 02:07:14 -06:00
$this->words = array_map('trim', explode(' ', $filteredQuery));
}
}
2016-11-06 07:52:31 -06:00
2015-02-27 04:09:23 -06:00
/**
* @return Collection
*/
public function searchTransactions(): Collection
2015-02-27 04:09:23 -06:00
{
2017-07-15 10:19:12 -05:00
Log::debug('Start of searchTransactions()');
2016-11-06 07:52:31 -06:00
$pageSize = 100;
$processed = 0;
$page = 1;
$result = new Collection();
2017-07-15 10:19:12 -05:00
$startTime = microtime(true);
2016-11-06 07:52:31 -06:00
do {
/** @var TransactionCollectorInterface $collector */
$collector = app(TransactionCollectorInterface::class);
2017-09-03 05:56:45 -05:00
$collector->setAllAssetAccounts()->setLimit($pageSize)->setPage($page)->withOpposingAccount();
2017-02-19 02:07:14 -06:00
if ($this->hasModifiers()) {
2017-02-19 00:41:12 -06:00
$collector->withOpposingAccount()->withCategoryInformation()->withBudgetInformation();
}
2017-10-30 11:28:43 -05:00
// some modifiers can be applied to the collector directly.
$collector = $this->applyModifiers($collector);
2017-04-28 13:08:25 -05:00
$collector->removeFilter(InternalTransferFilter::class);
2018-08-13 23:40:04 -05:00
$set = $collector->getPaginatedTransactions()->getCollection();
2016-11-06 07:52:31 -06:00
Log::debug(sprintf('Found %d journals to check. ', $set->count()));
// Filter transactions that match the given triggers.
$filtered = $set->filter(
2017-08-12 03:27:45 -05:00
function (Transaction $transaction) {
if ($this->matchModifiers($transaction)) {
2016-11-06 07:52:31 -06:00
return $transaction;
}
// return false:
return false;
2015-03-20 12:21:14 -05:00
}
2016-11-06 07:52:31 -06:00
);
2016-11-06 07:52:31 -06:00
Log::debug(sprintf('Found %d journals that match.', $filtered->count()));
2015-03-20 12:21:14 -05:00
2016-11-06 07:52:31 -06:00
// merge:
/** @var Collection $result */
$result = $result->merge($filtered);
Log::debug(sprintf('Total count is now %d', $result->count()));
// Update counters
2017-11-15 05:25:49 -06:00
++$page;
2018-04-27 23:23:13 -05:00
$processed += \count($set);
2016-11-06 07:52:31 -06:00
Log::debug(sprintf('Page is now %d, processed is %d', $page, $processed));
// Check for conditions to finish the loop
$reachedEndOfList = $set->count() < 1;
$foundEnough = $result->count() >= $this->limit;
Log::debug(sprintf('reachedEndOfList: %s', var_export($reachedEndOfList, true)));
Log::debug(sprintf('foundEnough: %s', var_export($foundEnough, true)));
2017-07-15 10:19:12 -05:00
// break at some point so the script does not crash:
$currentTime = microtime(true) - $startTime;
Log::debug(sprintf('Have been running for %f seconds.', $currentTime));
} while (!$reachedEndOfList && !$foundEnough && $currentTime <= 30);
2016-11-06 07:52:31 -06:00
$result = $result->slice(0, $this->limit);
2015-03-20 12:30:17 -05:00
2016-11-06 07:52:31 -06:00
return $result;
}
/**
* @param int $limit
*/
2018-07-26 22:03:37 -05:00
public function setLimit(int $limit): void
2016-11-06 07:52:31 -06:00
{
$this->limit = $limit;
}
2017-02-05 09:16:15 -06:00
/**
* @param User $user
*/
2018-07-26 22:03:37 -05:00
public function setUser(User $user): void
2017-02-05 09:16:15 -06:00
{
$this->user = $user;
}
2017-12-17 07:30:53 -06:00
/**
* @param TransactionCollectorInterface $collector
2017-12-17 07:30:53 -06:00
*
* @return TransactionCollectorInterface
2018-07-28 03:45:16 -05:00
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
2017-12-17 07:30:53 -06:00
*/
private function applyModifiers(TransactionCollectorInterface $collector): TransactionCollectorInterface
2017-10-30 11:28:43 -05:00
{
foreach ($this->modifiers as $modifier) {
switch ($modifier['type']) {
case 'amount_is':
case 'amount':
2018-04-02 07:50:17 -05:00
$amount = app('steam')->positive((string)$modifier['value']);
2017-10-30 11:33:39 -05:00
Log::debug(sprintf('Set "%s" using collector with value "%s"', $modifier['type'], $amount));
2017-10-30 11:28:43 -05:00
$collector->amountIs($amount);
break;
2017-10-30 11:34:56 -05:00
case 'amount_max':
2017-10-30 11:28:43 -05:00
case 'amount_less':
2018-04-02 07:50:17 -05:00
$amount = app('steam')->positive((string)$modifier['value']);
2017-10-30 11:33:39 -05:00
Log::debug(sprintf('Set "%s" using collector with value "%s"', $modifier['type'], $amount));
2017-10-30 11:28:43 -05:00
$collector->amountLess($amount);
break;
2017-10-30 11:34:56 -05:00
case 'amount_min':
2017-10-30 11:28:43 -05:00
case 'amount_more':
2018-04-02 07:50:17 -05:00
$amount = app('steam')->positive((string)$modifier['value']);
2017-10-30 11:33:39 -05:00
Log::debug(sprintf('Set "%s" using collector with value "%s"', $modifier['type'], $amount));
2017-10-30 11:28:43 -05:00
$collector->amountMore($amount);
break;
case 'type':
$collector->setTypes([ucfirst($modifier['value'])]);
2017-10-30 11:33:39 -05:00
Log::debug(sprintf('Set "%s" using collector with value "%s"', $modifier['type'], $modifier['value']));
2017-10-30 11:28:43 -05:00
break;
case 'date':
case 'on':
2017-10-30 11:33:39 -05:00
Log::debug(sprintf('Set "%s" using collector with value "%s"', $modifier['type'], $modifier['value']));
2017-10-30 11:28:43 -05:00
$start = new Carbon($modifier['value']);
$collector->setRange($start, $start);
break;
case 'date_before':
case 'before':
2017-10-30 11:33:39 -05:00
Log::debug(sprintf('Set "%s" using collector with value "%s"', $modifier['type'], $modifier['value']));
2017-10-30 11:28:43 -05:00
$before = new Carbon($modifier['value']);
$collector->setBefore($before);
break;
case 'date_after':
case 'after':
2017-10-30 11:33:39 -05:00
Log::debug(sprintf('Set "%s" using collector with value "%s"', $modifier['type'], $modifier['value']));
2017-10-30 11:28:43 -05:00
$after = new Carbon($modifier['value']);
2018-11-20 23:13:30 -06:00
$collector->setAfter($after);
2017-10-30 11:28:43 -05:00
break;
}
}
return $collector;
}
/**
* @param string $string
*/
2018-07-26 22:03:37 -05:00
private function extractModifier(string $string): void
{
$parts = explode(':', $string);
2018-08-04 10:30:06 -05:00
if (2 === \count($parts) && '' !== trim((string)$parts[1]) && \strlen(trim((string)$parts[0])) > 0) {
2018-04-02 07:50:17 -05:00
$type = trim((string)$parts[0]);
$value = trim((string)$parts[1]);
2018-07-26 22:03:37 -05:00
if (\in_array($type, $this->validModifiers, true)) {
// filter for valid type
2017-11-15 05:25:49 -06:00
$this->modifiers->push(['type' => $type, 'value' => $value]);
}
}
}
/**
* @param Transaction $transaction
*
* @return bool
2017-11-15 05:25:49 -06:00
*
*/
private function matchModifiers(Transaction $transaction): bool
{
Log::debug(sprintf('Now at transaction #%d', $transaction->id));
// first "modifier" is always the text of the search:
// check descr of journal:
2018-04-27 23:23:13 -05:00
if (\count($this->words) > 0
2018-04-02 07:50:17 -05:00
&& !$this->strposArray(strtolower((string)$transaction->description), $this->words)
&& !$this->strposArray(strtolower((string)$transaction->transaction_description), $this->words)
) {
Log::debug('Description does not match', $this->words);
return false;
}
// then a for-each and a switch for every possible other thingie.
foreach ($this->modifiers as $modifier) {
2017-02-19 00:38:51 -06:00
$res = Modifier::apply($modifier, $transaction);
2017-11-15 05:25:49 -06:00
if (false === $res) {
return $res;
}
}
return true;
}
2016-11-06 07:52:31 -06:00
/**
* @param string $haystack
* @param array $needle
*
* @return bool
*/
2018-07-26 22:03:37 -05:00
private function strposArray(string $haystack, array $needle): bool
2016-11-06 07:52:31 -06:00
{
2018-07-26 22:03:37 -05:00
if ('' === $haystack) {
2016-11-06 07:52:31 -06:00
return false;
}
foreach ($needle as $what) {
2017-11-15 05:25:49 -06:00
if (false !== stripos($haystack, $what)) {
2016-11-06 07:52:31 -06:00
return true;
}
}
2015-03-20 12:30:17 -05:00
2016-11-06 07:52:31 -06:00
return false;
2015-02-27 04:09:23 -06:00
}
2017-02-05 09:16:15 -06:00
}