Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Params Codec Bundle Laravel Package

aaugustyniak/params-codec-bundle

Symfony 2/3 bundle that AES-encrypts route parameters. Adds a param_codec service and Twig helpers to generate encrypted URLs, plus a @DecryptParams annotation to automatically decrypt controller arguments using a secret passphrase.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require aaugustyniak/params-codec-bundle
    

    Add the bundle to config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 2/3):

    Aaugustyniak\ParamsCodecBundle\ParamsCodecBundle::class => ['all' => true],
    
  2. Configuration: Add a secret passphrase to config/packages/params_codec.yaml (Symfony 4+):

    params_codec:
        secret: '%env(APP_SECRET)%'  # Must match your .env
    

    For Symfony 2/3, use parameters.yml:

    params_codec:
        secret: '%secret%'
    
  3. First Use Case: Encrypt a parameter in a route and decrypt it in the controller:

    <!-- Twig template -->
    <a href="{{ path('route_name', { 'param': 'sensitive_data' }) }}">Link</a>
    

    The URL will auto-encode the parameter. Decrypt it in the controller:

    use Aaugustyniak\ParamsCodecBundle\Annotations\DecryptParams;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    
    class SecureController extends Controller
    {
        /**
         * @Route("/secure/{param}", name="route_name")
         * @DecryptParams({"param": "param"})
         */
        public function secureAction($param)
        {
            // $param is now decrypted
        }
    }
    

Implementation Patterns

Core Workflows

  1. Route Parameter Encryption:

    • Use Twig’s path() or url() functions to generate links with encrypted params:
      {{ path('user_profile', { id: user.id, token: user.token }) }}
      
    • The bundle automatically encodes params marked in route annotations (e.g., {param}).
  2. Controller Decryption:

    • Annotate route methods with @DecryptParams to auto-decrypt params:
      /**
       * @Route("/profile/{userId}/{token}", name="profile")
       * @DecryptParams({"userId": "userId", "token": "token"})
       */
      public function showProfile($userId, $token) { ... }
      
    • Map param names in the annotation to route placeholders.
  3. Custom Codecs:

    • Implement Aaugustyniak\ParamsCodecBundle\Codec\ParamCodecInterface for custom logic (e.g., Base64, custom hashing):
      class CustomCodec implements ParamCodecInterface {
          public function encode($data) { ... }
          public function decode($data) { ... }
      }
      
    • Register it as a service and tag it with param_codec.codec.
  4. Dynamic Routes:

    • For dynamic routes (e.g., API tokens), combine with Symfony’s requirements:
      # config/routes.yaml
      secure_route:
          path: /secure/{encodedParam}
          controller: App\Controller\SecureController::index
          requirements:
              encodedParam: ".+"  # Accept any encoded string
      
  5. Twig Extensions:

    • Use param_codec_encode() and param_codec_decode() in Twig for manual operations:
      {% set encoded = param_codec_encode('secret') %}
      {% set decoded = param_codec_decode(encoded) %}
      

Integration Tips

  • Validation: Validate decrypted params in the controller (e.g., check token expiry).
  • Logging: Log decrypted params for debugging (avoid logging sensitive data in production).
  • Caching: Cache encrypted URLs if params are static (e.g., pre-signed links).
  • Testing: Mock the ParamCodec service in tests:
    $this->container->set('param_codec', $this->createMock(ParamCodecInterface::class));
    

Gotchas and Tips

Pitfalls

  1. Secret Management:

    • Hardcoded Secrets: Avoid hardcoding secrets in parameters.yml. Use environment variables (e.g., .env) and Symfony’s %env().
    • Secret Rotation: Changing the secret will break all existing encrypted URLs. Plan for migration if needed.
  2. Annotation Conflicts:

    • @DecryptParams may conflict with other annotations (e.g., @ParamConverter). Ensure proper ordering in route loading.
  3. URL Length Limits:

    • AES-encrypted params are longer than plaintext. Test with your target environment (e.g., emails, SMS links).
  4. Twig Auto-escaping:

    • Encrypted params in Twig may trigger escaping. Use |raw filter if needed:
      {{ path('route', { param: 'data' })|raw }}
      
  5. Symfony 4+ Configuration:

    • The bundle expects config/packages/params_codec.yaml. If missing, create it or adjust autoloading.

Debugging

  • Decryption Failures:

    • Check for Aaugustyniak\ParamsCodecBundle\Exception\DecodeException in logs. Common causes:
      • Mismatched secrets.
      • Corrupted/malformed encoded strings.
      • Invalid param names in @DecryptParams.
  • Route Mismatches:

    • Ensure route placeholders (e.g., {param}) match the keys in @DecryptParams.
  • Service Not Found:

    • Verify the bundle is enabled and the param_codec service is registered:
      php bin/console debug:container param_codec
      

Extension Points

  1. Custom Codec Logic:

    • Extend AesCodec or implement ParamCodecInterface for non-AES encryption (e.g., RSA, Fernet).
  2. Event Listeners:

    • Subscribe to kernel.request to pre-process decryption or log events:
      // src/EventListener/CodecListener.php
      public function onKernelRequest(GetResponseEvent $event) {
          $request = $event->getRequest();
          if ($request->attributes->has('encoded_param')) {
              $decoded = $this->paramCodec->decode($request->attributes->get('encoded_param'));
              $request->attributes->set('decoded_param', $decoded);
          }
      }
      
  3. Twig Filters:

    • Create custom Twig filters for advanced encoding/decoding:
      $twig->addFilter(new \Twig_SimpleFilter('custom_encode', [$this->paramCodec, 'encode']));
      
  4. Batch Processing:

    • For bulk operations (e.g., updating URLs in a database), use the ParamCodec service directly:
      $encoder = $this->container->get('param_codec');
      $encoded = $encoder->encode($plaintext);
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed