Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

change restrictions to allow PHP8 resolve#issue-22 #23

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 13 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
# [![PGS Software](https://www.pgs-soft.com/pgssoft-logo.png)](https://www.pgs-soft.com) / HashId

![PHP from Packagist](https://img.shields.io/packagist/php-v/symfony/symfony.svg)
[![Build Status](https://travis-ci.org/kjonski/HashId.svg?branch=dev-master)](https://travis-ci.org/kjonski/HashId)
[![Code Coverage](https://scrutinizer-ci.com/g/kjonski/HashId/badges/coverage.png?b=dev-master)](https://scrutinizer-ci.com/g/kjonski/HashId/?branch=dev-master)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/kjonski/HashId/badges/quality-score.png?b=dev-master)](https://scrutinizer-ci.com/g/kjonski/HashId/?branch=dev-master)

Symfony 4 bundle for encoding integer route parameters and decoding request parameters with <http://www.hashids.org/>
[![Build Status](https://travis-ci.org/PGSSoft/HashId.svg?branch=2.0)](https://travis-ci.org/PGSSoft/HashId)
[![Code Coverage](https://scrutinizer-ci.com/g/PGSSoft/HashId/badges/coverage.png?b=2.0)](https://scrutinizer-ci.com/g/PGSSoft/HashId/?branch=2.0)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/PGSSoft/HashId/badges/quality-score.png?b=2.0)](https://scrutinizer-ci.com/g/PGSSoft/HashId/?branch=2.0)

Symfony bundle for encoding integer route parameters and decoding request parameters with <http://www.hashids.org/>
***
Please use this version with Symfony &ge;4.4 and <5.0
***
Replace predictable integer url parameters in easy way:
* `/hash-id/demo/decode/216/30` => `/hash-id/demo/decode/X46dBNxd79/30`
* `/order/315` => `/order/4w9aA11avM`
Expand All @@ -24,9 +27,11 @@ composer require pgs-soft/hashid-bundle
# config/packages/pgs_hash_id.yaml

pgs_hash_id:
salt: 'my super salt'
min_hash_length: 20
alphabet: 'qwertyasdzxc098765-'
converter:
hashids:
salt: 'my super salt'
min_hash_length: 20
alphabet: 'qwertyasdzxc098765-'
```

## Controller configuration
Expand Down
6 changes: 3 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
}
],
"require": {
"php": "^7.1.3",
"php": ">=7.1.3",
"symfony/dependency-injection": "^4.1.12|^5.0",
"symfony/config": "~4.4|~5.0",
"doctrine/annotations": "^1.6",
Expand All @@ -29,14 +29,14 @@
"minimum-stability": "stable",
"extra": {
"branch-alias": {
"dev-master": "master"
"dev-master": "2.0-dev"
}
},
"require-dev": {
"phpstan/phpstan": "^0.12",
"sebastian/phpcpd": "^4.0",
"squizlabs/php_codesniffer": "^3.2",
"symfony/http-kernel": "^4.4|^5.0",
"symfony/http-kernel": "^4.4.13|^5.1.5",
"sensio/framework-extra-bundle": "^5.1",
"friendsofphp/php-cs-fixer": "^2.10",
"phpunit/phpunit": "^7.0",
Expand Down
23 changes: 23 additions & 0 deletions src/Controller/DemoController.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,29 @@ public function decodeMore(Request $request, int $id, int $other): Response
return new Response($this->getDecodeResponse($request, $id, $other));
}

/**
* @Hash("id")
*
* @param int $id
*/
public function encodeLocalized($id): Response
{
$url1 = $this->generateUrl('pgs_hash_id_demo_encode_localized', ['id' => $id, '_locale' => 'pl']);
$url2 = $this->generateUrl('pgs_hash_id_demo_encode_localized', ['id' => $id]);

$response = <<<EOT
<html>
<body>
Provided id: $id<br />
Localized url with encoded parameter and locale provided: <a href="$url1">$url1</a><br />
Localized url with encoded parameter: <a href="$url2">$url2</a><br />
</body>
</html>
EOT;

return new Response($response);
}

private function getDecodeResponse(Request $request, int $id, int $other): string
{
$providedId = $this->getRouteParam($request, 'id');
Expand Down
28 changes: 19 additions & 9 deletions src/Decorator/RouterDecorator.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,29 @@ public function getRouter(): RouterInterface
return $this->object;
}

/**
* @param string $name
* @param array $parameters
* @param int $referenceType
*/
public function generate($name, $parameters = [], $referenceType = RouterInterface::ABSOLUTE_PATH): string
{
$route = $this->getRouter()->getRouteCollection()->get($name);
$this->processParameters($route, $parameters);
public function generate(
$name,
$parameters = [],
$referenceType = RouterInterface::ABSOLUTE_PATH
): string {
$this->processParameters($this->getRoute($name, $parameters), $parameters);

return $this->getRouter()->generate($name, $parameters, $referenceType);
}

private function getRoute(string $name, array $parameters): ?Route
{
$routeCollection = $this->getRouter()->getRouteCollection();
$route = $routeCollection->get($name);

if (null === $route) {
$locale = $parameters['_locale'] ?? $this->getRouter()->getContext()->getParameter('_locale');
$route = $routeCollection->get(sprintf('%s.%s', $name, $locale));
}

return $route;
}

private function processParameters(?Route $route, array &$parameters): void
{
if (null !== $route) {
Expand Down
6 changes: 6 additions & 0 deletions src/Resources/routes.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,9 @@ pgs_hash_id_demo_decode:
pgs_hash_id_demo_decode_more:
path: /hash-id/demo/decode_more/{id}/{other}
controller: Pgs\HashIdBundle\Controller\DemoController::decodeMore

pgs_hash_id_demo_encode_localized:
path:
en: /hash-id/demo/encode-en/{id}
pl: /hash-id/demo/encode-pl/{id}
controller: Pgs\HashIdBundle\Controller\DemoController::encodeLocalized
12 changes: 11 additions & 1 deletion src/Service/DecodeControllerParameters.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,19 @@ public function __construct(DecodeParametersProcessorFactory $parametersProcesso
public function decodeControllerParameters(ControllerEvent $event): void
{
$controller = $event->getController();
if (\is_array($controller)) {
list($controllerObject, $method) = $controller;
} elseif (\is_object($controller) && !$controller instanceof \Closure) {
$controllerObject = $controller;
$method = '__invoke';
} else {
//Controller is a closure
return;
}

$parametersProcessor = $this
->getParametersProcessorFactory()
->createControllerDecodeParametersProcessor(...$controller);
->createControllerDecodeParametersProcessor($controllerObject, $method);

$this->processRequestParameters($event, $parametersProcessor);
$this->processRequestParametersWithParamConverter($event);
Expand Down
13 changes: 10 additions & 3 deletions tests/Controller/ControllerMockProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,20 @@
namespace Pgs\HashIdBundle\Tests\Controller;

use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class ControllerMockProvider extends TestCase
{
public function getTestControllerMock(): Controller
public function getTestControllerMock(): AbstractController
{
return $this->getMockBuilder(Controller::class)
return $this->getMockBuilder(AbstractController::class)
->getMockForAbstractClass();
}

public function getTestControllerObjectMock(): AbstractController
{
return $this->getMockBuilder(AbstractController::class)
->setMethods(['__invoke'])
->getMockForAbstractClass();
}
}
18 changes: 16 additions & 2 deletions tests/Decorator/RouterDecoratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,29 @@ public function testGenerateUrl(): void
$id = 10;
$other = 20;
$alphabet = self::$container->getParameter('pgs_hash_id.converter.hashids.alphabet');
$hashLength = self::$container->getParameter('pgs_hash_id.converter.hashids.min_hash_length');

$routeArgs = ['pgs_hash_id_demo_decode', ['id' => $id, 'other' => $other]];
$generatedPath = $this->router->generate(...$routeArgs);
$this->assertNotSame(sprintf('/hash-id/demo/decode/%d/%d', $id, $other), $generatedPath);
$pattern = sprintf('/\/hash-id\/demo\/decode\/[%s]+\/\d+/', $alphabet);
$pattern = sprintf('/\/hash-id\/demo\/decode\/[%s]{%d}\/\d+/', $alphabet, $hashLength);
$this->assertRegExp($pattern, $generatedPath);

$routeArgs = ['pgs_hash_id_demo_encode_localized', ['id' => $id, '_locale' => 'pl']];
$generatedPath = $this->router->generate(...$routeArgs);
$this->assertNotSame(sprintf('/hash-id/demo/encode-pl/%d', $id), $generatedPath);
$pattern = sprintf('/\/hash-id\/demo\/encode-pl\/[%s]{%d}/', $alphabet, $hashLength);
$this->assertRegExp($pattern, $generatedPath);

$routeArgs = ['pgs_hash_id_demo_decode_more', ['id' => $id, 'other' => $other]];
$generatedPath = $this->router->generate(...$routeArgs);
$pattern = sprintf('/\/hash-id\/demo\/decode_more\/[%s]+\/[%s]+/', $alphabet, $alphabet);
$pattern = sprintf(
'/\/hash-id\/demo\/decode_more\/[%s]{%d}\/[%s]{%d}/',
$alphabet,
$hashLength,
$alphabet,
$hashLength
);
$this->assertRegExp($pattern, $generatedPath);
}
}
50 changes: 35 additions & 15 deletions tests/Service/DecodeControllerParametersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,25 @@ class DecodeControllerParametersTest extends TestCase

protected function setUp()
{
$this->controllerMockProvider = new ControllerMockProvider();
$this->parametersProcessorMockProvider = new ParametersProcessorMockProvider();
}

public function getControllerMockProvider(): ControllerMockProvider
{
return $this->controllerMockProvider;
return $this->controllerMockProvider ?? new ControllerMockProvider();
}

public function getParametersProcessorMockProvider(): ParametersProcessorMockProvider
{
return $this->parametersProcessorMockProvider;
}

public function testDecodeControllerParameters(): void
/**
* @dataProvider decodeControllerParametersDataProvider
*
* @param mixed $controller
*/
public function testDecodeControllerParameters($controller): void
{
$decodeParametersProcessorFactory = $this->getDecodeParametersProcessorFactoryMock();
$decodeControllerParameters = new DecodeControllerParameters($decodeParametersProcessorFactory);
Expand All @@ -50,27 +54,43 @@ public function testDecodeControllerParameters(): void
'id' => 10,
'name' => 'test',
],
]
],
$controller
);
$decodeControllerParameters->decodeControllerParameters($event);
$this->assertSame(10, $event->getRequest()->attributes->all()['id']);
}

public function testDecodeControllerParametersWithParamConverter(): void
public function decodeControllerParametersDataProvider()
{
return [
['controller as array' => $this->getControllerMockProvider()->getTestControllerMock(), 'demo'],
];
}

/**
* @dataProvider decodeControllerParametersDataProvider
*
* @param $controller
*/
public function testDecodeControllerParametersWithParamConverter($controller): void
{
$decodeParametersProcessorFactory = $this->getDecodeParametersProcessorFactoryMock();
$decodeControllerParameters = new DecodeControllerParameters($decodeParametersProcessorFactory);
$decodeControllerParameters->setParamConverterListener($this->getDoctrineParamConverterListenerMock());
$event = $this->getEventMock([
[
'id' => 'encoded',
'name' => 'test',
],
$event = $this->getEventMock(
[
'id' => 10,
'name' => 'test',
[
'id' => 'encoded',
'name' => 'test',
],
[
'id' => 10,
'name' => 'test',
],
],
]);
$controller
);
$decodeControllerParameters->decodeControllerParameters($event);
$this->assertSame(10, $event->getRequest()->attributes->all()['id']);
}
Expand Down Expand Up @@ -102,15 +122,15 @@ protected function getDecodeParametersProcessorMock(): Decode
/**
* @return ControllerEvent|MockObject
*/
protected function getEventMock(array $requestConsecutiveCalls): ControllerEvent
protected function getEventMock(array $requestConsecutiveCalls, $controller): ControllerEvent
{
$mock = $this->getMockBuilder(ControllerEvent::class)
->disableOriginalConstructor()
->setMethods(['getController', 'getRequest'])
->getMock();

$mock->method('getController')
->willReturn([$this->getControllerMockProvider()->getTestControllerMock(), 'demo']);
->willReturn($controller);

$mock->method('getRequest')
->willReturn($this->getRequestMock($requestConsecutiveCalls));
Expand Down