Initial Commit

This commit is contained in:
2024-02-08 12:07:49 -07:00
parent 5813b1109f
commit 43077b57ed
5471 changed files with 682195 additions and 0 deletions
@@ -0,0 +1,52 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace YooKassa\Helpers\Config;
class ConfigurationLoader implements ConfigurationLoaderInterface
{
private $configParams;
public function load($filePath = null)
{
if ($filePath) {
$data = file_get_contents($filePath);
} else {
$data = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "configuration.json");
}
$paramsArray = json_decode($data, true);
$this->configParams = $paramsArray;
return $this;
}
public function getConfig()
{
return $this->configParams;
}
}
@@ -0,0 +1,40 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace YooKassa\Helpers\Config;
interface ConfigurationLoaderInterface
{
/**
* @return mixed
*/
public function getConfig();
/**
* @return mixed
*/
public function load();
}
@@ -0,0 +1,362 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace YooKassa\Helpers;
/**
* Класс для формирования тега 1162 на основе кода в формате Data Matrix
*
* @example $receiptItem->setProductCode(new \YooKassa\Helpers\ProductCode('010463003759131691sgEKKPPcS25y592FLduM/='));
* @example array(... 'product_code' => (string)(new \YooKassa\Helpers\ProductCode('010463003759131691sgEKKPPcS25y5') ...);
*
* @link https://github.com/yoomoney/yookassa-sdk-php/blob/master/lib/Helpers/ProductCode.php
*
* Class ProductCode
* @package YooKassa\Helpers
*/
class ProductCode
{
const PREFIX_DATA_MATRIX = '444D';
/** @var string Код типа маркировки */
private $prefix;
/**
* @var string Global Trade Item Number
* Глобальный номер товарной продукции в единой международной базе товаров GS1 https://ru.wikipedia.org/wiki/GS1
* @example 04630037591316
*/
private $gtin;
/**
* @var string Серийный номер товара
* @example sgEKKPPcS25y5
*/
private $serial;
/** @var string Сформированный тег 1162. Формат: hex([prefix]+gtin+serial)
* @example 04 36 03 BE F5 14 73 67 45 4b 4b 50 50 63 53 32 35 79 35
*/
private $result;
/** @var bool Флаг использования кода типа маркировки */
private $usePrefix = false;
/**
* ProductCode constructor.
* @param string|null $codeDataMatrix Строка, расшифрованная из QR-кода
* @param bool|string $usePrefix Нужен ли код типа маркировки в результате
*/
public function __construct($codeDataMatrix=null, $usePrefix=false)
{
$this->preparePrefix($usePrefix);
if (!empty($codeDataMatrix)) {
if ($this->parseCodeMatrixData($codeDataMatrix)) {
$this->result = $this->calcResult();
}
}
}
/**
* Возвращает Код типа маркировки
* @return string Код типа маркировки
*/
public function getPrefix()
{
return $this->prefix;
}
/**
* Устанавливает Код типа маркировки
* @param string|int $prefix Код типа маркировки
* @return ProductCode
*/
public function setPrefix($prefix)
{
if ($prefix === null || $prefix === '') {
$this->prefix = null;
return $this;
}
if (is_int($prefix)) {
$prefix = dechex($prefix);
}
$this->prefix = str_pad($prefix, 4, '0', STR_PAD_LEFT);
return $this;
}
/**
* Возвращает Глобальный номер товарной продукции
* @return string Глобальный номер товарной продукции
*/
public function getGtin()
{
return $this->gtin;
}
/**
* Устанавливает Глобальный номер товарной продукции
* @param string$gtin Глобальный номер товарной продукции
* @return ProductCode
*/
public function setGtin($gtin)
{
if ($gtin === null || $gtin === '') {
$this->gtin = null;
} else {
$this->gtin = $gtin;
}
return $this;
}
/**
* Возвращает Серийный номер товара
* @return string Серийный номер товара
*/
public function getSerial()
{
return $this->serial;
}
/**
* Устанавливает Серийный номер товара
* @param string $serial Серийный номер товара
* @return ProductCode
*/
public function setSerial($serial)
{
if ($serial === null || $serial === '') {
$this->prefix = null;
} else {
$this->serial = $serial;
}
return $this;
}
/**
* Возвращает Сформированный тег 1162.
* @return string Сформированный тег 1162.
*/
public function getResult()
{
if (!$this->result) {
$this->result = $this->calcResult();
}
return $this->result;
}
/**
* Возвращает флаг использования кода типа маркировки
* @return bool
*/
public function isUsePrefix()
{
return $this->usePrefix;
}
/**
* Устанавливает флаг использования кода типа маркировки
* @param bool $usePrefix Флаг использования кода типа маркировки
* @return ProductCode
*/
public function setUsePrefix($usePrefix)
{
$this->usePrefix = (bool)$usePrefix;
return $this;
}
/**
* Формирует тег 1162.
* @return string|null Сформированный тег 1162.
*/
public function calcResult()
{
$result = '';
if (!$this->validate()) {
return $result;
}
if ($this->isUsePrefix()) {
$result = $this->getPrefix() ?: self::PREFIX_DATA_MATRIX;
}
$result .= $this->numToHex($this->getGtin());
$result .= $this->strToHex($this->getSerial());
return $this->chunkStr($result);
}
/**
* Устанавливает prefix и usePrefix в зависимости от входящего параметра
* @param mixed $usePrefix Код типа маркировки или bool
*/
private function preparePrefix($usePrefix)
{
if ($usePrefix) {
$this->setUsePrefix(true);
if (is_string($usePrefix) || is_int($usePrefix)) {
$this->setPrefix($usePrefix);
} else {
$this->setPrefix(self::PREFIX_DATA_MATRIX);
}
} else {
$this->setUsePrefix(false);
$this->setPrefix(null);
}
}
/**
* Извлекает необходимые данные из строки, расшифрованной из QR-кода и устанавливает соответствующие свойства.
* Возвращает результат в виде bool
* @param string $codeDataMatrix Строки, расшифрованная из QR-кода
* @return false
*/
private function parseCodeMatrixData($codeDataMatrix)
{
$string = preg_replace('#91(.+)92(.+)#i', '', $codeDataMatrix);
preg_match('#01(\d{14})21(.+)#i', $string, $matches);
$this->setGtin(!empty($matches[1]) ? $matches[1] : null);
$this->setSerial(!empty($matches[2]) ? $matches[2] : null);
return $this->validate();
}
/**
* Проверяет заполненность необходимых свойств
* @return bool
*/
public function validate()
{
return $this->getGtin() && $this->getSerial();
}
/**
* Разбивает пробелами строку на пары символов и переводит в верхний регистр
* @param string $string Подготовленная к разбиению строка
* @return string
*/
private function chunkStr($string)
{
return strtoupper(trim(chunk_split($string, 2, ' ')));
}
/**
* Переводит десятичное число в шестнадцатеричный вид и дополняет нулями до 12 символов слева
* @param string $string Входящее число (Глобальный номер товарной продукции)
* @return string
*/
private function numToHex($string)
{
return str_pad($this->base_convert($string), 12, '0', STR_PAD_LEFT);
}
/**
* Переводит число из одной системы исчисления в другую
* Замена dechex() для 32-битных версии PHP
*
* @param string $numString
* @param int $fromBase
* @param int $toBase
* @return string
*/
private function base_convert($numString, $fromBase=10, $toBase=16)
{
$chars = "0123456789abcdefghijklmnopqrstuvwxyz";
$toString = substr($chars, 0, $toBase);
$length = strlen($numString);
$result = '';
$number = array();
for ($i = 0; $i < $length; $i++) {
$number[$i] = strpos($chars, substr($numString, $i, 1));
}
do {
$divide = 0;
$newLen = 0;
for ($i = 0; $i < $length; $i++) {
$divide = $divide * $fromBase + $number[$i];
if ($divide >= $toBase) {
$number[$newLen++] = (int)($divide / $toBase);
$divide = $divide % $toBase;
} elseif ($newLen > 0) {
$number[$newLen++] = 0;
}
}
$length = $newLen;
$result = substr($toString, $divide, 1) . $result;
} while ($newLen != 0);
return $result;
}
/**
* Переводит строку в шестнадцатеричный вид
* @param string $string Входящая строка (Серийный номер товара)
* @return string
*/
private function strToHex($string)
{
$hex = '';
for ($i = 0; $i < strlen($string); $i++) {
$ord = ord($string[$i]);
$hexCode = dechex($ord);
$hex .= substr('0' . $hexCode, -2);
}
return $hex;
}
/**
* Переводит строку из шестнадцатеричного вида в обычный
* Нужен для тестирования
* @param string $hex Входящая строка в шестнадцатеричном виде
* @return string
*/
private function hexToStr($hex)
{
$string = '';
for ($i = 0; $i < strlen($hex) - 1; $i += 2) {
$string .= chr(hexdec($hex[$i] . $hex[$i + 1]));
}
return $string;
}
/**
* Приводит объект к строке
* @return string
*/
public function __toString()
{
return $this->getResult();
}
}
@@ -0,0 +1,166 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace YooKassa\Helpers;
/**
* Класс хэлпера для генерации случайных значений, используется в тестах
*
* @package YooKassa\Helpers
*/
class Random
{
/**
* Возвращает рандомное целое число. По умолчанию возвращает число от нуля до PHP_INT_MAX.
* @param int|null $min Минимально возможное значение
* @param int|null $max Максимально возможное значение
* @param bool $useBest Использовать ли функцию random_int если она доступна
* @return int Рандомное целое число
* @throws \Exception
*/
public static function int($min = null, $max = null, $useBest = true)
{
if ($min === null) {
$min = 0;
}
if ($max === null) {
$max = PHP_INT_MAX;
}
if (function_exists('random_int') && $useBest) {
return random_int($min, $max);
} else {
return mt_rand($min, $max);
}
}
/**
* Возвращает рандомное число с плавающей точкой. По умолчанию возвращает значение в промежутке от нуля до едениы.
* @param float|null $min Минимально возможное значение
* @param float|null $max Максимально возможное значение
* @param bool $useBest Использовать ли функцию random_int если она доступна
* @return float Рандомное число с плавающей точкой
* @throws \Exception
*/
public static function float($min = null, $max = null, $useBest = true)
{
$random = self::int(null, null, $useBest) / PHP_INT_MAX;
if ($min === null) {
$min = 0.0;
}
if ($max === null) {
return $random + $min;
}
return ($random * ($max - $min)) + $min;
}
/**
* Возвращает строку из рандомных символов
* @param int $length Длина возвращаемой строки, или минимальная длина, если передан парамтр $maxLength
* @param int|null $maxLength Если параметр не равен null, возвращает сроку длиной от $length до $maxLength
* @param string|array|null $characters Строка или массив используемых в строке символов
* @param bool $useBest Использовать ли функцию random_int если она доступна
* @return string Строка, состоящая из рандомных символов
* @throws \Exception
*/
public static function str($length, $maxLength = null, $characters = null, $useBest = true)
{
$result = '';
if ($maxLength !== null) {
if (is_string($maxLength)) {
$characters = $maxLength;
} else {
$length = self::int($length, $maxLength, $useBest);
}
}
if ($characters === null) {
for ($i = 0; $i < $length; $i++) {
$chr = chr(self::int(32, 125, $useBest));
$result .= $chr;
}
} else {
for ($i = 0; $i < $length; $i++) {
$chr = $characters[self::int(0, strlen($characters) - 1, $useBest)];
$result .= $chr;
}
}
return $result;
}
/**
* Возвращает строку, состоящую из символов '0123456789abcdef'
* @param int $length Длина возвращаемой строки
* @param bool $useBest Использовать ли функцию random_int если она доступна
* @return string Строка, состоящая из рандомных символов
* @throws \Exception
*/
public static function hex($length, $useBest = true)
{
return self::str($length, '0123456789abcdef', $useBest);
}
/**
* Возвращает рандомную последовательность байт
* @param int $length Длина возвращаемой строки
* @param bool $useBest Использовать ли функцию random_int если она доступна
* @return string Строка, состоящая из рандомных символов
* @throws \Exception
*/
public static function bytes($length, $useBest = true)
{
if (function_exists('random_bytes') && $useBest) {
$result = random_bytes($length);
} else {
$result = '';
for ($i = 0; $i < $length; $i++) {
$chr = chr(self::int(0, 255));
$result .= $chr;
}
}
return $result;
}
/**
* Возвращает рандомное значение из переданного массива
* @param array $values Массив источник данных
* @param bool $useBest Использовать ли функцию random_int если она доступна
* @return mixed Случайное значение из переданного массива
* @throws \Exception
*/
public static function value(array $values, $useBest = true)
{
return $values[self::int(0, count($values) - 1, $useBest)];
}
/**
* Возвращает рандомное буллево значение
* @return bool Либо true либо false, одно из двух
* @throws \Exception
*/
public static function bool()
{
return self::int(0, 1) === 1;
}
}
@@ -0,0 +1,63 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace YooKassa\Helpers;
class RawHeadersParser
{
public static function parse($rawHeaders)
{
$headers = array();
$key = '';
foreach (explode("\n", $rawHeaders) as $headerRow) {
if (trim($headerRow) === '') {
break;
}
$headerArray = explode(':', $headerRow, 2);
if (isset($headerArray[1])) {
if (!isset($headers[$headerArray[0]])) {
$headers[trim($headerArray[0])] = trim($headerArray[1]);
} elseif (is_array($headers[$headerArray[0]])) {
$headers[trim($headerArray[0])] = array_merge($headers[trim($headerArray[0])], array(trim($headerArray[1])));
} else {
$headers[trim($headerArray[0])] = array_merge(array($headers[trim($headerArray[0])]), array(trim($headerArray[1])));
}
$key = $headerArray[0];
} else {
if (substr($headerArray[0], 0, 1) === "\t") {
$headers[$key] .= "\r\n\t" . trim($headerArray[0]);
} elseif (!$key) {
$headers[0] = trim($headerArray[0]);
}
}
}
return $headers;
}
}
@@ -0,0 +1,58 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace YooKassa\Helpers;
/**
* Класс объекта, кастящегося в строку, используется только в тестах
*
* @package YooKassa\Helpers
*/
class StringObject
{
/**
* @var string Значение, возвращаемое методом __toString
*/
private $value;
/**
* StringObject constructor.
* @param string $value
*/
public function __construct($value)
{
$this->value = (string)$value;
}
/**
* Возвращает строковое значение текущего объекта
* @return string Строковое представление объекта
*/
public function __toString()
{
return $this->value;
}
}
@@ -0,0 +1,126 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace YooKassa\Helpers;
use DateTime;
use Exception;
/**
* Класс хэлпер для преобразования типов значений
*
* @package YooKassa\Helpers
*/
class TypeCast
{
/**
* Проверяет может ли переданное значение быть преобразовано в строку
* @param mixed $value Проверяемое значение
* @return bool True если значение преобразовать в строку можно, false если нет
*/
public static function canCastToString($value)
{
if (is_scalar($value)) {
return !is_bool($value) && !is_resource($value);
} elseif (is_object($value)) {
return method_exists($value, '__toString');
}
return false;
}
/**
* Проверяет можно ли преобразовать переданное значение в строку из перечисления
* @param mixed $value Проверяемое значение
* @return bool True если значение преобразовать в строку можно, false если нет
*/
public static function canCastToEnumString($value)
{
if (is_string($value) && $value !== '') {
return true;
} elseif (is_object($value)) {
return method_exists($value, '__toString');
}
return false;
}
/**
* Проверяет, можно ли преобразовать переданное значение в объект даты-времени
* @param mixed $value Провеяремое значение
* @return bool True если значение можно преобразовать в объект даты, false если нет
*/
public static function canCastToDateTime($value)
{
if ($value instanceof DateTime) {
return true;
} elseif (is_numeric($value)) {
$value = (float)$value;
return $value >= 0;
} elseif (is_string($value)) {
return $value !== '';
} elseif (is_object($value)) {
return method_exists($value, '__toString') && ((string)$value) !== '';
}
return false;
}
/**
* Преобразует переданне значение в объект типа \DateTime
* @param string|int|DateTime $value Преобразуемое значение
* @return DateTime|null Объект типа \DateTime или null если при парсинг даты не удался
* @throws Exception
*/
public static function castToDateTime($value)
{
if ($value instanceof DateTime) {
return clone $value;
}
if (is_numeric($value)) {
$date = new DateTime();
$date->setTimestamp((int)$value);
} elseif (is_string($value) || (is_object($value) && method_exists($value, '__toString'))) {
$date = date_create((string)$value);
if ($date === false) {
$date = null;
}
} else {
$date = null;
}
return $date;
}
/**
* Проверяет можно ли преобразовать переданное значение в буллево значение
* @param mixed $value Проверяемое значение
* @return bool True если значение качтится в bool, false если нет
*/
public static function canCastToBoolean($value)
{
if (is_numeric($value) || is_bool($value)) {
return true;
}
return false;
}
}
@@ -0,0 +1,23 @@
<?php
namespace YooKassa\Helpers;
class UUID
{
/**
* @return string
* @throws \Exception
*/
public static function v4()
{
$hexData = bin2hex(Random::bytes(16));
$parts = str_split($hexData, 4);
$parts[3] = '4' . substr($parts[3], 1);
$parts[4] = '8' . substr($parts[4], 1);
return vsprintf('%s%s-%s-%s-%s-%s%s%s',
$parts
);
}
}