Files
chill-bundles/src/Bundle/ChillMainBundle/Search/AbstractSearch.php

88 lines
2.5 KiB
PHP

<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Search;
use DateTime;
/**
* This class implements abstract search with most common responses.
*
* you should use this abstract class instead of SearchInterface : if the signature of
* search interface change, the generic method will be implemented here.
*/
abstract class AbstractSearch implements SearchInterface
{
/**
* parse string expected to be a date and transform to a DateTime object.
*
* @return \DateTime
*
* @throws ParsingException if the date is not parseable
*/
public function parseDate(string $string)
{
try {
return new \DateTime($string);
} catch (\Exception $ex) {
$exception = new ParsingException('The date is '
.'not parsable', 0, $ex);
throw $exception;
}
}
/**
* recompose a pattern, retaining only supported terms.
*
* the outputted string should be used to show users their search
*
* @param string $domain if your domain is NULL, you should set NULL. You should set used domain instead
*
* @return string
*/
protected function recomposePattern(array $terms, array $supportedTerms, $domain = null)
{
$recomposed = '';
if (null !== $domain) {
$recomposed .= '@'.$domain.' ';
}
foreach ($supportedTerms as $term) {
if (\array_key_exists($term, $terms) && '_default' !== $term) {
$recomposed .= ' '.$term.':';
$containsSpace = str_contains((string) $terms[$term], ' ');
if ($containsSpace || is_numeric($terms[$term])) {
$recomposed .= '"';
}
$recomposed .= (false === mb_stristr(' ', (string) $terms[$term])) ? $terms[$term] : '('.$terms[$term].')';
if ($containsSpace || is_numeric($terms[$term])) {
$recomposed .= '"';
}
}
}
if ('' !== $terms['_default']) {
$recomposed .= ' '.$terms['_default'];
}
// strip first character if empty
if (' ' === mb_strcut($recomposed, 0, 1)) {
$recomposed = mb_strcut($recomposed, 1);
}
return $recomposed;
}
}