1
0
mirror of synced 2024-12-04 18:56:03 +03:00

Merge pull request #3 from IvanLutokhin/add-validators

Added validators
This commit is contained in:
IvanLutokhin 2020-08-18 16:32:07 +03:00 committed by GitHub
commit db3a4d8756
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 215 additions and 2 deletions

View File

@ -0,0 +1,7 @@
<?php
namespace RetailCrm\DeliveryModuleBundle\Exception;
class RetailCrmApiException extends \Exception
{
}

View File

@ -0,0 +1,11 @@
integration_module_access:
server_unreachable_exception: 'Failed to connect to the integration server'
module_access_exception: 'Invalid login or password'
retailcrm_access:
access_denied: 'Access to the method "%method%" is denied'
curl_exception: 'Failed to connect to API'
service_unavailable: 'Service is temporarily unavailable'
invalid_json: 'API returned a response in an unsupported format'
requires_https: 'API address must start with https'
wrong_api_key: 'Invalid API key'

View File

@ -0,0 +1,11 @@
integration_module_access:
server_unreachable_exception: 'No se ha podido conectar al servidor de integración'
module_access_exception: 'El Usuario o la contraseña no es correcta'
retailcrm_access:
access_denied: 'Acceso al método "%method%" está prohibido'
curl_exception: 'No se ha podido conectar al API'
service_unavailable: 'Servicio no está disponible temporalmente'
invalid_json: 'API ha devuelto la respuesta en el formato no soportado'
requires_https: 'Dirección del API tiene que comenzar con https'
wrong_api_key: 'El API-key no es correcto'

View File

@ -0,0 +1,11 @@
integration_module_access:
server_unreachable_exception: 'Не удалось подключиться к интеграционному серверу'
module_access_exception: 'Не верный логин или пароль'
retailcrm_access:
access_denied: 'Доступ к методу "%method%" запрещен'
curl_exception: 'Не удалось подключиться к API'
service_unavailable: 'Сервис временно недоступен'
invalid_json: 'API вернуло ответ в неподдерживаемом формате'
requires_https: 'Адрес API должен начинаться с https'
wrong_api_key: 'Неверный API-ключ'

View File

@ -25,6 +25,8 @@ interface ModuleManagerInterface
public function setAccount(Account $account): self;
public function checkAccess(): bool;
public function updateModuleConfiguration(): bool;
public function calculateDelivery(RequestCalculate $data): array;

View File

@ -0,0 +1,23 @@
<?php
namespace RetailCrm\DeliveryModuleBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
* @Target({"CLASS"})
*/
class IntegrationModuleAccess extends Constraint
{
/** @var string */
public $path = 'login';
/**
* {@inheritdoc}
*/
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
}

View File

@ -0,0 +1,44 @@
<?php
namespace RetailCrm\DeliveryModuleBundle\Validator\Constraints;
use RetailCrm\DeliveryModuleBundle\Exception\AbstractModuleException;
use RetailCrm\DeliveryModuleBundle\Exception\ServerUnreachableException;
use RetailCrm\DeliveryModuleBundle\Service\ModuleManagerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class IntegrationModuleAccessValidator extends ConstraintValidator
{
/** @var ModuleManagerInterface */
private $moduleManager;
public function __construct(ModuleManagerInterface $moduleManager)
{
$this->moduleManager = $moduleManager;
}
public function validate($account, Constraint $constraint)
{
if (!($constraint instanceof IntegrationModuleAccess)) {
throw new UnexpectedTypeException($constraint, IntegrationModuleAccess::class);
}
try {
$this->moduleManager->checkAccess();
} catch (ServerUnreachableException $e) {
$this->context
->buildViolation('integration_module_access.server_unreachable_exception')
->atPath($constraint->path)
->addViolation()
;
} catch (AbstractModuleException $e) {
$this->context
->buildViolation('integration_module_access.module_access_exception')
->atPath($constraint->path)
->addViolation()
;
}
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace App\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
* @Target({"CLASS"})
*/
class RetailCrmAccess extends Constraint
{
/** @var array */
public $requiredApiMethods = [];
/**
* {@inheritdoc}
*/
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
}

View File

@ -0,0 +1,80 @@
<?php
namespace App\Validator\Constraints;
use RetailCrm\DeliveryModuleBundle\Exception\RetailCrmApiException;
use RetailCrm\DeliveryModuleBundle\Service\ModuleManagerInterface;
use RetailCrm\Exception\CurlException;
use RetailCrm\Exception\InvalidJsonException;
use RetailCrm\Exception\LimitException;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class RetailCrmAccessValidator extends ConstraintValidator
{
/** @var ModuleManagerInterface */
private $moduleManager;
public function __construct(ModuleManagerInterface $moduleManager)
{
$this->moduleManager = $moduleManager;
}
public function validate($account, Constraint $constraint)
{
if (!($constraint instanceof RetailCrmAccess)) {
throw new UnexpectedTypeException($constraint, RetailCrmAccess::class);
}
$client = $this->moduleManager->getRetailCrmClient();
try {
$response = $client->request->credentials();
if (!$response->isSuccessful()) {
throw new RetailCrmApiException($response->offsetGet('errorMsg'));
}
$credentials = $response->offsetGet('credentials');
foreach ($constraint->requiredApiMethods as $method) {
if (!in_array($method, $credentials)) {
$this->context
->buildViolation('retailcrm_access.access_denied', ['%method%' => $method])
->atPath('crmApiKey')
->addViolation()
;
}
}
} catch (CurlException $e) {
$this->context
->buildViolation('retailcrm_access.curl_exception')
->atPath('crmUrl')
->addViolation()
;
} catch (LimitException $e) {
$this->context
->buildViolation('retailcrm_access.service_unavailable')
->atPath('crmUrl')
->addViolation()
;
} catch (InvalidJsonException $e) {
$this->context
->buildViolation('retailcrm_access.invalid_json')
->atPath('crmUrl')
->addViolation()
;
} catch (\InvalidArgumentException $e) {
$this->context
->buildViolation('retailcrm_access.requires_https')
->atPath('crmUrl')
->addViolation()
;
} catch (RetailCrmApiException $e) {
$this->context
->buildViolation('retailcrm_access.wrong_api_key')
->atPath('crmUrl')
->addViolation()
;
}
}
}

View File

@ -24,9 +24,10 @@
"symfony/framework-bundle": "^3.4|^4.0|^5.1",
"symfony/lock": "^5.1",
"symfony/routing": "^5.1",
"symfony/translation": "^5.1"
"symfony/translation": "^5.1",
"symfony/validator": "^5.1"
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.3"
}
}
}