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,74 @@
<?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\Common;
/**
* Базовый класс генерируемых enum'ов
*
* @package YooKassa\Common
*/
abstract class AbstractEnum
{
/**
* @var array Массив принимаемых enum'ом значений
*/
protected static $validValues = array();
/**
* Проверяет наличие значения в enum'e
* @param mixed $value Проверяемое значение
* @return bool True если значение имеется, false если нет
*/
public static function valueExists($value)
{
return array_key_exists($value, static::$validValues);
}
/**
* Возвращает все значения в enum'e
* @return array Массив значений в перечислении
*/
public static function getValidValues()
{
return array_keys(static::$validValues);
}
/**
* Возвращает значения в enum'е значения которых разрешены
* @return string[] Массив разрешённых значений
*/
public static function getEnabledValues()
{
$result = array();
foreach (static::$validValues as $key => $enabled) {
if ($enabled) {
$result[] = $key;
}
}
return $result;
}
}
@@ -0,0 +1,251 @@
<?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\Common;
if (!defined('YOOKASSA_DATE')) {
if (version_compare(PHP_VERSION, '7.0') >= 0) {
define('YOOKASSA_DATE', "Y-m-d\TH:i:s.vP");
} else {
define('YOOKASSA_DATE', "Y-m-d\TH:i:s.uP");
}
}
if (!interface_exists('JsonSerializable')) {
require_once dirname(__FILE__) . '/legacy_json_serializable.php';
}
/**
* Базовый класс генерируемых объектов
*
* @package YooKassa\Common
*/
abstract class AbstractObject implements \ArrayAccess, \JsonSerializable
{
/**
* @var array Свойства установленные пользователем
*/
private $unknownProperties = array();
/**
* AbstractObject constructor.
* @param array $data
*/
public function __construct($data = array())
{
if (!empty($data) && is_array($data)) {
$this->fromArray($data);
}
}
/**
* Проверяет наличие свойства
* @param string $offset Имя проверяемого свойства
* @return bool True если свойство имеется, false если нет
*/
public function offsetExists($offset)
{
$method = 'get' . ucfirst($offset);
if (method_exists($this, $method)) {
return true;
}
$method = 'get' . self::matchPropertyName($offset);
if (method_exists($this, $method)) {
return true;
}
return array_key_exists($offset, $this->unknownProperties);
}
/**
* Возвращает значение свойства
* @param string $offset Имя свойства
* @return mixed Значение свойства
*/
public function offsetGet($offset)
{
$method = 'get' . ucfirst($offset);
if (method_exists($this, $method)) {
return $this->{$method} ();
}
$method = 'get' . self::matchPropertyName($offset);
if (method_exists($this, $method)) {
return $this->{$method} ();
}
return array_key_exists($offset, $this->unknownProperties) ? $this->unknownProperties[$offset] : null;
}
/**
* Устанавливает значение свойства
* @param string $offset Имя свойства
* @param mixed $value Значение свойства
*/
public function offsetSet($offset, $value)
{
$method = 'set' . ucfirst($offset);
if (method_exists($this, $method)) {
$this->{$method}($value);
} else {
$method = 'set' . self::matchPropertyName($offset);
if (method_exists($this, $method)) {
$this->{$method}($value);
} else {
$this->unknownProperties[$offset] = $value;
}
}
}
/**
* Удаляет свойство
* @param string $offset Имя удаляемого свойства
*/
public function offsetUnset($offset)
{
$method = 'set' . ucfirst($offset);
if (method_exists($this, $method)) {
$this->{$method} (null);
} else {
$method = 'set' . self::matchPropertyName($offset);
if (method_exists($this, $method)) {
$this->{$method} (null);
} else {
unset($this->unknownProperties[$offset]);
}
}
}
/**
* Возвращает значение свойства
* @param string $propertyName Имя свойства
* @return mixed Значение свойства
*/
public function __get($propertyName)
{
return $this->offsetGet($propertyName);
}
/**
* Устанавливает значение свойства
* @param string $propertyName Имя свойства
* @param mixed $value Значение свойства
*/
public function __set($propertyName, $value)
{
$this->offsetSet($propertyName, $value);
}
/**
* Проверяет наличие свойства
* @param string $propertyName Имя проверяемого свойства
* @return bool True если свойство имеется, false если нет
*/
public function __isset($propertyName)
{
return $this->offsetExists($propertyName);
}
/**
* Удаляет свойство
* @param string $propertyName Имя удаляемого свойства
*/
public function __unset($propertyName)
{
$this->offsetUnset($propertyName);
}
/**
* Устанавливает значения свойств текущего объекта из массива
* @param array|\Traversable $sourceArray Ассоциативный массив с найтройками
*/
public function fromArray($sourceArray)
{
foreach ($sourceArray as $key => $value) {
$this->offsetSet($key, $value);
}
}
/**
* Возвращает ассоциативный массив со свойствами текущего объекта для его дальнейшей JSON сериализации
* @return array Ассоциативный массив со свойствами текущего объекта
*/
public function jsonSerialize()
{
$result = array();
foreach (get_class_methods($this) as $method) {
if (strncmp('get', $method, 3) === 0) {
if ($method === 'getUnknownProperties') {
continue;
}
if ($method === 'getIterator') {
continue;
}
$property = strtolower(preg_replace('/[A-Z]/', '_\0', lcfirst(substr($method, 3))));
$value = $this->serializeValueToJson($this->{$method} ());
if ($value !== null) {
$result[$property] = $value;
}
}
}
if (!empty($this->unknownProperties)) {
foreach ($this->unknownProperties as $property => $value) {
if (!array_key_exists($property, $result)) {
$result[$property] = $this->serializeValueToJson($value);
}
}
}
return $result;
}
private function serializeValueToJson($value)
{
if ($value === null || is_scalar($value) || is_array($value)) {
return $value;
} elseif (is_object($value) && $value instanceof \JsonSerializable) {
return $value->jsonSerialize();
} elseif (is_object($value) && $value instanceof \DateTime) {
return $value->format(YOOKASSA_DATE);
}
return $value;
}
/**
* Возвращает массив свойств которые не существуют, но были заданы у объекта
* @return array Ассоциативный массив с не существующими у текущего объекта свойствами
*/
protected function getUnknownProperties()
{
return $this->unknownProperties;
}
/**
* Преобразует имя свойства из snake_case в camelCase
* @param string $property Преобразуемое значение
* @return string Значение в камэл кейсе
*/
private static function matchPropertyName($property)
{
return preg_replace('/\_(\w)/', '\1', $property);
}
}
@@ -0,0 +1,223 @@
<?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\Common;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Model\AmountInterface;
use YooKassa\Model\Receipt;
use YooKassa\Model\ReceiptInterface;
use YooKassa\Model\Transfer;
use YooKassa\Model\TransferInterface;
/**
* Класс объекта запроса к API
*
* @property AmountInterface $amount Сумма
* @property ReceiptInterface $receipt Данные фискального чека 54-ФЗ
* @property TransferInterface[] $transfers Данные о распределении платежа между магазинами
*
* @since 1.0.18
*/
class AbstractPaymentRequest extends AbstractRequest
{
/**
* @var AmountInterface Сумма оплаты
*/
protected $_amount;
/**
* @var Receipt Данные фискального чека 54-ФЗ
*/
protected $_receipt;
/**
* @var TransferInterface[]
*/
protected $_transfers = array();
/**
* Возвращает сумму оплаты
* @return AmountInterface Сумма оплаты
*/
public function getAmount()
{
return $this->_amount;
}
/**
* Проверяет была ли установлена сумма оплаты
* @return bool True если сумма оплаты была установлена, false если нет
*/
public function hasAmount()
{
return !empty($this->_amount);
}
/**
* Устанавливает сумму оплаты
* @param AmountInterface $value Сумма оплаты
*/
public function setAmount(AmountInterface $value)
{
$this->_amount = $value;
}
/**
* Возвращает чек, если он есть
* @return ReceiptInterface|null Данные фискального чека 54-ФЗ или null если чека нет
*/
public function getReceipt()
{
return $this->_receipt;
}
/**
* Устанавливает чек
* @param ReceiptInterface|null $value Инстанс чека или null для удаления информации о чеке
* @throws InvalidPropertyValueTypeException Выбрасывается если передан не инстанс класса чека и не null
*/
public function setReceipt($value)
{
if ($value === null || $value instanceof ReceiptInterface) {
$this->_receipt = $value;
} else {
throw new InvalidPropertyValueTypeException('Invalid receipt in Refund', 0, 'Refund.receipt', $value);
}
}
/**
* Проверяет наличие чека
* @return bool True если чек есть, false если нет
*/
public function hasReceipt()
{
return $this->_receipt !== null && $this->_receipt->notEmpty();
}
/**
* Удаляет чек из запроса
*/
public function removeReceipt()
{
$this->_receipt = null;
}
/**
* Устанавливает transfers (массив распределения денег между магазинами)
* @param TransferInterface[]|array $value
*/
public function setTransfers($value)
{
if (!is_array($value)) {
$message = 'Transfers must be an array of TransferInterface';
throw new InvalidPropertyValueTypeException($message, 0, 'Payment.transfers', $value);
}
$transfers = array();
foreach ($value as $item) {
if (is_array($item)) {
$item = new Transfer($item);
}
if (!($item instanceof TransferInterface)) {
$message = 'Transfers must be an array of TransferInterface';
throw new InvalidPropertyValueTypeException($message, 0, 'Payment.transfers', $value);
}
$transfers[] = $item;
}
$this->_transfers = $transfers;
}
/**
* Валидирует объект запроса
* @return bool True если запрос валиден и его можно отправить в API, false если нет
*/
public function validate()
{
if ($this->_amount === null) {
$this->setValidationError('Payment amount not specified');
return false;
}
$value = $this->_amount->getValue();
if (empty($value) || $value <= 0.0) {
$this->setValidationError('Invalid payment amount value: ' . $value);
return false;
}
if (!empty($this->_transfers)) {
$sum = 0;
foreach ($this->_transfers as $transfer) {
if ($transfer->getAmount() === null) {
$this->setValidationError('Payment amount not specified');
return false;
}
$value = $transfer->getAmount()->getValue();
if (empty($value) || $value <= 0.0) {
$this->setValidationError('Invalid transfer amount value: ' . $value);
return false;
}
$sum += (float) $value;
$accountId = $transfer->getAccountId();
if (empty($accountId)) {
$this->setValidationError('Transfer account id not specified');
return false;
}
}
if ($sum !== (float) $this->getAmount()->getValue()) {
$this->setValidationError('Transfer amount sum does not match top-level amount');
}
}
if ($this->getReceipt() && $this->getReceipt()->notEmpty()) {
$email = $this->getReceipt()->getCustomer()->getEmail();
$phone = $this->getReceipt()->getCustomer()->getPhone();
if (empty($email) && empty($phone)) {
$this->setValidationError('Both email and phone values are empty in receipt');
return false;
}
}
return true;
}
public function hasTransfers()
{
return !empty($this->_transfers);
}
public function getTransfers()
{
return $this->_transfers;
}
}
@@ -0,0 +1,336 @@
<?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\Common;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Model\AmountInterface;
use YooKassa\Model\MonetaryAmount;
use YooKassa\Model\Receipt;
use YooKassa\Model\Receipt\ReceiptItemAmount;
use YooKassa\Model\ReceiptCustomer;
use YooKassa\Model\ReceiptInterface;
use YooKassa\Model\ReceiptItem;
use YooKassa\Model\ReceiptItemInterface;
use YooKassa\Model\Transfer;
use YooKassa\Model\TransferInterface;
/**
* Базовый класс объекта платежного запроса, передаваемого в методы клиента API
*
* @package YooKassa\Common
*
* @since 1.0.18
*/
abstract class AbstractPaymentRequestBuilder extends AbstractRequestBuilder
{
/**
* @var MonetaryAmount Сумма
*/
protected $amount;
/**
* @var Receipt Объект с информацией о чеке
*/
protected $receipt;
/**
* @var TransferInterface[] Массив платежей в пользу разных мерчантов
*/
protected $transfers;
/**
* @return self
*/
protected function initCurrentObject()
{
$this->amount = new MonetaryAmount();
$this->receipt = new Receipt();
$this->transfers = array();
return $this;
}
/**
* {@inheritDoc}
*/
public function build(array $options = null)
{
return parent::build($options);
}
/**
* Устанавливает сумму
*
* @param AmountInterface|array|string $value Сумма оплаты
*
* @return self Инстанс билдера запросов
*/
public function setAmount($value)
{
if ($value === null || $value === '') {
$this->amount = new MonetaryAmount();
} elseif ($value instanceof AmountInterface) {
$this->amount->setValue($value->getValue());
$this->amount->setCurrency($value->getCurrency());
} elseif (is_array($value)) {
$this->amount->fromArray($value);
} else {
$this->amount->setValue($value);
}
return $this;
}
/**
* Устанавливает трансферы
*
* @param array|string $value Массив трансферов
*
* @return self Инстанс билдера запросов
*/
public function setTransfers($value)
{
$value = (array)$value;
$this->transfers = array();
foreach ($value as $item) {
$transfer = new Transfer();
if ($item instanceof TransferInterface) {
$transfer->setAmount($item->getAmount());
$transfer->setAccountId($item->getAccountId());
if ($item->hasPlatformFeeAmount()) {
$transfer->setPlatformFeeAmount($item->getPlatformFeeAmount());
}
} elseif (is_array($item)) {
$transfer->fromArray($item);
}
$this->transfers[] = $transfer;
}
return $this;
}
/**
* Устанавливает валюту в которой будет происходить подтверждение оплаты заказа
*
* @param string $value Валюта в которой подтверждается оплата
*
* @return self Инстанс билдера запросов
*/
public function setCurrency($value)
{
$this->amount->setCurrency($value);
foreach ($this->receipt->getItems() as $item) {
$item->getPrice()->setCurrency($value);
}
return $this;
}
/**
* Устанавливает чек
*
* @param ReceiptInterface|array $value Инстанс чека или ассоциативный массив с данными чека
*
* @return self
*
* @throws InvalidPropertyValueTypeException Генерируется если было передано значение невалидного типа
*/
public function setReceipt($value)
{
if (is_array($value)) {
$this->receipt->fromArray($value);
} elseif ($value instanceof ReceiptInterface) {
$this->receipt = clone $value;
} else {
throw new InvalidPropertyValueTypeException('Invalid receipt value type', 0, 'receipt', $value);
}
return $this;
}
/**
* Устанавлвиает список товаров для создания чека
*
* @param array $value Массив товаров в заказе
*
* @return self Инстанс билдера запросов
*
* @throws InvalidPropertyValueException Выбрасывается если хотя бы один из товаров имеет неверную структуру
*/
public function setReceiptItems($value)
{
$this->receipt->setItems(array());
$index = 0;
foreach ($value as $item) {
if ($item instanceof ReceiptItemInterface) {
$this->receipt->addItem($item);
} else {
if (empty($item['title']) && empty($item['description'])) {
throw new InvalidPropertyValueException(
'Item#'.$index.' title or description not specified',
0,
'AbstractPaymentRequestBuilder.items['.$index.'].title',
json_encode($item)
);
}
foreach (array('price', 'quantity', 'vatCode') as $property) {
if (empty($item[$property])) {
throw new InvalidPropertyValueException(
'Item#'.$index.' '.$property.' not specified',
0,
'AbstractPaymentRequestBuilder.items['.$index.'].'.$property,
json_encode($item)
);
}
}
$this->addReceiptItem(
empty($item['title']) ? $item['description'] : $item['title'],
$item['price'],
$item['quantity'],
$item['vatCode']
);
}
$index++;
}
return $this;
}
/**
* Добавляет в чек товар
*
* @param string $title Название или описание товара
* @param string $price Цена товара в валюте, заданной в заказе
* @param float $quantity Количество товара
* @param int $vatCode Ставка НДС
*
* @param null|string $paymentSubject значение перечисления PaymentSubject
* @see \YooKassa\Model\Receipt\PaymentSubject::class
*
* @param null|string $paymentMode значение перечисления PaymentMode
* @see \YooKassa\Model\Receipt\PaymentMode::class
*
* @return self Инстанс билдера запросов
*/
public function addReceiptItem($title, $price, $quantity, $vatCode, $paymentMode = null, $paymentSubject = null)
{
$item = new ReceiptItem();
$item->setDescription($title);
$item->setQuantity($quantity);
$item->setVatCode($vatCode);
$item->setPrice(new ReceiptItemAmount($price, $this->amount->getCurrency()));
$item->setPaymentSubject($paymentSubject);
$item->setPaymentMode($paymentMode);
$this->receipt->addItem($item);
return $this;
}
/**
* Добавляет в чек доставку товара
*
* @param string $title Название доставки в чеке
* @param string $price Стоимость доставки
* @param int $vatCode Ставка НДС
*
* @param null|string $paymentSubject значение перечисления PaymentSubject
* @see \YooKassa\Model\Receipt\PaymentSubject::class
*
* @param null|string $paymentMode значение перечисления PaymentMode
* @see \YooKassa\Model\Receipt\PaymentMode::class
*
* @return self Инстанс билдера запросов
*/
public function addReceiptShipping($title, $price, $vatCode, $paymentMode = null, $paymentSubject = null)
{
$item = new ReceiptItem();
$item->setDescription($title);
$item->setQuantity(1);
$item->setVatCode($vatCode);
$item->setIsShipping(true);
$item->setPrice(new ReceiptItemAmount($price, $this->amount->getCurrency()));
$item->setPaymentMode($paymentMode);
$item->setPaymentSubject($paymentSubject);
$this->receipt->addItem($item);
return $this;
}
/**
* Устанавливает адрес электронной почты получателя чека
*
* @param string $value Email получателя чека
*
* @return self Инстанс билдера запросов
*/
public function setReceiptEmail($value)
{
if (!$this->receipt->getCustomer()) {
$this->receipt->setCustomer(new ReceiptCustomer());
}
$this->receipt->getCustomer()->setEmail($value);
return $this;
}
/**
* Устанавливает телефон получателя чека
*
* @param string $value Телефон получателя чека
* @return self Инстанс билдера запросов
*
* @throws InvalidPropertyValueTypeException Выбрасывается если в качестве значения была передана не строка
*/
public function setReceiptPhone($value)
{
if (!$this->receipt->getCustomer()) {
$this->receipt->setCustomer(new ReceiptCustomer());
}
$this->receipt->getCustomer()->setPhone($value);
return $this;
}
/**
* Устанавливает код системы налогообложения.
*
* @param int $value Код системы налогообложения. Число 1-6.
*
* @return self Инстанс билдера запросов
*/
public function setTaxSystemCode($value)
{
$this->receipt->setTaxSystemCode($value);
return $this;
}
}
@@ -0,0 +1,72 @@
<?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\Common;
/**
* Базовый класс объекта запроса, передаваемого в методы клиента API
*
* @package YooKassa\Common
*/
abstract class AbstractRequest extends AbstractObject
{
/**
* @var string Последняя ошибка валидации текущего запроса
*/
private $_validationError;
/**
* Валидирует текущий запрос, проверяет все ли нужные свойства установлены
* @return bool True если запрос валиден, false если нет
*/
abstract public function validate();
/**
* Очищает статус валидации текущего запроса
*/
public function clearValidationError()
{
$this->_validationError = null;
}
/**
* Устанавливает ошибку валидации
* @param string $value Ошибка, произошедшая при валидации объекта
*/
protected function setValidationError($value)
{
$this->_validationError = $value;
}
/**
* Возвращает последнюю ошибку валидации
* @return string Последняя произошедшая ошибка валидации
*/
public function getLastValidationError()
{
return $this->_validationError;
}
}
@@ -0,0 +1,119 @@
<?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\Common;
use YooKassa\Common\Exceptions\InvalidPropertyException;
use YooKassa\Common\Exceptions\InvalidRequestException;
/**
* Базовый класс билдера запросов
*
* @package YooKassa\Common
*/
abstract class AbstractRequestBuilder
{
/**
* @var AbstractRequest Инстанс собираемого запроса
*/
protected $currentObject;
/**
* Конструктор, инициализирует пустой запрос, который в будущем начнём собирать
*/
public function __construct()
{
$this->currentObject = $this->initCurrentObject();
}
/**
* Инициализирует пустой запрос
* @return AbstractRequest Инстанс запроса который будем собирать
*/
abstract protected function initCurrentObject();
/**
* Строит запрос, валидирует его и возвращает, если все прошло нормально
* @param array $options Массив свойств запроса, если нужно их установить перед сборкой
* @return AbstractRequest Инстанс собранного запроса
*
* @throws InvalidRequestException Выбрасывается если при валидации запроса произошла ошибка
* @throws InvalidPropertyException Выбрасывается если не удалось установить один из параметров, переданныч в
* массиве настроек
*/
public function build(array $options = null)
{
if (!empty($options)) {
$this->setOptions($options);
}
try {
$this->currentObject->clearValidationError();
if (!$this->currentObject->validate()) {
throw new InvalidRequestException($this->currentObject);
}
} catch (InvalidRequestException $e) {
throw $e;
} catch (\Exception $e) {
throw new InvalidRequestException($this->currentObject, 0, $e);
}
$result = $this->currentObject;
$this->currentObject = $this->initCurrentObject();
return $result;
}
/**
* Устанавливает свойства запроса из массива
* @param array|\Traversable $options Массив свойств запроса
* @return AbstractRequestBuilder Инстанс текущего билдера запросов
*
* @throws \InvalidArgumentException Выбрасывается если аргумент не массив и не итерируемый объект
* @throws InvalidPropertyException Выбрасывается если не удалось установить один из параметров, переданныч
* в массиве настроек
*/
public function setOptions($options)
{
if (empty($options)) {
return $this;
}
if (!is_array($options) && !($options instanceof \Traversable)) {
throw new \InvalidArgumentException('Invalid options value in setOptions method');
}
foreach ($options as $property => $value) {
$method = 'set' . ucfirst($property);
if (method_exists($this, $method)) {
$this->{$method} ($value);
} else {
$property = str_replace('.', '_', $property);
$field = implode('', array_map('ucfirst', explode('_', $property)));
$method = 'set' . ucfirst($field);
if (method_exists($this, $method)) {
$this->{$method} ($value);
}
}
}
return $this;
}
}
@@ -0,0 +1,32 @@
<?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\Common\Exceptions;
class ApiConnectionException extends ApiException
{
}
@@ -0,0 +1,73 @@
<?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\Common\Exceptions;
use Exception;
class ApiException extends Exception
{
/**
* @var mixed
*/
protected $responseBody;
/**
* @var string[]
*/
protected $responseHeaders;
/**
* Constructor
*
* @param string $message Error message
* @param int $code HTTP status code
* @param string[] $responseHeaders HTTP header
* @param mixed $responseBody HTTP body
*/
public function __construct($message = "", $code = 0, $responseHeaders = array(), $responseBody = null)
{
parent::__construct($message, $code);
$this->responseHeaders = $responseHeaders;
$this->responseBody = $responseBody;
}
/**
* @return string[]
*/
public function getResponseHeaders()
{
return $this->responseHeaders;
}
/**
* @return mixed
*/
public function getResponseBody()
{
return $this->responseBody;
}
}
@@ -0,0 +1,32 @@
<?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\Common\Exceptions;
class AuthorizeException extends ApiException
{
}
@@ -0,0 +1,64 @@
<?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\Common\Exceptions;
class BadApiRequestException extends ApiException
{
const HTTP_CODE = 400;
public $type;
public $retryAfter;
public function __construct($responseHeaders = array(), $responseBody = null)
{
$errorData = json_decode($responseBody, true);
$message = '';
if (isset($errorData['description'])) {
$message .= $errorData['description'] . '. ';
}
if (isset($errorData['code'])) {
$message .= sprintf('Error code: %s. ', $errorData['code']);
}
if (isset($errorData['parameter'])) {
$message .= sprintf('Parameter name: %s. ', $errorData['parameter']);
}
if (isset($errorData['retry_after'])) {
$this->retryAfter = $errorData['retry_after'];
}
if (isset($errorData['type'])) {
$this->type = $errorData['type'];
}
parent::__construct(trim($message), self::HTTP_CODE, $responseHeaders, $responseBody);
}
}
@@ -0,0 +1,31 @@
<?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\Common\Exceptions;
class EmptyPropertyValueException extends InvalidPropertyException
{
}
@@ -0,0 +1,46 @@
<?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\Common\Exceptions;
use Exception;
class ExtensionNotFoundException extends Exception
{
/**
* Constructor
*
* @param string $name extension name
* @param int $code error code
*/
public function __construct($name, $code = 0)
{
$message = sprintf('%s extension is not loaded!', $name);
parent::__construct($message, $code);
}
}
@@ -0,0 +1,64 @@
<?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\Common\Exceptions;
class ForbiddenException extends ApiException
{
const HTTP_CODE = 403;
public $type;
public $retryAfter;
public function __construct($responseHeaders = array(), $responseBody = null)
{
$errorData = json_decode($responseBody, true);
$message = '';
if (isset($errorData['description'])) {
$message .= $errorData['description'] . '. ';
}
if (isset($errorData['code'])) {
$message .= sprintf('Error code: %s. ', $errorData['code']);
}
if (isset($errorData['parameter'])) {
$message .= sprintf('Parameter name: %s. ', $errorData['parameter']);
}
if (isset($errorData['retry_after'])) {
$this->retryAfter = $errorData['retry_after'];
}
if (isset($errorData['type'])) {
$this->type = $errorData['type'];
}
parent::__construct(trim($message), self::HTTP_CODE, $responseHeaders, $responseBody);
}
}
@@ -0,0 +1,64 @@
<?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\Common\Exceptions;
class InternalServerError extends ApiException
{
const HTTP_CODE = 500;
public $retryAfter;
public $type;
public function __construct($responseHeaders = array(), $responseBody = null)
{
$errorData = json_decode($responseBody, true);
$message = '';
if (isset($errorData['description'])) {
$message .= $errorData['description'] . '. ';
}
if (isset($errorData['code'])) {
$message .= sprintf('Error code: %s. ', $errorData['code']);
}
if (isset($errorData['parameter'])) {
$message .= sprintf('Parameter name: %s. ', $errorData['parameter']);
}
if (isset($errorData['retry_after'])) {
$this->retryAfter = $errorData['retry_after'];
}
if (isset($errorData['type'])) {
$this->type = $errorData['type'];
}
parent::__construct(trim($message), self::HTTP_CODE, $responseHeaders, $responseBody);
}
}
@@ -0,0 +1,55 @@
<?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\Common\Exceptions;
class InvalidPropertyException extends \InvalidArgumentException
{
/**
* @var string
*/
private $propertyName;
/**
* InvalidValueException constructor.
* @param string $message
* @param int $code
* @param string $property
*/
public function __construct($message = "", $code = 0, $property = "")
{
parent::__construct($message, $code);
$this->propertyName = (string)$property;
}
/**
* @return string
*/
public function getProperty()
{
return $this->propertyName;
}
}
@@ -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\Common\Exceptions;
class InvalidPropertyValueException extends InvalidPropertyException
{
/**
* @var mixed
*/
private $invalidValue;
/**
* InvalidPropertyValueTypeException constructor.
* @param string $message
* @param int $code
* @param string $property
* @param mixed $value
*/
public function __construct($message = '', $code = 0, $property = '', $value = null)
{
parent::__construct($message, $code, $property);
if ($value !== null) {
$this->invalidValue = $value;
}
}
/**
* @return mixed
*/
public function getValue()
{
return $this->invalidValue;
}
}
@@ -0,0 +1,62 @@
<?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\Common\Exceptions;
class InvalidPropertyValueTypeException extends InvalidPropertyException
{
/**
* @var string
*/
private $type;
/**
* InvalidPropertyValueTypeException constructor.
* @param string $message
* @param int $code
* @param string $property
* @param mixed $value
*/
public function __construct($message = "", $code = 0, $property = "", $value = null)
{
parent::__construct($message, $code, $property);
if ($value === null) {
$this->type = 'null';
} elseif (is_object($value)) {
$this->type = get_class($value);
} else {
$this->type = gettype($value);
}
}
/**
* @return string
*/
public function getType()
{
return $this->type;
}
}
@@ -0,0 +1,62 @@
<?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\Common\Exceptions;
use YooKassa\Common\AbstractRequest;
class InvalidRequestException extends \RuntimeException
{
/**
* @var AbstractRequest|null
*/
private $errorRequest;
/**
* InvalidRequestException constructor.
* @param AbstractRequest|string $error
* @param int $code
* @param null $previous
*/
public function __construct($error, $code = 0, $previous = null)
{
if ($error instanceof AbstractRequest) {
$message = 'Failed to build request "'.get_class($error).'": "'.$error->getLastValidationError().'"';
$this->errorRequest = $error;
} else {
$message = $error;
}
parent::__construct($message, $code, $previous);
}
/**
* @return AbstractRequest|null
*/
public function getRequestObject()
{
return $this->errorRequest;
}
}
@@ -0,0 +1,46 @@
<?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\Common\Exceptions;
class JsonException extends \UnexpectedValueException
{
public static $errorLabels = array(
JSON_ERROR_NONE => 'No error',
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
JSON_ERROR_STATE_MISMATCH => 'State mismatch (invalid or malformed JSON)',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
);
public function __construct($message = "", $code = 0, $previous = null)
{
$errorMsg = isset(self::$errorLabels[$code]) ? self::$errorLabels[$code] : 'Unknown error';
$message = sprintf('%s %s', $message, $errorMsg);
parent::__construct($message, $code, $previous);
}
}
@@ -0,0 +1,64 @@
<?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\Common\Exceptions;
class NotFoundException extends ApiException
{
const HTTP_CODE = 404;
public $type;
public $retryAfter;
public function __construct($responseHeaders = array(), $responseBody = null)
{
$errorData = json_decode($responseBody, true);
$message = '';
if (isset($errorData['description'])) {
$message .= $errorData['description'].'. ';
}
if (isset($errorData['code'])) {
$message .= sprintf('Error code: %s. ', $errorData['code']);
}
if (isset($errorData['parameter'])) {
$message .= sprintf('Parameter name: %s. ', $errorData['parameter']);
}
if (isset($errorData['retry_after'])) {
$this->retryAfter = $errorData['retry_after'];
}
if (isset($errorData['type'])) {
$this->type = $errorData['type'];
}
parent::__construct(trim($message), self::HTTP_CODE, $responseHeaders, $responseBody);
}
}
@@ -0,0 +1,56 @@
<?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\Common\Exceptions;
class ResponseProcessingException extends ApiException
{
const HTTP_CODE = 202;
public $type;
public $retryAfter;
public function __construct($responseHeaders = array(), $responseBody = null)
{
$errorData = json_decode($responseBody, true);
$message = '';
if (isset($errorData['description'])) {
$message .= $errorData['description'] . '. ';
}
if (isset($errorData['retry_after'])) {
$this->retryAfter = $errorData['retry_after'];
}
if (isset($errorData['type'])) {
$this->type = $errorData['type'];
}
parent::__construct(trim($message), self::HTTP_CODE, $responseHeaders, $responseBody);
}
}
@@ -0,0 +1,64 @@
<?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\Common\Exceptions;
class TooManyRequestsException extends ApiException
{
const HTTP_CODE = 429;
public $type;
public $retryAfter;
public function __construct($responseHeaders = array(), $responseBody = null)
{
$errorData = json_decode($responseBody, true);
$message = '';
if (isset($errorData['description'])) {
$message .= $errorData['description'] . '. ';
}
if (isset($errorData['code'])) {
$message .= sprintf('Error code: %s. ', $errorData['code']);
}
if (isset($errorData['parameter'])) {
$message .= sprintf('Parameter name: %s. ', $errorData['parameter']);
}
if (isset($errorData['retry_after'])) {
$this->retryAfter = $errorData['retry_after'];
}
if (isset($errorData['type'])) {
$this->type = $errorData['type'];
}
parent::__construct(trim($message), self::HTTP_CODE, $responseHeaders, $responseBody);
}
}
@@ -0,0 +1,64 @@
<?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\Common\Exceptions;
class UnauthorizedException extends ApiException
{
const HTTP_CODE = 401;
public $type;
public $retryAfter;
public function __construct($responseHeaders = array(), $responseBody = null)
{
$errorData = json_decode($responseBody, true);
$message = '';
if (isset($errorData['description'])) {
$message .= $errorData['description'] . '. ';
}
if (isset($errorData['code'])) {
$message .= sprintf('Error code: %s. ', $errorData['code']);
}
if (isset($errorData['parameter'])) {
$message .= sprintf('Parameter name: %s. ', $errorData['parameter']);
}
if (isset($errorData['retry_after'])) {
$this->retryAfter = $errorData['retry_after'];
}
if (isset($errorData['type'])) {
$this->type = $errorData['type'];
}
parent::__construct(trim($message), self::HTTP_CODE, $responseHeaders, $responseBody);
}
}
@@ -0,0 +1,48 @@
<?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\Common;
class HttpVerb extends AbstractEnum
{
const GET = 'GET';
const POST = 'POST';
const PATCH = 'PATCH';
const HEAD = 'HEAD';
const OPTIONS = 'OPTIONS';
const PUT = 'PUT';
const DELETE = 'DELETE';
protected static $validValues = array(
'GET' => true,
'POST' => true,
'PATCH' => true,
'HEAD' => true,
'OPTIONS' => true,
'PUT' => true,
'DELETE' => true
);
}
@@ -0,0 +1,192 @@
<?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\Common;
use Psr\Log\InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
class LoggerWrapper implements LoggerInterface
{
/**
* @var null|callable
*/
private $loggerCallback;
/**
* @var object
*/
private $loggerInstance;
/**
* LoggerWrapper constructor.
* @param object|callable $wrapped
*/
public function __construct($wrapped)
{
if (is_object($wrapped) && method_exists($wrapped, 'log')) {
$this->loggerInstance = $wrapped;
} elseif (is_callable($wrapped)) {
$this->loggerCallback = $wrapped;
} else {
throw new InvalidArgumentException('Invalid wrapped logger');
}
}
/**
* System is unusable.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function emergency($message, array $context = array())
{
$this->log(LogLevel::EMERGENCY, $message, $context);
}
/**
* Action must be taken immediately.
*
* Example: Entire website down, database unavailable, etc. This should
* trigger the SMS alerts and wake you up.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function alert($message, array $context = array())
{
$this->log(LogLevel::ALERT, $message, $context);
}
/**
* Critical conditions.
*
* Example: Application component unavailable, unexpected exception.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function critical($message, array $context = array())
{
$this->log(LogLevel::CRITICAL, $message, $context);
}
/**
* Runtime errors that do not require immediate action but should typically
* be logged and monitored.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function error($message, array $context = array())
{
$this->log(LogLevel::ERROR, $message, $context);
}
/**
* Exceptional occurrences that are not errors.
*
* Example: Use of deprecated APIs, poor use of an API, undesirable things
* that are not necessarily wrong.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function warning($message, array $context = array())
{
$this->log(LogLevel::WARNING, $message, $context);
}
/**
* Normal but significant events.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function notice($message, array $context = array())
{
$this->log(LogLevel::NOTICE, $message, $context);
}
/**
* Interesting events.
*
* Example: User logs in, SQL logs.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function info($message, array $context = array())
{
$this->log(LogLevel::INFO, $message, $context);
}
/**
* Detailed debug information.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function debug($message, array $context = array())
{
$this->log(LogLevel::DEBUG, $message, $context);
}
/**
* Logs with an arbitrary level.
*
* @param mixed $level
* @param string $message
* @param array $context
*
* @return void
*/
public function log($level, $message, array $context = array())
{
if ($this->loggerInstance !== null) {
$this->loggerInstance->log($level, $message, $context);
} elseif ($this->loggerCallback !== null) {
call_user_func_array($this->loggerCallback, array($level, $message, $context));
}
}
}
@@ -0,0 +1,73 @@
<?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\Common;
class ResponseObject
{
protected $code;
protected $headers;
protected $body;
public function __construct($config = null)
{
if (isset($config['headers'])) {
$this->headers = $config['headers'];
}
if (isset($config['body'])) {
$this->body = $config['body'];
}
if (isset($config['code'])) {
$this->code = $config['code'];
}
}
/**
* @return mixed
*/
public function getHeaders()
{
return $this->headers;
}
/**
* @return mixed
*/
public function getBody()
{
return $this->body;
}
/**
* @return mixed
*/
public function getCode()
{
return $this->code;
}
}
@@ -0,0 +1,31 @@
<?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.
*/
if (!interface_exists('JsonSerializable')) {
interface JsonSerializable {
public function jsonSerialize();
}
}