On Sat, Dec 5, 2020, at 1:21 PM, Marc Bennewitz wrote:
> > * I often use metadata in enumerations and so I would be very
> > interested to allow constants.
>
>
> Could you give an example what you mean? Metadata on individual cases is
> supported by methods, which map more cleanly to things like interfaces,
> and the notion of each case as a singleton object, not a static class.
>
>
> That said, I have a related question: can enum cases be used as the
> *value* of constants? e.g.:
>
> class OldMaid {
> public const SUIT = Suit::Spades;
> public const VALUE = CardValue::Queen;
> }
At present, no. They're "just" objects, and you can't assign an object to a
constant. Unfortunately I'm not sure how to enable that without making them
not-objects, which introduces all sorts of other complexity.
> I mean on mapping something to something else defined as a single assoc
> array constant.
> Something like:
>
> enum Role {
> case User,
> case Admin,
> ...
> }
>
> enum Action {
> case Order_Edit,
> case Order_Read,
>
> private const BY_ROLE = [
> Role::User => [self::Order_Read],
> Role::Admin => [self::Order_Read, self::Order_Edit],
> ];
>
> public function isAllowed(User $user) {
> return in_array($this, self::BY_ROLE[$user->role]);
> }
> }
Because of their object-ness, I think you'd have to use a weak map defined at
runtime:
class AccessControl {
private WeakMap $perms;
public function __construct() {
$this->perms = new WeakMap();
$this->perms[Role::User] = [Action::Order_Read, Action::Order_Edit];
$this->perms[Role::Admin] = [Action::Order_Read, Action::Order_Edit];
}
public function isAllowed($user, $action): bool {
return in_array($action, $this->perms[$user->role]);
}
}
--Larry Garfield
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php