mirror of
https://gitlab.com/Chill-Projet/chill-bundles.git
synced 2025-06-12 13:24:25 +00:00
92 lines
2.6 KiB
PHP
92 lines
2.6 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\Utils;
|
|
|
|
use libphonenumber\PhoneNumberUtil;
|
|
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
|
|
|
|
class ExtractPhonenumberFromPattern
|
|
{
|
|
private const PATTERN = '([\+]{0,1}[0-9\ ]{5,})';
|
|
|
|
private readonly string $defaultCarrierCode;
|
|
|
|
public function __construct(ParameterBagInterface $parameterBag)
|
|
{
|
|
$this->defaultCarrierCode = $parameterBag->get('chill_main')['phone_helper']['default_carrier_code'];
|
|
}
|
|
|
|
public function extractPhonenumber(string $subject): SearchExtractionResult
|
|
{
|
|
$matches = [];
|
|
\preg_match(self::PATTERN, $subject, $matches);
|
|
|
|
if (0 < \count($matches)) {
|
|
$phonenumber = [];
|
|
$length = 0;
|
|
|
|
foreach (\str_split(\trim($matches[0])) as $key => $char) {
|
|
switch ($char) {
|
|
case '+':
|
|
if (0 === $key) {
|
|
$phonenumber[] = $char;
|
|
} else {
|
|
throw new \LogicException('should not match not alnum character');
|
|
}
|
|
|
|
break;
|
|
|
|
case '0':
|
|
$length++;
|
|
|
|
if (0 === $key) {
|
|
$util = PhoneNumberUtil::getInstance();
|
|
$phonenumber[] = '+'.$util->getCountryCodeForRegion($this->defaultCarrierCode);
|
|
} else {
|
|
$phonenumber[] = $char;
|
|
}
|
|
|
|
break;
|
|
|
|
case '1':
|
|
case '2':
|
|
case '3':
|
|
case '4':
|
|
case '5':
|
|
case '6':
|
|
case '7':
|
|
case '8':
|
|
case '9':
|
|
$length++;
|
|
$phonenumber[] = $char;
|
|
|
|
break;
|
|
|
|
case ' ':
|
|
break;
|
|
|
|
default:
|
|
throw new \LogicException('should not match not alnum character');
|
|
}
|
|
}
|
|
|
|
if (5 < $length) {
|
|
$filtered = \trim(\strtr($subject, [$matches[0] => '']));
|
|
|
|
return new SearchExtractionResult($filtered, [\implode('', $phonenumber)]);
|
|
}
|
|
}
|
|
|
|
return new SearchExtractionResult($subject, []);
|
|
}
|
|
}
|