1. Go to this page and download the library: Download brysem/phpenums 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/ */
brysem / phpenums example snippets
// Assume that this model will now give us access to the property "status"
// which has been set to an instance of the UserStatus enum class.
$user = new Models\User([
'status' => new UserStatus(UserStatus::ACTIVE)
]);
echo("Hello, your account is currently ". $user->status ."."); // __toString() -> Hello, your account is currently Active.
// Get all values.
UserStatus::all(); // [1 => 'Pending', 2 => 'Active', 3 => 'Banned']
// Get all keys from the enum.
UserStatus::keys(); // [1, 2, 3]
$userStatus = new UserStatus(UserStatus::ACTIVE);
$userStatus->values(); // [1 => 'Pending', 2 => 'Active', 3 => 'Banned']
// Cast to a string.
(string) $user->status; // Active
// Perform checks
$user->status->is(UserStatus::ACTIVE); // true
$user->status->is([UserStatus::ACTIVE, UserStatus::PENDING]); // true (checkes whether the status is active or pending.)
$user->status->has(UserStatus::PENDING); // true
$user->status->has(1337); // false
// Set and get the value.
$user->status->value(); // 2
$user->status->set(UserStatus::ACTIVE); // Active
$user->status->get(UserStatus::ACTIVE); // Active
// Safegaurding against invalid values
try {
$user->status->set(1337);
$user->status->set('undefined');
} catch (UndefinedEnumValueException $e) {
//
} catch (InvalidArgumentException $e) {
//
}
ryse\Enums\Enum;
class UserStatus extends Enum
{
const PENDING = 1;
const ACTIVE = 2;
const BANNED = 3;
/**
* Returns all possible key value pairs for the enum.
*
* @return array
*/
public function values()
{
return [
self::PENDING => 'Pending',
self::ACTIVE => 'Active',
self::BANNED => 'Banned',
];
}
}
namespace App\Models;
use App\Models\Enums\UserType;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
public function getTypeAttribute()
{
return new UserType($this->attributes['type']);
}
public function setTypeAttribute($value)
{
$this->attributes['type'] = (new UserType($value))->value();
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.