Skip to content

Commit

Permalink
Merge pull request #1 from johnkhansrc/refactor/validation_service_in…
Browse files Browse the repository at this point in the history
…jection

Refactor/validation service injection
  • Loading branch information
johnkhansrc authored Mar 4, 2022
2 parents 5afd124 + 0c426c8 commit 9e5113e
Show file tree
Hide file tree
Showing 38 changed files with 268 additions and 107 deletions.
8 changes: 7 additions & 1 deletion src/DependencyInjection/IaphubExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,13 @@ class IaphubExtension extends Extension
public function load(array $configs, ContainerBuilder $container): void
{
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Ressources/config'));
$loader->load('services.xml');

if('test' === $container->getParameter('kernel.environment')) {
$loader->load('services_test.xml');
} else {
$loader->load('services.xml');
}


/** @var Configuration $configuration */
$configuration = $this->getConfiguration($configs, $container);
Expand Down
33 changes: 33 additions & 0 deletions src/Ressources/config/services_test.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services
https://symfony.com/schema/dic/services/services-1.0.xsd">

<services>
<!-- <defaults autowire="true" autoconfigure="true"/>-->
<!-- <prototype namespace="Johnkhansrc\" resource="../../../src/*" exclude="../../../src/{DependencyInjection,Entity,Tests,Kernel.php}"/>-->

<service id="johnkhansrc_iaphub.iaphub_http_client_validation_service" class="Johnkhansrc\IaphubBundle\Service\IaphubHttpClientValidationService" public="true"/>
<service id="johnkhansrc_iaphub.iaphub_webhook_request_validator_service" class="Johnkhansrc\IaphubBundle\Service\IaphubWebhookRequestValidatorService" public="true" />
<service id="johnkhansrc_iaphub.webhook_factory" class="Johnkhansrc\IaphubBundle\Factory\WebhookFactory" />
<service id="symfony.http_client" class="Johnkhansrc\IaphubBundle\Tests\Mocks\FakeHTTPCLient" />

<service id="johnkhansrc_iaphub.iaphub_webhook_entrypoint_controller" class="Johnkhansrc\IaphubBundle\Controller\IaphubWebhookEntrypointController" public="true">
<argument key="$webhookFactory" type="service" id="johnkhansrc_iaphub.webhook_factory" />
<argument key="$eventDispatcher" type="service" id="event_dispatcher" on-invalid="null" />
<argument key="$requestValidator" type="service" id="johnkhansrc_iaphub.iaphub_webhook_request_validator_service" />
</service>

<service id="johnkhansrc_iaphub.iaphub_http_client_service" class="Johnkhansrc\IaphubBundle\Service\IaphubHttpClientService" public="true" >
<argument key="$iaphubHttpClientValidationService" type="service" id="johnkhansrc_iaphub.iaphub_http_client_validation_service"/>
<argument key="$client" type="service" id="symfony.http_client"/>
</service>

<service id="johnkhansrc_iaphub.iaphub" class="Johnkhansrc\IaphubBundle\Iaphub" public="true" >
<argument key="$iaphubHttpClient" type="service" id="johnkhansrc_iaphub.iaphub_http_client_service"/>
</service>

<service id="Johnkhansrc\IaphubBundle\Iaphub" alias="johnkhansrc_iaphub.iaphub" public="false" />
</services>
</container>
107 changes: 11 additions & 96 deletions src/Service/IaphubHttpClientService.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;

class IaphubHttpClientService
{
Expand All @@ -33,51 +34,6 @@ class IaphubHttpClientService
public const GET_PURCHASES_URI = '/v1/app/:appId/purchases';
public const GET_SUBSCRIPTION_URI = '/v1/app/:appId/subscription/:originalPurchaseId';
public const GET_RECEIPT_URI = '/v1/app/:appId/receipt/:receiptId';

public const VALID_QUERY_PARAMETERS = [
'getUser' => [
'environment' => ['production', 'staging', 'development'],
'platform' => ['ios', 'android'],
'upsert' => []
],
'getUserMigrate' => ['environment' => ['production', 'staging', 'development']],
'getPurchase' => ['environment' => ['production', 'staging', 'development']],
'getPurchases' => [
'environment' => ['production', 'staging', 'development'],
'page' => [],
'limit' => [],
'order' => ['desc', 'asc'],
'fromDate' => [],
'toDate' => [],
'user' => [],
'userId' => [],
'originalPurchase' => [],
],
'getSubscription' => ['environment' => ['production', 'staging', 'development']],
'getReceipt' => ['environment' => ['production', 'staging', 'development']],
];
public const VALID_BODY_PARAMETERS = [
'postUser' => [
'environment' => ['production', 'staging', 'development'],
'tags' => [],
'country' => [],
'userId' => [],
'upsert' => []
],
'postUserReceipt' => [
'environment' => ['production', 'staging', 'development'],
'platform' => ['ios', 'android'],
'token' => [],
'sku' => [],
'context' => ['refresh', 'purchase', 'restore'],
'prorationMode' => [
'immediate_with_time_proration',
'immediate_and_charge_prorated_price',
'immediate_without_proration'
],
'upsert' => []
],
];
public const IAPHUB_API_DOMAIN = 'https://api.iaphub.com';
private string $apikey;
private IaphubHttpClientValidationService $iaphubHttpClientValidationService;
Expand Down Expand Up @@ -163,7 +119,7 @@ public function post(array $body)
/**
* @throws TransportExceptionInterface
*/
public function fetch()
public function fetch(): ResponseInterface
{
$this->method = 'GET';

Expand All @@ -179,7 +135,7 @@ public function fetch()
/**
* @throws TransportExceptionInterface
*/
public function fetchWithQueryParameters(array $queryParameters)
public function fetchWithQueryParameters(array $queryParameters): ResponseInterface
{
$this->method = 'GET';

Expand Down Expand Up @@ -239,7 +195,7 @@ public function getUser(string $userId, string $appId, ?array $queryParameters =
* @throws DecodingExceptionInterface
* @throws ClientExceptionInterface
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface|IaphubBundleBadQueryStringException
* @throws ServerExceptionInterface|IaphubBundleBadQueryStringException|IaphubBundleBadQueryStringValueException
*/
public function getUserMigrate(string $userId, string $appId, ?array $queryParameters = null): string
{
Expand All @@ -263,7 +219,7 @@ public function getUserMigrate(string $userId, string $appId, ?array $queryParam

/**
* @throws TransportExceptionInterface
* @throws IaphubBundleBadQueryStringException
* @throws IaphubBundleBadQueryStringException|IaphubBundleBadQueryStringValueException
*/
public function postUser(string $userId, array $payloadData, string $appId): void
{
Expand All @@ -279,7 +235,7 @@ public function postUser(string $userId, array $payloadData, string $appId): voi
* @throws ServerExceptionInterface
* @throws RedirectionExceptionInterface
* @throws DecodingExceptionInterface
* @throws ClientExceptionInterface
* @throws ClientExceptionInterface|IaphubBundleBadQueryStringValueException
*/
public function postUserReceipt(string $userId, array $payloadData, string $appId): PostUserReceiptResponse
{
Expand All @@ -298,7 +254,7 @@ public function postUserReceipt(string $userId, array $payloadData, string $appI
* @throws ClientExceptionInterface
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
* @throws IaphubBundleBadQueryStringException
* @throws IaphubBundleBadQueryStringException|IaphubBundleBadQueryStringValueException
*/
public function getPurchase(string $purchaseId, string $appId, ?array $queryParameters = null): Purchase
{
Expand All @@ -324,7 +280,7 @@ public function getPurchase(string $purchaseId, string $appId, ?array $queryPara
* @throws DecodingExceptionInterface
* @throws ClientExceptionInterface
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface|IaphubBundleBadQueryStringException
* @throws ServerExceptionInterface|IaphubBundleBadQueryStringException|IaphubBundleBadQueryStringValueException
*/
public function getPurchases(string $appId, ?array $queryParameters = null): GetPurchases
{
Expand Down Expand Up @@ -399,36 +355,13 @@ public function getReceipt(string $receiptId, string $appId, ?array $queryParame
return ReceiptFactory::build($response->toArray());
}

public function sayHelloForTest(): string
{
return "Test reussi !";
}

/**
* @throws IaphubBundleBadQueryStringException
* @throws IaphubBundleBadQueryStringValueException
*/
private function validateParameters(array $queryParameters, string $method)
private function validateParameters(array $queryParameters, string $method): void
{
foreach (array_keys($queryParameters) as $parameter) {
if (!array_key_exists($parameter, self::VALID_QUERY_PARAMETERS[$method])) {
throw new IaphubBundleBadQueryStringException(
$this->apiUri, array_keys(self::VALID_QUERY_PARAMETERS[$method]), $method);
}
if (self::VALID_QUERY_PARAMETERS[$method][$parameter]) {
$this->validateParameterValues(self::VALID_QUERY_PARAMETERS[$method][$parameter], $queryParameters[$parameter]);
}
}
}

/**
* @throws IaphubBundleBadQueryStringValueException
*/
private function validateParameterValues($acceptedParameterValues, $parameterValue): void
{
if (!in_array($parameterValue, $acceptedParameterValues, true)) {
throw new IaphubBundleBadQueryStringValueException($this->apiUri, $acceptedParameterValues, $parameterValue);
}
$this->getIaphubHttpClientValidationService()->validateParameters($queryParameters, $method, $this->apiUri);
}

/**
Expand All @@ -437,24 +370,6 @@ private function validateParameterValues($acceptedParameterValues, $parameterVal
*/
private function validateBodyParameters(array $bodyParameters, string $method): void
{
foreach (array_keys($bodyParameters) as $parameter) {
if (!array_key_exists($parameter, self::VALID_BODY_PARAMETERS[$method])) {
throw new IaphubBundleBadQueryStringException(
$this->apiUri, array_keys(self::VALID_BODY_PARAMETERS[$method]), $method);
}
if (self::VALID_QUERY_PARAMETERS[$method][$parameter]) {
$this->validateBodyParameterValues(self::VALID_BODY_PARAMETERS[$method][$parameter], $bodyParameters[$parameter]);
}
}
}

/**
* @throws IaphubBundleBadQueryStringValueException
*/
private function validateBodyParameterValues($acceptedParameterValues, $parameterValue): void
{
if (!in_array($parameterValue, $acceptedParameterValues, true)) {
throw new IaphubBundleBadQueryStringValueException($this->apiUri, $acceptedParameterValues, $parameterValue);
}
$this->getIaphubHttpClientValidationService()->validateBodyParameters($bodyParameters, $method, $this->apiUri);
}
}
22 changes: 14 additions & 8 deletions src/Service/IaphubHttpClientValidationService.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class IaphubHttpClientValidationService
],
'getSubscription' => ['environment' => ['production', 'staging', 'development']],
'getReceipt' => ['environment' => ['production', 'staging', 'development']],
'postUserReceipt' => ['appId', 'userId'],
];
public const VALID_BODY_PARAMETERS = [
'postUser' => [
Expand All @@ -52,19 +53,24 @@ class IaphubHttpClientValidationService
],
];

public static function withoutNamespace(string $method)
{
return preg_replace('/[a-zA-Z\\\]+[\:]{2}/', '', $method);
}

/**
* @throws IaphubBundleBadQueryStringException
* @throws IaphubBundleBadQueryStringValueException
*/
public function validateParameters(array $queryParameters, string $method, string $apiUri): void
{
foreach (array_keys($queryParameters) as $parameter) {
if (!array_key_exists($parameter, self::VALID_QUERY_PARAMETERS[$method])) {
if (!array_key_exists($parameter, self::VALID_QUERY_PARAMETERS[self::withoutNamespace($method)])) {
throw new IaphubBundleBadQueryStringException(
$apiUri, array_keys(self::VALID_QUERY_PARAMETERS[$method]), $method);
$apiUri, array_keys(self::VALID_QUERY_PARAMETERS[self::withoutNamespace($method)]), self::withoutNamespace($method));
}
if (self::VALID_QUERY_PARAMETERS[$method][$parameter]) {
$this->validateParameterValues(self::VALID_QUERY_PARAMETERS[$method][$parameter], $queryParameters[$parameter], $apiUri);
if (self::VALID_QUERY_PARAMETERS[self::withoutNamespace($method)][$parameter]) {
$this->validateParameterValues(self::VALID_QUERY_PARAMETERS[self::withoutNamespace($method)][$parameter], $queryParameters[$parameter], $apiUri);
}
}
}
Expand All @@ -86,12 +92,12 @@ private function validateParameterValues($acceptedParameterValues, $parameterVal
public function validateBodyParameters(array $bodyParameters, string $method, string $apiUri): void
{
foreach (array_keys($bodyParameters) as $parameter) {
if (!array_key_exists($parameter, self::VALID_BODY_PARAMETERS[$method])) {
if (!array_key_exists($parameter, self::VALID_BODY_PARAMETERS[self::withoutNamespace($method)])) {
throw new IaphubBundleBadQueryStringException(
$apiUri, array_keys(self::VALID_BODY_PARAMETERS[$method]), $method);
$apiUri, array_keys(self::VALID_BODY_PARAMETERS[self::withoutNamespace($method)]), self::withoutNamespace($method));
}
if (self::VALID_QUERY_PARAMETERS[$method][$parameter]) {
$this->validateBodyParameterValues(self::VALID_BODY_PARAMETERS[$method][$parameter], $bodyParameters[$parameter], $apiUri);
if (self::VALID_BODY_PARAMETERS[self::withoutNamespace($method)][$parameter]) {
$this->validateBodyParameterValues(self::VALID_BODY_PARAMETERS[self::withoutNamespace($method)][$parameter], $bodyParameters[$parameter], $apiUri);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion tests/Controller/IaphubWebhookEntrypointControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public function testIndex(): void
'webhook_auth_token' => 'bar',
]);

$payload = file_get_contents(__DIR__.'/../mocks/webhooksPayloads/purchaseBodyMocks.json');
$payload = file_get_contents(__DIR__ . '/../Mocks/webhooksPayloads/purchaseBodyMocks.json');
$client = new KernelBrowser($kernel);
$method = 'POST';
$uri = '/webhook_entry_point/';
Expand Down
47 changes: 47 additions & 0 deletions tests/IaphubHttpClientServiceTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

namespace Johnkhansrc\IaphubBundle\Tests;

use Johnkhansrc\IaphubBundle\Service\IaphubHttpClientService;
use Johnkhansrc\IaphubBundle\Tests\Mocks\FakeHTTPCLient;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

class IaphubHttpClientServiceTest extends TestCase
{
private JohnkhansrcIaphubTestingKernel $kernel;
private ContainerInterface $container;
private IaphubHttpClientService $httpClientService;
private HttpClientInterface $clientMock;

public function setUp(): void
{
$kernel = new JohnkhansrcIaphubTestingKernel([
'apikey' => 'foo',
'webhook_auth_token' => 'bar',
]);
$kernel->boot();
$container = $kernel->getContainer();

/** @var IaphubHttpClientService $httpClientService */
$httpClientService = $container->get('johnkhansrc_iaphub.iaphub_http_client_service');

$this->kernel = $kernel;
$this->container = $container;
$this->httpClientService = $httpClientService;
$this->clientMock = $httpClientService->getClient();

parent::setUp();
}

public function testClientIsMocked(): void
{
self::assertInstanceOf(FakeHTTPCLient::class, $this->clientMock);
}

public function testGetApikey(): void
{
self::assertEquals('foo', $this->httpClientService->getApikey());
}
}
Loading

0 comments on commit 9e5113e

Please sign in to comment.