1
0
Fork 0
mirror of synced 2025-04-05 06:03:34 +03:00
This commit is contained in:
curse89 2022-07-21 15:01:36 +00:00 committed by GitHub
commit c0dfe5c87a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
42 changed files with 250 additions and 998 deletions

2
.gitignore vendored
View file

@ -56,3 +56,5 @@ test-report.xml
.idea
coverage.xml
.docker
docker-compose*

View file

@ -5,30 +5,13 @@ namespace RetailCrm\ServiceBundle\ArgumentResolver;
use RetailCrm\ServiceBundle\Exceptions\InvalidRequestArgumentException;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* Class AbstractValueResolver
*
* @package RetailCrm\ServiceBundle\ArgumentResolver
*/
abstract class AbstractValueResolver
{
protected $validator;
/**
* AbstractValueResolver constructor.
*
* @param ValidatorInterface $validator
*/
public function __construct(ValidatorInterface $validator)
public function __construct(
protected ValidatorInterface $validator)
{
$this->validator = $validator;
}
/**
* @param object $data
*
* @return void
*/
protected function validate(object $data): void
{
$errors = $this->validator->validate($data);

View file

@ -9,37 +9,16 @@ use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
use Generator;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* Class CallbackValueResolver
*
* @package RetailCrm\ServiceBundle\ArgumentResolver
*/
class CallbackValueResolver extends AbstractValueResolver implements ArgumentValueResolverInterface
{
private $serializer;
private $requestSchema;
/**
* CallbackValueResolver constructor.
*
* @param Adapter $serializer
* @param ValidatorInterface $validator
* @param array $requestSchema
*/
public function __construct(
Adapter $serializer,
ValidatorInterface $validator,
array $requestSchema
private Adapter $serializer,
private array $requestSchema
) {
parent::__construct($validator);
$this->serializer = $serializer;
$this->requestSchema = $requestSchema;
}
/**
* {@inheritdoc }
*/
public function supports(Request $request, ArgumentMetadata $argument): bool
{
if (empty($this->requestSchema) || $request->getMethod() !== Request::METHOD_POST) {
@ -49,9 +28,6 @@ class CallbackValueResolver extends AbstractValueResolver implements ArgumentVal
return null !== $this->search($request, $argument);
}
/**
* {@inheritdoc }
*/
public function resolve(Request $request, ArgumentMetadata $argument): Generator
{
$parameter = $this->search($request, $argument);
@ -61,12 +37,6 @@ class CallbackValueResolver extends AbstractValueResolver implements ArgumentVal
yield $data;
}
/**
* @param Request $request
* @param ArgumentMetadata $argument
*
* @return string|null
*/
private function search(Request $request, ArgumentMetadata $argument): ?string
{
foreach ($this->requestSchema as $callback) {

View file

@ -9,46 +9,21 @@ use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Generator;
/**
* Class ClientValueResolver
*
* @package RetailCrm\ServiceBundle\ArgumentResolver
*/
class ClientValueResolver extends AbstractValueResolver implements ArgumentValueResolverInterface
{
private $serializer;
private $requestSchema;
/**
* ClientValueResolver constructor.
*
*
* @param Adapter $serializer
* @param ValidatorInterface $validator
* @param array $requestSchema
*/
public function __construct(
Adapter $serializer,
ValidatorInterface $validator,
array $requestSchema
private Adapter $serializer,
private array $requestSchema
) {
parent::__construct($validator);
$this->serializer = $serializer;
$this->requestSchema = $requestSchema;
}
/**
* {@inheritdoc}
*/
public function supports(Request $request, ArgumentMetadata $argument): bool
{
return in_array($argument->getType(), $this->requestSchema, true);
}
/**
* {@inheritdoc}
*/
public function resolve(Request $request, ArgumentMetadata $argument): Generator
{
if (Request::METHOD_GET === $request->getMethod()) {
@ -62,23 +37,11 @@ class ClientValueResolver extends AbstractValueResolver implements ArgumentValue
yield $dto;
}
/**
* @param array $data
* @param string $type
*
* @return object
*/
private function handleGetData(array $data, string $type): object
{
return $this->serializer->arrayToObject($data, $type);
}
/**
* @param string $data
* @param string $type
*
* @return object
*/
private function handlePostData(string $data, string $type): object
{
return $this->serializer->deserialize($data, $type);

View file

@ -5,16 +5,8 @@ namespace RetailCrm\ServiceBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* Class Configuration
*
* @package RetailCrm\ServiceBundle\DependencyInjection
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc }
*/
public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('retail_crm_service');

View file

@ -6,25 +6,15 @@ use RetailCrm\ServiceBundle\ArgumentResolver\CallbackValueResolver;
use RetailCrm\ServiceBundle\ArgumentResolver\ClientValueResolver;
use RetailCrm\ServiceBundle\Messenger\MessageHandler;
use RetailCrm\ServiceBundle\Response\ErrorJsonResponseFactory;
use RetailCrm\ServiceBundle\Security\CallbackClientAuthenticator;
use RetailCrm\ServiceBundle\Security\FrontApiClientAuthenticator;
use RetailCrm\ServiceBundle\Security\ApiClientAuthenticator;
use RetailCrm\ServiceBundle\Serializer\JMSSerializerAdapter;
use RetailCrm\ServiceBundle\Serializer\SymfonySerializerAdapter;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Reference;
/**
* Class RetailCrmServiceExtension
*
* @package RetailCrm\ServiceBundle\DependencyInjection
*/
class RetailCrmServiceExtension extends Extension
{
/**
* @param array $configs
* @param ContainerBuilder $container
*/
public function load(array $configs, ContainerBuilder $container): void
{
$configuration = $this->getConfiguration($configs, $container);
@ -75,8 +65,8 @@ class RetailCrmServiceExtension extends Extension
$container
->register(CallbackValueResolver::class)
->setArguments([
new Reference($container->getParameter('retail_crm_service.request_schema.callback.serializer')),
new Reference('validator'),
new Reference($container->getParameter('retail_crm_service.request_schema.callback.serializer')),
$container->getParameter('retail_crm_service.request_schema.callback.supports')
])
->addTag('controller.argument_value_resolver', ['priority' => 50])
@ -85,8 +75,8 @@ class RetailCrmServiceExtension extends Extension
$container
->register(ClientValueResolver::class)
->setArguments([
new Reference($container->getParameter('retail_crm_service.request_schema.client.serializer')),
new Reference('validator'),
new Reference($container->getParameter('retail_crm_service.request_schema.client.serializer')),
$container->getParameter('retail_crm_service.request_schema.client.supports')
])
->addTag('controller.argument_value_resolver', ['priority' => 50])
@ -97,11 +87,7 @@ class RetailCrmServiceExtension extends Extension
->setAutowired(true);
$container
->register(CallbackClientAuthenticator::class)
->setAutowired(true);
$container
->register(FrontApiClientAuthenticator::class)
->register(ApiClientAuthenticator::class)
->setAutowired(true);
$container

View file

@ -5,32 +5,17 @@ namespace RetailCrm\ServiceBundle\Exceptions;
use InvalidArgumentException;
use Throwable;
/**
* Class InvalidRequestArgumentException
*
* @package RetailCrm\ServiceBundle\Exceptions
*/
class InvalidRequestArgumentException extends InvalidArgumentException
{
private $validateErrors;
/**
* InvalidRequestArgumentException constructor.
* @param string $message
* @param int $code
* @param array $errors
* @param Throwable|null $previous
*/
public function __construct($message = "", $code = 0, iterable $errors = [], Throwable $previous = null)
public function __construct(string $message = "", int $code = 0, iterable $errors = [], Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
$this->validateErrors = $errors;
}
/**
* @return iterable
*/
public function getValidateErrors(): iterable
{
return $this->validateErrors;

View file

@ -2,91 +2,54 @@
namespace RetailCrm\ServiceBundle\Messenger;
/**
* Class Message
*
* @package RetailCrm\ServiceBundle\Messenger
*/
abstract class CommandMessage
{
/** @var string */
protected $commandName;
protected string $commandName;
/** @var array */
protected $options = [];
protected array $options = [];
/** @var array */
protected $arguments = [];
protected array $arguments = [];
/**
* @return string
*/
public function getCommandName(): string
{
return $this->commandName;
}
/**
* @param string $commandName
*/
public function setCommandName(string $commandName): void
{
$this->commandName = $commandName;
}
/**
* @return array
*/
public function getOptions(): array
{
return $this->options;
}
/**
* @param array $options
*/
public function setOptions(array $options): void
{
$this->options = $options;
}
/**
* @return array
*/
public function getArguments(): array
{
return $this->arguments;
}
/**
* @param array $arguments
*/
public function setArguments(array $arguments): void
{
$this->arguments = $arguments;
}
/**
* @param string $key
* @param string $value
*/
public function addOption(string $key, string $value): void
{
$this->options[$key] = $value;
}
/**
* @param string $key
* @param string $value
*/
public function addArgument(string $key, string $value): void
{
$this->arguments[$key] = $value;
}
/**
* @return array
*/
public function getFormattedOptions(): array
{
$options = [];
@ -97,11 +60,6 @@ abstract class CommandMessage
return $options;
}
/**
* For lockable message
*
* @return array
*/
public function __serialize(): array
{
return [

View file

@ -6,31 +6,13 @@ use RetailCrm\ServiceBundle\Messenger\MessageHandler\JobRunner;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
use Exception;
/**
* Class MessageHandler
*
* @package RetailCrm\ServiceBundle\Messenger
*/
class MessageHandler implements MessageHandlerInterface
{
/**
* @var JobRunner
*/
private $runner;
/**
* CommandQueueHandler constructor.
*
* @param JobRunner $runner
*/
public function __construct(JobRunner $runner)
public function __construct(private JobRunner $runner)
{
$this->runner = $runner;
}
/**
* @param CommandMessage $message
*
* @throws Exception
*/
public function __invoke(CommandMessage $message): void

View file

@ -9,38 +9,17 @@ use Symfony\Component\Process\Exception\ProcessTimedOutException;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\Process;
/**
* Class InNewProcessRunner
*
* @package RetailCrm\ServiceBundle\Messenger\MessageHandler
*/
class InNewProcessRunner implements JobRunner
{
/** @var int Default timeout for process */
public const DEFAULT_TIMEOUT = 3600;
/**
* @var LoggerInterface
*/
private $logger;
private LoggerInterface $logger;
/**
* @var KernelInterface
*/
private $kernel;
private KernelInterface $kernel;
/**
* @var int
*/
private $timeout = self::DEFAULT_TIMEOUT;
private int $timeout = self::DEFAULT_TIMEOUT;
/**
* CommandQueueHandler constructor.
*
* @param LoggerInterface $logger
* @param KernelInterface $kernel
* @param int|null $timeout
*/
public function __construct(
LoggerInterface $logger,
KernelInterface $kernel,
@ -54,9 +33,6 @@ class InNewProcessRunner implements JobRunner
}
}
/**
* {@inheritdoc}
*/
public function run(CommandMessage $message): void
{
$phpBinaryPath = (new PhpExecutableFinder)->find();
@ -92,11 +68,6 @@ class InNewProcessRunner implements JobRunner
}
}
/**
* @param CommandMessage $message
*
* @return array
*/
private function getOptions(CommandMessage $message): array
{
$options = [];

View file

@ -4,15 +4,7 @@ namespace RetailCrm\ServiceBundle\Messenger\MessageHandler;
use RetailCrm\ServiceBundle\Messenger\CommandMessage;
/**
* Interface JobRunner
*
* @package RetailCrm\ServiceBundle\Messenger\MessageHandler
*/
interface JobRunner
{
/**
* @param CommandMessage $message
*/
public function run(CommandMessage $message): void;
}

View file

@ -9,38 +9,12 @@ use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\HttpKernel\KernelInterface;
/**
* Class SimpleConsoleRunner
*
* @package RetailCrm\ServiceBundle\Messenger\MessageHandler
*/
class SimpleConsoleRunner implements JobRunner
{
/**
* @var LoggerInterface
*/
private $logger;
/**
* @var KernelInterface
*/
private $kernel;
/**
* CommandQueueHandler constructor.
*
* @param LoggerInterface $logger
* @param KernelInterface $kernel
*/
public function __construct(LoggerInterface $logger, KernelInterface $kernel)
public function __construct(private LoggerInterface $logger, private KernelInterface $kernel)
{
$this->logger = $logger;
$this->kernel = $kernel;
}
/**
* {@inheritdoc}
*/
public function run(CommandMessage $message): void
{
$application = new Application($this->kernel);

View file

@ -2,11 +2,6 @@
namespace RetailCrm\ServiceBundle\Messenger\Middleware;
/**
* Interface LockableMessage
*
* @package RetailCrm\ServiceBundle\Messenger\Middleware
*/
interface LockableMessage
{
public function __serialize(): array;

View file

@ -9,29 +9,13 @@ use Symfony\Component\Messenger\Middleware\StackInterface;
use Symfony\Component\Messenger\Stamp\ReceivedStamp;
use Throwable;
/**
* Class LockableMessageMiddleware
*
* @package RetailCrm\ServiceBundle\Messenger\Middleware
*/
class LockableMessageMiddleware implements MiddlewareInterface
{
/**
* @var LockFactory
*/
private $lockFactory;
public function __construct(LockFactory $lockFactory)
public function __construct(private LockFactory $lockFactory)
{
$this->lockFactory = $lockFactory;
}
/**
* @param Envelope $envelope
* @param StackInterface $stack
*
* @return Envelope
*
* @throws Throwable
*/
public function handle(Envelope $envelope, StackInterface $stack): Envelope
@ -56,11 +40,6 @@ class LockableMessageMiddleware implements MiddlewareInterface
return $stack->next()->handle($envelope, $stack);
}
/**
* @param LockableMessage $message
*
* @return string
*/
private function objectHash(LockableMessage $message): string
{
return hash('crc32', serialize($message));

View file

@ -2,11 +2,6 @@
namespace RetailCrm\ServiceBundle\Models;
/**
* Class Error
*
* @package RetailCrm\ServiceBundle\Models
*/
class Error
{
/**

View file

@ -2,6 +2,8 @@
#### Callbacks (form data)
> For successful deserialization of an entity, there must be setters for the passed parameters
To automatically get the callback request parameter
```php

View file

@ -4,67 +4,58 @@ Example security configuration:
```yaml
security:
hide_user_not_found: false
providers:
client:
entity:
class: 'App\Entity\Connection' # must implements UserInterface
property: 'clientId'
connection:
entity: { class: App\Entity\Connection, property: clientId }
firewalls:
api:
pattern: ^/api
provider: client
anonymous: ~
lazy: true
stateless: false
guard:
authenticators:
- RetailCrm\ServiceBundle\Security\FrontApiClientAuthenticator
callback:
pattern: ^/callback
provider: client
anonymous: ~
lazy: true
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
simple-connection:
pattern: ^/simple-connection
stateless: true
guard:
authenticators:
- RetailCrm\ServiceBundle\Security\CallbackClientAuthenticator
security: false
front:
pattern: ^/front
provider: connection
stateless: true
custom_authenticators:
- RetailCrm\ServiceBundle\Security\FrontApiClientAuthenticator
main:
anonymous: true
pattern: ^/
lazy: true
access_control:
- { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY } # login for programmatically authentication user
- { path: ^/api, roles: ROLE_USER }
- { path: ^/callback, roles: ROLE_USER }
- { path: ^/front, roles: IS_AUTHENTICATED_FULLY }
- { path: ^/(simple-connection), roles: PUBLIC_ACCESS }
```
To authenticate the user after creating it, you can use the following code
Login controller will be called after the authenticator successfully authenticates the user. You can get the authenticated user, generate a token (or whatever you need to return) and return response:
```php
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
use RetailCrm\ServiceBundle\Security\FrontApiClientAuthenticator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Entity\User;
use Symfony\Component\Security\Http\Attribute\CurrentUser;
class AppController extends AbstractController
{
public function someAction(
Request $request,
GuardAuthenticatorHandler $guardAuthenticatorHandler,
FrontApiClientAuthenticator $frontApiClientAuthenticator,
ConnectionManager $manager
): Response {
$user = $manager->getUser(); // getting user
$guardAuthenticatorHandler->authenticateUserAndHandleSuccess(
$user,
$request,
$frontApiClientAuthenticator,
'api'
);
// ...
class ApiLoginController extends AbstractController
{
#[Route('/front', name: 'front')]
public function front(#[CurrentUser] ?User $user): Response
{
$token = ...; // somehow create an API token for $user
return $this->json([
'user' => $user->getUserIdentifier(),
'token' => $token,
]);
}
}
}
```
The <code>#[CurrentUser]</code> can only be used in controller arguments to retrieve the authenticated user. In services, you would use getUser().
See the [manual](https://symfony.com/doc/6.0/security.html) for more information.
> If you set the parameter stateless: false, then during an active session the login will be made on the basis of the data deserialized from the session storage

View file

@ -7,32 +7,12 @@ use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\SerializerInterface;
/**
* Class ErrorJsonResponseFactory
*
* @package RetailCrm\ServiceBundle\Response
*/
class ErrorJsonResponseFactory
{
private $serializer;
/**
* ErrorJsonResponseFactory constructor.
*
* @param SerializerInterface $serializer
*/
public function __construct(SerializerInterface $serializer)
public function __construct(private SerializerInterface $serializer)
{
$this->serializer = $serializer;
}
/**
* @param Error $error
* @param int $statusCode
* @param array $headers
*
* @return Response
*/
public function create(Error $error, int $statusCode = Response::HTTP_BAD_REQUEST, array $headers = []): Response
{
return JsonResponse::fromJsonString(

View file

@ -2,75 +2,28 @@
namespace RetailCrm\ServiceBundle\Security;
use Doctrine\Persistence\ObjectRepository;
use RetailCrm\ServiceBundle\Models\Error;
use RetailCrm\ServiceBundle\Response\ErrorJsonResponseFactory;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
/**
* Class AbstractClientAuthenticator
*
* @package RetailCrm\ServiceBundle\Security
*/
abstract class AbstractClientAuthenticator extends AbstractGuardAuthenticator
abstract class AbstractClientAuthenticator extends AbstractAuthenticator
{
public const AUTH_FIELD = 'clientId';
private $errorResponseFactory;
/**
* AbstractClientAuthenticator constructor.
*
* @param ErrorJsonResponseFactory $errorResponseFactory
*/
public function __construct(ErrorJsonResponseFactory $errorResponseFactory)
public function __construct(private ErrorJsonResponseFactory $errorResponseFactory)
{
$this->errorResponseFactory = $errorResponseFactory;
}
/**
* {@inheritdoc }
*/
public function start(Request $request, AuthenticationException $authException = null): Response
{
$error = new Error();
$error->message = 'Authentication required';
abstract public function supports(Request $request): ?bool;
return $this->errorResponseFactory->create($error,Response::HTTP_UNAUTHORIZED);
}
abstract public function authenticate(Request $request): Passport;
/**
* {@inheritdoc }
*/
public function getCredentials(Request $request): string
{
return $request->get(static::AUTH_FIELD);
}
/**
* {@inheritdoc }
*/
public function getUser($credentials, UserProviderInterface $userProvider): ?UserInterface
{
return $userProvider->loadUserByUsername($credentials);
}
/**
* {@inheritdoc }
*/
public function checkCredentials($credentials, UserInterface $user): bool
{
return true;
}
/**
* {@inheritdoc }
*/
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
$error = new Error();
@ -79,9 +32,6 @@ abstract class AbstractClientAuthenticator extends AbstractGuardAuthenticator
return $this->errorResponseFactory->create($error,Response::HTTP_FORBIDDEN);
}
/**
* {@inheritdoc }
*/
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $providerKey): ?Response
{
return null;

View file

@ -0,0 +1,45 @@
<?php
namespace RetailCrm\ServiceBundle\Security;
use RetailCrm\ServiceBundle\Response\ErrorJsonResponseFactory;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
class ApiClientAuthenticator extends AbstractClientAuthenticator
{
public function __construct(
ErrorJsonResponseFactory $errorResponseFactory,
private Security $security,
) {
parent::__construct($errorResponseFactory);
}
public function supports(Request $request): bool
{
if ($this->security->getUser()) {
return false;
}
return $request->request->has(static::AUTH_FIELD);
}
public function authenticate(Request $request): Passport
{
$identifier = $request->request->get(static::AUTH_FIELD);
if (null === $identifier) {
throw new AuthenticationException('Request does not contain authentication data');
}
return new SelfValidatingPassport(
new UserBadge(
$identifier
),
[]
);
}
}

View file

@ -1,29 +0,0 @@
<?php
namespace RetailCrm\ServiceBundle\Security;
use Symfony\Component\HttpFoundation\Request;
/**
* Class CallbackClientAuthenticator
*
* @package RetailCrm\ServiceBundle\Security
*/
class CallbackClientAuthenticator extends AbstractClientAuthenticator
{
/**
* {@inheritdoc }
*/
public function supports(Request $request): bool
{
return $request->request->has(static::AUTH_FIELD) || $request->query->has(static::AUTH_FIELD);
}
/**
* {@inheritdoc }
*/
public function supportsRememberMe(): bool
{
return false;
}
}

View file

@ -1,52 +0,0 @@
<?php
namespace RetailCrm\ServiceBundle\Security;
use RetailCrm\ServiceBundle\Response\ErrorJsonResponseFactory;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Security;
/**
* Class FrontApiClientAuthenticator
*
* @package RetailCrm\ServiceBundle\Security
*/
class FrontApiClientAuthenticator extends AbstractClientAuthenticator
{
private $security;
/**
* FrontApiClientAuthenticator constructor.
*
* @param ErrorJsonResponseFactory $errorResponseFactory
* @param Security $security
*/
public function __construct(
ErrorJsonResponseFactory $errorResponseFactory,
Security $security
) {
parent::__construct($errorResponseFactory);
$this->security = $security;
}
/**
* {@inheritdoc }
*/
public function supports(Request $request): bool
{
if ($this->security->getUser()) {
return false;
}
return $request->request->has(static::AUTH_FIELD);
}
/**
* {@inheritdoc }
*/
public function supportsRememberMe(): bool
{
return true;
}
}

View file

@ -2,28 +2,9 @@
namespace RetailCrm\ServiceBundle\Serializer;
/**
* Interface Adapter
*
* @package RetailCrm\ServiceBundle\Serializer
*/
interface Adapter
{
/**
* @param string $data
* @param string $type
* @param string $format
*
* @return object
*/
public function deserialize(string $data, string $type, string $format = 'json'): object;
/**
* @param array $data
* @param string $type
* @param string|null $format
*
* @return object
*/
public function arrayToObject(array $data, string $type, ?string $format = null): object;
}

View file

@ -6,50 +6,26 @@ use JMS\Serializer\ArrayTransformerInterface;
use JMS\Serializer\Context;
use JMS\Serializer\SerializerInterface;
/**
* Class JMSSerializerAdapter
*
* @package RetailCrm\ServiceBundle\Serializer
*/
class JMSSerializerAdapter implements Adapter
{
private $serializer;
private $transformer;
private $context;
/**
* JMSSerializerAdapter constructor.
*
* @param SerializerInterface $serializer
* @param ArrayTransformerInterface $transformer
*/
public function __construct(
SerializerInterface $serializer,
ArrayTransformerInterface $transformer
private SerializerInterface $serializer,
private ArrayTransformerInterface $transformer
) {
$this->serializer = $serializer;
$this->transformer = $transformer;
}
/**
* {@inheritdoc }
*/
public function deserialize(string $data, string $type, string $format = 'json'): object
{
return $this->serializer->deserialize($data, $type, $format, $this->context);
}
/**
* {@inheritdoc }
*/
public function arrayToObject(array $data, string $type, ?string $format = null): object
{
return $this->transformer->fromArray($data, $type, $this->context);
}
/**
* @param Context $context
*/
public function setContext(Context $context): void
{
$this->context = $context;

View file

@ -5,48 +5,24 @@ namespace RetailCrm\ServiceBundle\Serializer;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\SerializerInterface;
/**
* Class SymfonySerializerAdapter
*
* @package RetailCrm\ServiceBundle\Serializer
*/
class SymfonySerializerAdapter implements Adapter
{
private $serializer;
private $denormalizer;
private $context = [];
private array $context = [];
/**
* SymfonySerializerAdapter constructor.
*
* @param SerializerInterface $serializer
* @param DenormalizerInterface $denormalizer
*/
public function __construct(SerializerInterface $serializer, DenormalizerInterface $denormalizer)
public function __construct(private SerializerInterface $serializer, private DenormalizerInterface $denormalizer)
{
$this->serializer = $serializer;
$this->denormalizer = $denormalizer;
}
/**
* {@inheritdoc }
*/
public function deserialize(string $data, string $type,string $format = 'json'): object
{
return $this->serializer->deserialize($data, $type, $format, $this->context);
}
/**
* {@inheritdoc }
*/
public function arrayToObject(array $data, string $type, string $format = null): object
{
return $this->denormalizer->denormalize($data, $type, $format, $this->context);
}
/**
* @param array $context
*/
public function setContext(array $context): void
{
$this->context = $context;

View file

@ -15,11 +15,6 @@ use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Validator\Validation;
use Generator;
/**
* Class CallbackValueResolverTest
*
* @package RetailCrm\ServiceBundle\Tests\ArgumentResolver
*/
class CallbackValueResolverTest extends TestCase
{
private $resolver;
@ -28,10 +23,11 @@ class CallbackValueResolverTest extends TestCase
{
$serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]);
$this->resolver = new CallbackValueResolver(
new SymfonySerializerAdapter($serializer, $serializer),
Validation::createValidatorBuilder()
->enableAnnotationMapping()
->addDefaultDoctrineAnnotationReader()
->getValidator(),
new SymfonySerializerAdapter($serializer, $serializer),
[
[
'type' => RequestDto::class,

View file

@ -15,11 +15,6 @@ use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Validator\Validation;
use Generator;
/**
* Class ClientValueResolverTest
*
* @package RetailCrm\ServiceBundle\Tests\ArgumentResolver
*/
class ClientValueResolverTest extends TestCase
{
private $resolver;
@ -28,10 +23,11 @@ class ClientValueResolverTest extends TestCase
{
$serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]);
$this->resolver = new ClientValueResolver(
new SymfonySerializerAdapter($serializer, $serializer),
Validation::createValidatorBuilder()
->enableAnnotationMapping()
->addDefaultDoctrineAnnotationReader()
->getValidator(),
new SymfonySerializerAdapter($serializer, $serializer),
[
RequestDto::class
]

View file

@ -5,11 +5,6 @@ namespace RetailCrm\ServiceBundle\Tests\DataFixtures;
use Symfony\Component\Validator\Constraints as Assert;
use JMS\Serializer\Annotation as JMS;
/**
* Class RequestDto
*
* @package RetailCrm\ServiceBundle\Tests\DataFixtures
*/
class RequestDto
{
/**

View file

@ -4,28 +4,15 @@ namespace RetailCrm\ServiceBundle\Tests\DataFixtures;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Class User
*
* @package RetailCrm\ServiceBundle\Tests\DataFixtures
*/
class User implements UserInterface
{
protected string $clientId = '123';
public function getRoles(): array
{
return ["USER"];
}
public function getPassword(): string
{
return "123";
}
public function getSalt(): string
{
return "salt";
}
public function getUsername(): string
{
return "user";
@ -34,4 +21,9 @@ class User implements UserInterface
public function eraseCredentials(): void
{
}
public function getUserIdentifier(): string
{
return $this->clientId;
}
}

View file

@ -6,11 +6,6 @@ use PHPUnit\Framework\TestCase;
use RetailCrm\ServiceBundle\DependencyInjection\Configuration;
use Symfony\Component\Config\Definition\Processor;
/**
* Class ConfigurationTest
*
* @package RetailCrm\ServiceBundle\Tests\DependencyInjection
*/
class ConfigurationTest extends TestCase
{
public function testConfig(): void

View file

@ -7,16 +7,10 @@ use RetailCrm\ServiceBundle\ArgumentResolver\CallbackValueResolver;
use RetailCrm\ServiceBundle\ArgumentResolver\ClientValueResolver;
use RetailCrm\ServiceBundle\DependencyInjection\RetailCrmServiceExtension;
use RetailCrm\ServiceBundle\Response\ErrorJsonResponseFactory;
use RetailCrm\ServiceBundle\Security\CallbackClientAuthenticator;
use RetailCrm\ServiceBundle\Security\FrontApiClientAuthenticator;
use RetailCrm\ServiceBundle\Security\ApiClientAuthenticator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag;
/**
* Class RetailCrmServiceExtensionTest
*
* @package RetailCrm\ServiceBundle\Tests\DependencyInjection
*/
class RetailCrmServiceExtensionTest extends TestCase
{
private $container;
@ -57,7 +51,6 @@ class RetailCrmServiceExtensionTest extends TestCase
static::assertTrue($this->container->hasDefinition(CallbackValueResolver::class));
static::assertTrue($this->container->hasDefinition(ClientValueResolver::class));
static::assertTrue($this->container->hasDefinition(ErrorJsonResponseFactory::class));
static::assertTrue($this->container->hasDefinition(CallbackClientAuthenticator::class));
static::assertTrue($this->container->hasDefinition(FrontApiClientAuthenticator::class));
static::assertTrue($this->container->hasDefinition(ApiClientAuthenticator::class));
}
}

View file

@ -3,21 +3,20 @@
namespace RetailCrm\ServiceBundle\Tests\Fixtures\App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class Kernel extends \Symfony\Component\HttpKernel\Kernel
{
use MicroKernelTrait;
public function registerBundles()
public function registerBundles(): array
{
return [
new \Symfony\Bundle\FrameworkBundle\FrameworkBundle()
];
}
protected function configureContainer(ContainerBuilder $container/*, LoaderInterface $loader*/): void
protected function configureContainer(ContainerBuilder $container): void
{
$container
->register(TestCommand::class, TestCommand::class)
@ -26,8 +25,4 @@ class Kernel extends \Symfony\Component\HttpKernel\Kernel
$container->setParameter('kernel.project_dir', __DIR__ . '/..');
}
// public function registerContainerConfiguration(LoaderInterface $loader)
// {
// }
}

View file

@ -5,11 +5,6 @@ namespace RetailCrm\ServiceBundle\Tests\Messenger;
use PHPUnit\Framework\TestCase;
use RetailCrm\ServiceBundle\Tests\DataFixtures\TestMessage;
/**
* Class CommandMessageTest
*
* @package RetailCrm\ServiceBundle\Tests\Messenger
*/
class CommandMessageTest extends TestCase
{
public function testMessage(): void

View file

@ -7,11 +7,6 @@ use RetailCrm\ServiceBundle\Messenger\MessageHandler\InNewProcessRunner;
use RetailCrm\ServiceBundle\Tests\Fixtures\App\TestCommandMessage;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
/**
* Class InNewProcessRunnerTest
*
* @package RetailCrm\ServiceBundle\Tests\Messenger\MessageHandler
*/
class InNewProcessRunnerTest extends KernelTestCase
{
protected function setUp(): void

View file

@ -7,11 +7,6 @@ use RetailCrm\ServiceBundle\Messenger\MessageHandler\SimpleConsoleRunner;
use RetailCrm\ServiceBundle\Tests\Fixtures\App\TestCommandMessage;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
/**
* Class SimpleConsoleRunnerTest
*
* @package RetailCrm\ServiceBundle\Tests\Messenger\MessageHandler
*/
class SimpleConsoleRunnerTest extends KernelTestCase
{
protected function setUp(): void

View file

@ -7,11 +7,6 @@ use RetailCrm\ServiceBundle\Messenger\CommandMessage;
use RetailCrm\ServiceBundle\Messenger\MessageHandler;
use RetailCrm\ServiceBundle\Messenger\MessageHandler\JobRunner;
/**
* Class MessageHandlerTest
*
* @package RetailCrm\ServiceBundle\Tests\Messenger
*/
class MessageHandlerTest extends TestCase
{
public function testRun(): void

View file

@ -15,17 +15,9 @@ use Symfony\Component\Messenger\Middleware\MiddlewareInterface;
use Symfony\Component\Messenger\Middleware\StackInterface;
use Symfony\Component\Messenger\Stamp\ReceivedStamp;
/**
* Class LockableMessageMiddlewareTest
*
* @package RetailCrm\ServiceBundle\Tests\Messenger\Middleware
*/
class LockableMessageMiddlewareTest extends TestCase
{
/**
* @var LockFactory
*/
private $lockFactory;
private LockFactory $lockFactory;
protected function setUp(): void
{
@ -35,7 +27,7 @@ class LockableMessageMiddlewareTest extends TestCase
public function testHandle(): void
{
$store = $this->createMock(PersistingStoreInterface::class);
$key = new Key(uniqid());
$key = new Key(uniqid('', true));
$lock = new Lock($key, $store);
$this->lockFactory->expects(static::once())->method('createLock')->willReturn($lock);
$envelope = new Envelope(new TestMessage(), [new ReceivedStamp('test')]);
@ -55,7 +47,7 @@ class LockableMessageMiddlewareTest extends TestCase
{
$store = $this->createMock(PersistingStoreInterface::class);
$store->method('save')->willThrowException(new LockConflictedException);
$key = new Key(uniqid());
$key = new Key(uniqid('', true));
$lock = new Lock($key, $store);
$this->lockFactory->expects(static::once())->method('createLock')->willReturn($lock);
$envelope = new Envelope(new TestMessage(), [new ReceivedStamp('test')]);
@ -75,7 +67,7 @@ class LockableMessageMiddlewareTest extends TestCase
{
$store = $this->createMock(PersistingStoreInterface::class);
$store->method('save')->willThrowException(new LockConflictedException);
$key = new Key(uniqid());
$key = new Key(uniqid('', true));
$lock = new Lock($key, $store);
$this->lockFactory->expects(static::never())->method('createLock')->willReturn($lock);
$envelope = new Envelope(new \stdClass(), [new ReceivedStamp('test')]);
@ -95,7 +87,7 @@ class LockableMessageMiddlewareTest extends TestCase
{
$store = $this->createMock(PersistingStoreInterface::class);
$store->method('save')->willThrowException(new LockConflictedException);
$key = new Key(uniqid());
$key = new Key(uniqid('', true));
$lock = new Lock($key, $store);
$this->lockFactory->expects(static::never())->method('createLock')->willReturn($lock);
$envelope = new Envelope(new TestMessage());

View file

@ -0,0 +1,94 @@
<?php
namespace RetailCrm\ServiceBundle\Tests\Security;
use PHPUnit\Framework\TestCase;
use RetailCrm\ServiceBundle\Response\ErrorJsonResponseFactory;
use RetailCrm\ServiceBundle\Security\ApiClientAuthenticator;
use RetailCrm\ServiceBundle\Tests\DataFixtures\User;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
class ApiClientAuthenticatorTest extends TestCase
{
public function testOnAuthenticationFailure(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$errorResponseFactory
->expects(static::once())
->method('create')
->willReturn(
new JsonResponse(
['message' => 'An authentication exception occurred.'],
Response::HTTP_FORBIDDEN
)
);
$security = $this->createMock(Security::class);
$auth = new ApiClientAuthenticator($errorResponseFactory, $security);
$result = $auth->onAuthenticationFailure(new Request(), new AuthenticationException());
static::assertInstanceOf(JsonResponse::class, $result);
static::assertEquals(Response::HTTP_FORBIDDEN, $result->getStatusCode());
}
public function testSupportsFalse(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$security = $this->createMock(Security::class);
$security->method('getUser')->willReturn(new User());
$auth = new ApiClientAuthenticator($errorResponseFactory, $security);
$result = $auth->supports(new Request());
static::assertFalse($result);
}
public function testSupportsTrue(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$security = $this->createMock(Security::class);
$security->method('getUser')->willReturn(null);
$auth = new ApiClientAuthenticator($errorResponseFactory, $security);
$result = $auth->supports(new Request([], [ApiClientAuthenticator::AUTH_FIELD => '123']));
static::assertTrue($result);
}
public function testAuthenticate(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$security = $this->createMock(Security::class);
$user = new User();
$auth = new ApiClientAuthenticator($errorResponseFactory, $security);
$passport = $auth->authenticate(new Request([], [ApiClientAuthenticator::AUTH_FIELD => '123']));
static::assertTrue($passport->hasBadge(UserBadge::class));
static::assertEquals(
$user->getUserIdentifier(),
$passport->getBadge(UserBadge::class)->getUserIdentifier()
);
$this->expectException(AuthenticationException::class);
$auth->authenticate(new Request());
}
public function testOnAuthenticationSuccess(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$security = $this->createMock(Security::class);
$request = $this->createMock(Request::class);
$token = $this->createMock(TokenInterface::class);
$auth = new ApiClientAuthenticator($errorResponseFactory, $security);
$result = $auth->onAuthenticationSuccess($request, $token, 'key');
static::assertNull($result);
}
}

View file

@ -1,168 +0,0 @@
<?php
namespace RetailCrm\ServiceBundle\Tests\Security;
use PHPUnit\Framework\TestCase;
use RetailCrm\ServiceBundle\Response\ErrorJsonResponseFactory;
use RetailCrm\ServiceBundle\Security\CallbackClientAuthenticator;
use RetailCrm\ServiceBundle\Tests\DataFixtures\User;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
/**
* Class CallbackClientAuthenticatorTest
*
* @package RetailCrm\ServiceBundle\Tests\Security
*/
class CallbackClientAuthenticatorTest extends TestCase
{
public function testStart(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$errorResponseFactory
->expects(static::once())
->method('create')
->willReturn(
new JsonResponse(['message' => 'Authentication required'], Response::HTTP_UNAUTHORIZED)
);
$auth = new CallbackClientAuthenticator($errorResponseFactory);
$result = $auth->start(new Request(), new AuthenticationException());
static::assertInstanceOf(JsonResponse::class, $result);
static::assertEquals(Response::HTTP_UNAUTHORIZED, $result->getStatusCode());
}
public function testGetCredentials(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$auth = new CallbackClientAuthenticator($errorResponseFactory);
$result = $auth->getCredentials(new Request([], [CallbackClientAuthenticator::AUTH_FIELD => '123']));
static::assertEquals('123', $result);
$result = $auth->getCredentials(new Request([CallbackClientAuthenticator::AUTH_FIELD => '123']));
static::assertEquals('123', $result);
}
public function testCheckCredentials(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$user = new class implements UserInterface {
public function getRoles(): array
{
return ["USER"];
}
public function getPassword(): string
{
return "123";
}
public function getSalt(): string
{
return "salt";
}
public function getUsername(): string
{
return "user";
}
public function eraseCredentials(): void
{
}
};
$auth = new CallbackClientAuthenticator($errorResponseFactory);
$result = $auth->checkCredentials(new Request(), $user);
static::assertTrue($result);
}
public function testOnAuthenticationFailure(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$errorResponseFactory
->expects(static::once())
->method('create')
->willReturn(
new JsonResponse(
['message' => 'An authentication exception occurred.'],
Response::HTTP_FORBIDDEN
)
);
$auth = new CallbackClientAuthenticator($errorResponseFactory);
$result = $auth->onAuthenticationFailure(new Request(), new AuthenticationException());
static::assertInstanceOf(JsonResponse::class, $result);
static::assertEquals(Response::HTTP_FORBIDDEN, $result->getStatusCode());
}
public function testSupports(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$auth = new CallbackClientAuthenticator($errorResponseFactory);
$result = $auth->supports(new Request([], [CallbackClientAuthenticator::AUTH_FIELD => '123']));
static::assertTrue($result);
$result = $auth->supports(new Request([CallbackClientAuthenticator::AUTH_FIELD => '123']));
static::assertTrue($result);
$result = $auth->supports(new Request());
static::assertFalse($result);
}
public function testSupportsRememberMe(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$auth = new CallbackClientAuthenticator($errorResponseFactory);
$result = $auth->supportsRememberMe();
static::assertFalse($result);
}
public function testGetUser(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$user = new User();
$auth = new CallbackClientAuthenticator($errorResponseFactory);
$userProvider = $this->createMock(UserProviderInterface::class);
$userProvider
->expects(static::once())
->method('loadUserByUsername')
->with('clientId')
->willReturn($user)
;
$result = $auth->getUser('clientId', $userProvider);
static::assertEquals($user, $result);
}
public function testOnAuthenticationSuccess(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$request = $this->createMock(Request::class);
$token = $this->createMock(TokenInterface::class);
$auth = new CallbackClientAuthenticator($errorResponseFactory);
$result = $auth->onAuthenticationSuccess($request, $token, 'key');
static::assertNull($result);
}
}

View file

@ -1,156 +0,0 @@
<?php
namespace RetailCrm\ServiceBundle\Tests\Security;
use PHPUnit\Framework\TestCase;
use RetailCrm\ServiceBundle\Response\ErrorJsonResponseFactory;
use RetailCrm\ServiceBundle\Security\FrontApiClientAuthenticator;
use RetailCrm\ServiceBundle\Tests\DataFixtures\User;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserProviderInterface;
/**
* Class FrontApiClientAuthenticatorTest
*
* @package RetailCrm\ServiceBundle\Tests\Security
*/
class FrontApiClientAuthenticatorTest extends TestCase
{
public function testStart(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$errorResponseFactory
->expects(static::once())
->method('create')
->willReturn(
new JsonResponse(['message' => 'Authentication required'], Response::HTTP_UNAUTHORIZED)
);
$security = $this->createMock(Security::class);
$auth = new FrontApiClientAuthenticator($errorResponseFactory, $security);
$result = $auth->start(new Request(), new AuthenticationException());
static::assertInstanceOf(JsonResponse::class, $result);
static::assertEquals(Response::HTTP_UNAUTHORIZED, $result->getStatusCode());
}
public function testGetCredentials(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$security = $this->createMock(Security::class);
$auth = new FrontApiClientAuthenticator($errorResponseFactory, $security);
$result = $auth->getCredentials(new Request([], [FrontApiClientAuthenticator::AUTH_FIELD => '123']));
static::assertEquals('123', $result);
$result = $auth->getCredentials(new Request([FrontApiClientAuthenticator::AUTH_FIELD => '123']));
static::assertEquals('123', $result);
}
public function testCheckCredentials(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$security = $this->createMock(Security::class);
$auth = new FrontApiClientAuthenticator($errorResponseFactory, $security);
$result = $auth->checkCredentials(new Request(), new User());
static::assertTrue($result);
}
public function testOnAuthenticationFailure(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$errorResponseFactory
->expects(static::once())
->method('create')
->willReturn(
new JsonResponse(
['message' => 'An authentication exception occurred.'],
Response::HTTP_FORBIDDEN
)
);
$security = $this->createMock(Security::class);
$auth = new FrontApiClientAuthenticator($errorResponseFactory, $security);
$result = $auth->start(new Request(), new AuthenticationException());
static::assertInstanceOf(JsonResponse::class, $result);
static::assertEquals(Response::HTTP_FORBIDDEN, $result->getStatusCode());
}
public function testSupportsFalse(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$security = $this->createMock(Security::class);
$security->method('getUser')->willReturn(new User());
$auth = new FrontApiClientAuthenticator($errorResponseFactory, $security);
$result = $auth->supports(new Request());
static::assertFalse($result);
}
public function testSupportsTrue(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$security = $this->createMock(Security::class);
$security->method('getUser')->willReturn(null);
$auth = new FrontApiClientAuthenticator($errorResponseFactory, $security);
$result = $auth->supports(new Request([], [FrontApiClientAuthenticator::AUTH_FIELD => '123']));
static::assertTrue($result);
}
public function testSupportsRememberMe(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$security = $this->createMock(Security::class);
$auth = new FrontApiClientAuthenticator($errorResponseFactory, $security);
$result = $auth->supportsRememberMe();
static::assertTrue($result);
}
public function testGetUser(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$security = $this->createMock(Security::class);
$user = new User();
$auth = new FrontApiClientAuthenticator($errorResponseFactory, $security);
$userProvider = $this->createMock(UserProviderInterface::class);
$userProvider
->expects(static::once())
->method('loadUserByUsername')
->with('clientId')
->willReturn($user)
;
$result = $auth->getUser('clientId', $userProvider);
static::assertEquals($user, $result);
}
public function testOnAuthenticationSuccess(): void
{
$errorResponseFactory = $this->createMock(ErrorJsonResponseFactory::class);
$security = $this->createMock(Security::class);
$request = $this->createMock(Request::class);
$token = $this->createMock(TokenInterface::class);
$auth = new FrontApiClientAuthenticator($errorResponseFactory, $security);
$result = $auth->onAuthenticationSuccess($request, $token, 'key');
static::assertNull($result);
}
}

View file

@ -7,7 +7,7 @@ use PHPUnit\Framework\TestCase;
use RetailCrm\ServiceBundle\Serializer\JMSSerializerAdapter;
use RetailCrm\ServiceBundle\Tests\DataFixtures\RequestDto;
class JSMSerializerAdapterTest extends TestCase
class JMSSerializerAdapterTest extends TestCase
{
private $serializer;
private $transformer;

View file

@ -11,17 +11,18 @@
],
"minimum-stability": "stable",
"require": {
"php": ">=7.3",
"symfony/framework-bundle": "^4.0|^5.0",
"symfony/serializer": "^5.2",
"symfony/http-kernel": "^4.0|^5.0",
"symfony/validator": "^4.0|^5.3",
"symfony/security-guard": "^4.0|^5.0",
"symfony/console": "^5.2",
"symfony/messenger": "^5.2",
"symfony/process": "^5.2",
"symfony/event-dispatcher": "^5.2",
"symfony/lock": "^5.2"
"php": ">=8.0.2",
"symfony/framework-bundle": "^5.4|^6.0",
"symfony/serializer": "^5.4|^6.0",
"symfony/http-kernel": "^5.4|^6.0",
"symfony/validator": "^5.4|^6.0",
"symfony/security-bundle": "^6.0",
"symfony/console": "^5.4|^6.0",
"symfony/messenger": "^5.4|^6.0",
"symfony/process": "^5.4|^6.0",
"symfony/event-dispatcher": "^5.4|^6.0",
"symfony/lock": "^5.4|^6.0",
"doctrine/doctrine-bundle": "^2.6"
},
"autoload": {
"psr-4": {
@ -38,9 +39,9 @@
},
"require-dev": {
"ext-json": "*",
"phpunit/phpunit": "^8.0 || ^9.0",
"doctrine/annotations": "^1.11",
"doctrine/cache": "^1.10",
"phpunit/phpunit": "^8.5|^9.5",
"doctrine/annotations": "^1.13.1",
"doctrine/cache": "^1.11|^2.0",
"jms/serializer-bundle": "^3.8"
},
"scripts": {