Skip to content

Instantly share code, notes, and snippets.

@wyster
Last active May 26, 2019 21:42
Show Gist options
  • Save wyster/b4347932d99067f92139659211ead4e5 to your computer and use it in GitHub Desktop.
Save wyster/b4347932d99067f92139659211ead4e5 to your computer and use it in GitHub Desktop.
Актуальная версия: https://github.com/wyster/funpay-test
<?php declare(strict_types=1);
/**
@deprecated, актуальная версия в репозитории https://github.com/wyster/funpay-test
**/
$messages = [
1 => <<<TEXT
Пароль: 7740
Спишется 234,18р.
Перевод на счет 41001247739481
TEXT
,
<<<TEXT
Без мелочи
Пароль: 7740
Спишется 234р.
Перевод на счет 41001247739481
TEXT
,
<<<TEXT
Поменял местами поля
Перевод на счет 41001247739481
Спишется 234,18р.
Пароль: 7740
TEXT
,
<<<TEXT
Сумма списания имеет 4 знака, а вдруг посчитает её паролем?
Поменял местами поля
Перевод на счет 41001247739481
Спишется 1000р.
Пароль: 7740
TEXT
,
<<<TEXT
Яндекс вдруг решил совсем не указывать текст :)
41001247739481
234,18р.
7740
TEXT
,
// Должно падать с ошибкой
<<<TEXT
Нехватает одного из полей
Пароль: 7740
Спишется 234,18р.
TEXT
,
// Должно падать с ошибкой
<<<TEXT
Ожидаем по одному варианту каждого типа
41001247739481
234,18р.
7740
41001247739481
234,18р.
7740'
TEXT
];
foreach ($messages as $i => $message) {
try {
echo "\noutput {$i}\n";
var_dump(getData($message));
} catch (Exception $e) {
echo "error {$e->getMessage()}";
}
echo "\n\n\n";
}
/**
* @param string $message
* @return array
*/
function getData(string $message): array
{
$matches = [];
$result = [
'password' => null,
'sum' => null,
'account' => null
];
$pattern = '/(?:(?<account>\d{14})|(?<password>\d{4}\b)|(?<sum>\d+(\s?)(,?\d+))\р\.)/ui';
preg_match_all($pattern, $message, $matches, PREG_UNMATCHED_AS_NULL);
foreach ($matches as $field => $match) {
if (!is_string($field)) {
continue;
}
$match = array_filter($match, 'is_string');
// Что то не так, не нашли даже одного вхождения
if (count($match) === 0) {
throw new InvalidArgumentException("Not found matches for field ${field}");
}
// Что то не так, по плану найти по одному вхождению
if (count($match) > 1) {
throw new InvalidArgumentException("Too many matches for field ${field}");
}
$value = array_values($match)[0];
if (in_array($field, ['password', 'account'])) {
$value = (int)$value;
}
if ($field === 'sum') {
$value = str_replace(',', '.', $value);
}
$result[$field] = $value;
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment