danilovl / sqids-bundle
Symfony bundle provides integrates sqids
Package info
github.com/danilovl/sqids-bundle
Type:symfony-bundle
pkg:composer/danilovl/sqids-bundle
Requires
- php: ^8.5
- doctrine/orm: ^3.0
- doctrine/persistence: ^3.0 || ^4.0
- sqids/sqids: ^0.5
- symfony/doctrine-bridge: ^8.0
- symfony/framework-bundle: ^8.0
- symfony/twig-bundle: ^8.0
- symfony/yaml: ^8.0
Requires (Dev)
- danilovl/phpstan-rules: ^0.0.3
- friendsofphp/php-cs-fixer: ^3.92.5
- phpstan/extension-installer: ^1.4.3
- phpstan/phpstan: ^2.1.33
- phpstan/phpstan-symfony: ^2.0.9
- phpunit/phpunit: ^12.5.6
Suggests
- ext-bcmath: Required by Sqids (or ext-gmp)
- ext-gmp: Required by Sqids (or ext-bcmath)
Provides
None
Conflicts
None
Replaces
None
README
SqidsBundle
About
Symfony bundle provides integrates Sqids, the successor of Hashids.
Requirements
- PHP 8.5 or higher
- Symfony 8.0 or higher
- Sqids 0.5 or higher
ext-gmporext-bcmath
1. Installation
Install danilovl/sqids-bundle package by Composer:
composer require danilovl/sqids-bundle
Add the SqidsBundle to your application's bundles if does not add automatically:
<?php // config/bundles.php return [ // ... Danilovl\SqidsBundle\SqidsBundle::class => ['all' => true] ];
2. Usage
Bundle configuration.
# config/packages/danilovl_sqids.yaml danilovl_sqids: # shuffle the default alphabet to get ids unique to the project alphabet: 'k3G7QAe51FCsPW92uEOyq4Bg6Sp8YzVTmnU0liwDdHXLajZrfxNhobJIRcMvKt' min_length: 10 # not set: the Sqids default list, []: no blocklist blocklist: ~ enable_param_converter: false
The alphabet must contain at least 3 unique ASCII characters and no spaces. min_length is between 0 and 255.
Sqids is not compatible with Hashids: the same number gives another id. There is no salt, a shuffled alphabet makes ids unique instead.
2.1 Canonical ids
The Sqids library decodes any string of alphabet characters, so several ids give the same numbers.
SqidsService::decode() returns the numbers only for the canonical id, the one encode() produces for them. Otherwise it returns [].
Use SqidsServiceInterface, not Sqids\Sqids, for user input.
2.2 ParamConverter
With enable_param_converter: true the bundle decodes request attributes before EntityValueResolver loads the entity.
The decoded attributes are:
- the identifier fields of the entity (
id) and the argument name ({conversation}forConversation $conversation) - the request attributes from
#[MapEntity(mapping: [...])]and#[MapEntity(id: ...)] - the name of a non-class argument (
int $id)
A value is replaced only when it is a string with a canonical id of exactly one number. An unknown id stays as is, so the entity is not found and the response is 404.
Routes.
# config/routes.yaml conversation_detail: path: /detail/{id} requirements: id: '[a-zA-Z0-9]{10,}' defaults: _controller: App\Controller\ConversationController::detail methods: [GET, POST]
In the controller the id attribute is decoded and EntityValueResolver finds Conversation by id.
<?php declare(strict_types=1); namespace App\Controller; use App\Entity\Conversation; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; class ConversationController extends AbstractController { public function detail(Conversation $conversation): Response { return $this->render('conversation/detail.html.twig', [ 'conversation' => $conversation ]); } }
Attribute for request attributes with other names. It can be placed on a method or on a class (invokable controllers).
#[SqidsRequestConverterAttribute(requestAttributesKeys: ['id_work', 'id_task'])] public function edit( Request $request, #[MapEntity(mapping: ['id_work' => 'id'])] Work $work, #[MapEntity(mapping: ['id_task' => 'id'])] Task $task ): Response { $this->denyAccessUnlessGranted(VoterSupportConstant::EDIT, $task); return $this->taskEditHandle->handle($request, $work, $task); }
2.3 Service
Inject SqidsServiceInterface.
<?php declare(strict_types=1); namespace App\Controller; use Danilovl\SqidsBundle\Interfaces\SqidsServiceInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\{ Request, Response }; class UserController extends AbstractController { public function __construct(private readonly SqidsServiceInterface $sqidsService) {} public function detail(Request $request): Response { $id = $request->query->getString('id'); $userId = $this->sqidsService->decodeOne($id); if ($userId === null) { throw $this->createNotFoundException(); } return $this->render('profile/detail.html.twig', [ 'userId' => $userId, 'id' => $this->sqidsService->encodeOne($userId) ]); } }
Methods:
encode(array $numbers): string: throwsInvalidArgumentExceptionfor a negative numberdecode(string $id): array:[]for a non-canonical idencodeOne(int $number): stringdecodeOne(string $id): ?int:nullunless the id holds exactly one number
2.4 Twig extension
Sqids encode filter accepts a number or a list of numbers.
<a target="_blank" href="{{ path('user_detail', { 'id': user.id | sqids_encode }) }}" class="btn btn-primary btn-xs"> <i class="fa fa-desktop"></i> {{ 'app.form.action.show_detail' | trans() }} </a>
Sqids decode filter returns a list of numbers.
{% set ids = id | sqids_decode %}
{% if ids | length == 1 %}
User id: {{ ids | first }}
{% endif %}
3. Development
composer tests composer phpstan composer cs-fixer-check
License
The SqidsBundle is open-sourced software licensed under the MIT license.