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

Doctrine Encrypted Contracts Laravel Package

aeliot/doctrine-encrypted-contracts

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require aeliot/doctrine-encrypted-contracts
    

    Ensure your project uses Doctrine ORM (v2.10+) and PHP 8.1+.

  2. First Use Case Extend the Aeliot\DoctrineEncryptedContracts\EncryptedType abstract class to create a custom encrypted field type:

    use Aeliot\DoctrineEncryptedContracts\EncryptedType;
    use Doctrine\DBAL\Platforms\AbstractPlatform;
    
    class CustomEncryptedStringType extends EncryptedType
    {
        public function getName(): string
        {
            return 'custom_encrypted_string';
        }
    
        public function getSQLDeclaration(
            array $column,
            AbstractPlatform $platform
        ): string {
            return $platform->getStringTypeDeclarationSQL($column);
        }
    }
    
  3. Register the Type Add your type to Doctrine’s configuration (e.g., in config/packages/doctrine.yaml):

    doctrine:
        orm:
            mappings:
                App:
                    type: attribute
                    dir: "%kernel.project_dir%/src/Entity"
                    prefix: "App\Entity"
                    is_bundle: false
            dbal:
                types:
                    custom_encrypted_string: App\Doctrine\DBAL\Type\CustomEncryptedStringType
    
  4. Annotate an Entity Field

    use Doctrine\ORM\Mapping as ORM;
    use Aeliot\DoctrineEncryptedContracts\Attributes as Encrypted;
    
    #[ORM\Entity]
    class User
    {
        #[ORM\Column(type: 'custom_encrypted_string')]
        #[Encrypted\Encrypted]
        private string $sensitiveData;
    }
    

Implementation Patterns

Workflows

  1. Encrypted Field Creation

    • Extend EncryptedType for custom logic (e.g., key derivation, cipher selection).
    • Override convertToDatabaseValue() and convertToPHPValue() for serialization/deserialization.
  2. Integration with doctrine-encrypted-bundle

    • Use EncryptedField trait in entities to auto-apply encryption:
      use Aeliot\DoctrineEncryptedContracts\Traits\EncryptedField;
      
      #[ORM\Entity]
      class User
      {
          use EncryptedField;
      
          #[ORM\Column(type: 'string')]
          #[Encrypted\Encrypted]
          private string $password;
      }
      
  3. Query Filtering

    • Leverage EncryptedType::getComparisonExpression() to build encrypted queries:
      $qb = $entityManager->createQueryBuilder();
      $qb->andWhere('u.sensitiveData = :value')
         ->setParameter('value', $encryptedValue);
      
  4. Bulk Operations

    • Use EntityManager::createNativeQuery() with raw SQL for bulk inserts/updates of encrypted fields.

Integration Tips

  • Key Management: Store encryption keys in environment variables or a dedicated service (e.g., AWS KMS).
  • Performance: Cache decrypted values in entity hydrators if frequently accessed.
  • Migrations: Use Doctrine Migrations to add encrypted columns without downtime:
    php bin/console make:migration
    php bin/console doctrine:migrations:migrate
    

Gotchas and Tips

Pitfalls

  1. Key Rotation

    • Encrypted data cannot be re-encrypted with a new key without re-inserting. Plan for key rotation strategies (e.g., dual-key periods).
  2. Indexing Limitations

    • Encrypted fields cannot be indexed in most databases. Use application-layer filtering or partial decryption for searches.
  3. Type Safety

    • Ensure getSQLDeclaration() returns a compatible DBAL type (e.g., VARCHAR for strings). Mismatches cause ClassNotFoundException.
  4. Serialization Conflicts

    • Avoid circular references in encrypted entities. Use __serialize()/__unserialize() or @ORM\Transient for non-persistent properties.

Debugging

  • Query Logs: Enable Doctrine debug mode to inspect generated SQL:
    doctrine:
        dbal:
            logging: true
    
  • Value Dumping: Override convertToPHPValue() to log decrypted values for debugging:
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        error_log("Decrypted: " . print_r($value, true));
        return parent::convertToPHPValue($value, $platform);
    }
    

Extension Points

  1. Custom Ciphers

    • Implement Aeliot\DoctrineEncryptedContracts\Contracts\CipherInterface for non-standard encryption (e.g., RSA-OAEP):
      class RsaCipher implements CipherInterface
      {
          public function encrypt(string $data, string $key): string { ... }
          public function decrypt(string $data, string $key): string { ... }
      }
      
  2. Field-Level Config

    • Use attributes to customize encryption per field:
      #[Encrypted\Encrypted(
          cipher: 'AesCbc',
          key: 'custom_key_123',
          algorithm: 'aes-256-cbc'
      )]
      private string $customField;
      
  3. Event Listeners

    • Attach listeners to prePersist/preUpdate for dynamic key resolution:
      $entityManager->getEventManager()->addEventListener(
          [User::class],
          new EncryptedFieldListener($keyProvider)
      );
      
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.
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
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope