From a31cca45754536c07b0a94e31ba6fd1b3c9116d1 Mon Sep 17 00:00:00 2001 From: Jaik Dean Date: Tue, 29 Mar 2016 17:19:20 +0100 Subject: [PATCH] Add Twig extension to encode/decode Hashids --- README.md | 36 ++++++++++++++++++++++-------- Twig/HashidsExtension.php | 46 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 9 deletions(-) create mode 100644 Twig/HashidsExtension.php diff --git a/README.md b/README.md index ccd3131..2a3c4d4 100644 --- a/README.md +++ b/README.md @@ -3,17 +3,16 @@ hashidsBundle ============= -##This is a bundle to use http://www.hashids.org/ as a service +## This is a bundle to use http://www.hashids.org/ as a service ## Installation - #### Symfony 2.1.x <= 2.4.x: Composer [Composer](http://packagist.org/about-composer) is a project dependency manager for PHP. You have to list your dependencies in a `composer.json` file: -``` json +```json { "require": { "cayetanosoriano/hashids-bundle": "dev-master" @@ -22,7 +21,7 @@ your dependencies in a `composer.json` file: ``` To actually install in your project, download the composer binary and run it: -``` bash +```bash wget http://getcomposer.org/composer.phar # or curl -O http://getcomposer.org/composer.phar @@ -34,7 +33,7 @@ php composer.phar install Finally, enable the bundle in the kernel: -``` php +```php get('hashids'); ``` -### license +## Optional features + +### Twig extension + +#### Declare the service to your services.yml +```yaml +twig.hashids_extension: + class: cayetanosoriano\HashidsBundle\Twig\HashidsExtension + arguments: ["@hashids"] + public: false + tags: [{ name: twig.extension }] +``` + +#### Use the extension in your Twig templates +```twig +View Profile +``` + +### License ``` Copyright (c) 2015 neoshadybeat[at]gmail.com diff --git a/Twig/HashidsExtension.php b/Twig/HashidsExtension.php new file mode 100644 index 0000000..46f9598 --- /dev/null +++ b/Twig/HashidsExtension.php @@ -0,0 +1,46 @@ + + */ +class HashidsExtension extends \Twig_Extension +{ + /** + * @var Hashids\Hashids; + */ + private $hashids; + + public function __construct(Hashids $hashids) + { + $this->hashids = $hashids; + } + + public function getFilters() + { + return [ + new \Twig_SimpleFilter('hashid_encode', [$this, 'encode']), + new \Twig_SimpleFilter('hashid_decode', [$this, 'decode']), + ]; + } + + public function encode($number) + { + return $this->hashids->encode($number); + } + + public function decode($hash) + { + return $this->hashids->decode($hash); + } + + public function getName() + { + return 'hashids_extension'; + } +}