PHP code example of saadsebai / enum-support

1. Go to this page and download the library: Download saadsebai/enum-support library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

saadsebai / enum-support example snippets


namespace App\Enums;

use Saad\EnumSupport\Traits\Enums\Enumerable;

enum UserRole: string
{
    use Enumerable; // Add the trait to your enum.

    case ADMIN = 'admin';
    case EDITOR = 'editor';
    case VIEWER = 'viewer';
}

UserRole::values(); // ['admin', 'editor', 'viewer']

UserRole::names(); // ['ADMIN', 'EDITOR', 'VIEWER']

UserRole::getByName('ADMIN'); // Returns UserRole::ADMIN
UserRole::getByName('invalid'); // Returns null

UserRole::getByValue('admin'); // Returns UserRole::ADMIN
UserRole::getByValue('invalid'); // Returns null

UserRole::ADMIN->translate('role'); // Returns the translation of the enum value using the giving translation file path.



use Saad\EnumSupport\Traits\Enums\Enumerable;

enum UserRole: string
{
    use Enumerable;

    case ADMIN = 'admin';
    case EDITOR = 'editor';
    case VIEWER = 'viewer';
}

it('returns all enum values', function () {
    expect(UserRole::values())->toBe(['admin', 'editor', 'viewer']);
});

it('returns all enum names', function () {
    expect(UserRole::names())->toBe(['ADMIN', 'EDITOR', 'VIEWER']);
});

it('retrieves an enum by name', function () {
    expect(UserRole::getByName('ADMIN'))->toBe(UserRole::ADMIN);
    expect(UserRole::getByName('invalid'))->toBeNull();
});

it('retrieves an enum by value', function () {
    expect(UserRole::getByValue('admin'))->toBe(UserRole::ADMIN);
    expect(UserRole::getByValue('invalid'))->toBeNull();
});
bash
php vendor/bin/pest