ekvedaras/doctrine-enum

Doctrine integration for ekvedaras/php-enum

v1.0.0 2020-12-30 14:12 UTC

This package is auto-updated.

Last update: 2024-10-29 06:00:15 UTC


README

Tests Code Coverage Software License Latest Version on Packagist Total Downloads

Twitter Follow

This package integrates ekvedaras/php-enum into Doctrine by providing custom enum mapping type.

Usage

PaymentStatus.php

namespace App\Enums;

use EKvedaras\Doctrine\Enum;

class PaymentStatus extends Enum
{
    /**
     * @return static
     */
    final public static function pending(): self
    {
        return static::get('pending', 'Payment is pending');
    }

    /**
     * @return static
     */
    final public static function completed(): self
    {
        return static::get('completed', 'Payment has been processed');
    }

    /**
     * @return static
     */
    final public static function failed(): self
    {
        return static::get('failed', 'Payment has failed');
    }
}

UserStatus.php

namespace App\Enums;

use EKvedaras\Doctrine\Enum;

class UserStatus extends Enum
{
    /**
     * @return static
     */
    final public static function active(): self
    {
        return static::get(1, 'User is active');
    }

    /**
     * @return static
     */
    final public static function banned(): self
    {
        return static::get(2, 'User is banned');
    }

    /**
     * @return static
     */
    final public static function deactivated(): self
    {
        return static::get(3, 'User account is deactivated');
    }
}

Casting

Payment.php

use App\Enums\PaymentStatus;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity()
 * @ORM\Table(name="payments")
 */
class Payment
{
    // ...
   
    /**
     * @var PaymentStatus
     *
     * @ORM\Column(type=PaymentStatus::class)
     */
    protected $status;

    // ...
}

User.php

use App\Enums\UserStatus;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity()
 * @ORM\Table(name="users")
 */
class User
{
    // ...
   
    /**
     * @var UserStatus
     *
     * @ORM\Column(type="user-status")
     */
    protected $status;

    // ...
}

Registering enum:

use App\Enums\PaymentStatus;
use App\Enums\UserStatus;
use EKvedaras\DoctrineEnum\EnumType;

// As class name
EnumType::register(PaymentStatus::class);
EnumType::register('user-status', UserStatus::class);

// Or multiple at once
EnumType::register([
    PaymentStatus::class,
    'user-status' => UserStatus::class,
]);