我想用Ben Sampo Package元来做腊肠. 此包有一个名为‘Description’的属性作为新属性. 但是我不能向我的枚举添加额外的属性(属性).

我想要有一个具有‘isfinal’属性的枚举‘Status’.来确定这个密钥是不是最终密钥?

我真的需要为一些枚举添加一些属性. 有什么办法吗?

我也查了this package张.添加额外的属性非常好,而且非常容易.但我也需要本地化,而默认情况下它没有.

编辑: 我需要的枚举是这样的:

final class Status extends Enum
{
#[Color('red')]
#[Description('Initial status')]
#[IsFinal(false)]    
const Initial = 1;

#[Color('blue')]
#[Description('suspended status')]
#[IsFinal(false)] 
const Pending = 2;

#[Color('white')]
#[Description('completed status')]
#[IsFinal(true)] 
const Completed = 3;

#[Color('red')]
#[Description('canceled status')]
#[IsFinal(true)] 
const Canceled = 4;
 }

然后,我想要检索 colored颜色 值,或者是如下所示的最终值:

Status::getColor(1);

 

Status::Initial->getColor();

$enum->getColor();

更新:我现在有这个trait 了:

   <?php
namespace App\Enums\Concerns;

use BenSampo\Enum\Attributes\Description;
use Exception;

/**
 * Get Enum attributes
 */
trait GetEnumAttributes
{
    public $color;
    public $isFinal;

    public function __construct(mixed $enumValue)
    {
        $this->color = $this->getCustomAttribute($enumValue, 'color');
        $this->isFinal = $this->getCustomAttribute($enumValue, 'is_final');
        $this->description = self::getDescription($enumValue);
        parent::__construct($enumValue);
    }

    protected static function getCustomAttribute(mixed $value, $key)
    {
        $reflection = self::getReflection();
        $constantName = static::getKey($value);
        $constReflection = $reflection->getReflectionConstant($constantName);
        if ($constReflection === false) {
            return null;
        }

        switch ($key) {
            case 'color':
              //  dd( $constReflection->getAttributes(Color::class));
                $customAttributes = $constReflection->getAttributes(Color::class);
                break;
            case 'is_final':
                $customAttributes = $constReflection->getAttributes(IsFinal::class);
                break;
            case 'description':
                    $customAttributes = $constReflection->getAttributes(Description::class);
                    break;
            default:
                $customAttributes = [];
                break;
        }

        return match (count($customAttributes)) {
            0 => null,
            1 => $customAttributes[0]->newInstance()->$key,
            default => throw new Exception('You cannot use more than 1 custom attribute on ' . class_basename(static::class) . '::' . $constantName),
        };
    }
    public static function getCustomInstances()
    {
        return array_map(
            function ($constantValue) {
                $newStatic = new static($constantValue);
                $newStatic = (array) $newStatic;
                $newStatic['description'] = self::getCustomAttribute($constantValue,'description');//getDescription($constantValue);
                $newStatic['color'] = self::getCustomAttribute($constantValue,'color');
                $newStatic['isFinal'] = self::getCustomAttribute($constantValue,'is_final');
                $newStatic = (object) $newStatic;
                return $newStatic;
            },
            static::getConstants(),
        );
    }  

}

当我使用以下命令时会发生这种情况:

dd(Status::getInstances());

结果:

array:4 [▼ // app\Http\Controllers\testController.php:19
  "Initial" => App\Enums\Status {#416 ▼
    +value: 1
    +key: "Initial"
    +description: "initial status"
    +color: null
    +isFinal: null
  }
  "Pending" => App\Enums\Status {#418 ▼
    +value: 2
    +key: "Pending"
    +description: "suspended status"
    +color: null
    +isFinal: null
  }
  "Completed" => App\Enums\Status {#421 ▶}
  "Canceled" => App\Enums\Status {#422 ▶}
]

我在‘getCustomAttribute’中判断了这个问题,以防万一:

case 'color':
                dd( $constReflection->getAttributes(Color::class));
                $customAttributes = $constReflection->getAttributes(Color::class);
                break;

返回NULL,但是$stRefltion具有正确的所有属性. 同样的情况发生在我使用

Status::getCustomInstances();

推荐答案

对于BenSampo包,您可以按照如下方式操作:
创造一种trait :

<?php

namespace App\Traits;

/**
 * Get Enum Description
 */
trait GetEnumDescription
{
    private static $thisClass;

    public static function getCustomEnumDescription($enumValue = 0)
    {
        return __(self::getEnumDescription(intval($enumValue)));
    }

    private static function getEnumDescription($enumValue = 0)
    {
        self::$thisClass = static::class;
        $key = self::$thisClass::getKey($enumValue);
        return ucwords(str_replace('_', ' ', $key));
    }

    public static function getCustomInstances()
    {
        return array_map(
            function ($constantValue) {
                $newStatic = new static($constantValue);
                $newStatic = (array) $newStatic;
                $newStatic['custom_description'] = self::getCustomEnumDescription($constantValue);
                $newStatic = (object) $newStatic;
                return $newStatic;
            },
            static::getConstants(),
        );
    }
}

创建一个Enum(我通常使用带蛇形大小写的数字和变量名创建枚举值.您可以根据自己的需要定制方法):

<?php

declare(strict_types=1);

namespace App\Enums;

use App\Traits\GetEnumDescription;
use BenSampo\Enum\Enum;

/**
 * Menu item types
 */
final class MenuItemType extends Enum
{
    use GetEnumDescription;

    const both = 0;
    const only_customer = 1;
    const only_vendor = 2;
    const closed = 3;
}

确保使用GetEnumDescription个特征.示例实例:

// app()->setLocale('tr');
// dd(MenuItemType::getCustomInstances());
// RESULT:
array:4 [▼
  "both" => {#1156 ▼
    +"value": 0
    +"key": "both"
    +"description": "Both"
    +"custom_description": "Her ikisi de"
  }
  "only_customer" => {#1157 ▼
    +"value": 1
    +"key": "only_customer"
    +"description": "Only customer"
    +"custom_description": "Sadece müşteri"
  }
  "only_vendor" => {#1159 ▼
    +"value": 2
    +"key": "only_vendor"
    +"description": "Only vendor"
    +"custom_description": "Sadece bayi"
  }
  "closed" => {#1158 ▼
    +"value": 3
    +"key": "closed"
    +"description": "Closed"
    +"custom_description": "Closed"
  }
]

示例:

public static function getCustomInstances()
{
    return array_map(
        function ($constantValue) {
            $newStatic = new static($constantValue);
            $newStatic = (array) $newStatic;
            $newStatic['custom_description'] = self::getCustomEnumDescription($constantValue);
            $newStatic['color'] = 'red';
            $newStatic['is_final'] = true;
            $newStatic = (object) $newStatic;
            return $newStatic;
        },
        static::getConstants(),
    );
}

结果:

// after attributes added: dd(MenuItemType::getCustomInstances());
array:4 [▼
  "both" => {#1156 ▼
    +"value": 0
    +"key": "both"
    +"description": "Both"
    +"custom_description": "Her ikisi de"
    +"color": "red"
    +"is_final": true
  }
  "only_customer" => {#1157 ▼
    +"value": 1
    +"key": "only_customer"
    +"description": "Only customer"
    +"custom_description": "Sadece müşteri"
    +"color": "red"
    +"is_final": true
  }
  "only_vendor" => {#1158 ▼
    +"value": 2
    +"key": "only_vendor"
    +"description": "Only vendor"
    +"custom_description": "Sadece bayi"
    +"color": "red"
    +"is_final": true
  }
  "closed" => {#1159 ▼
    +"value": 3
    +"key": "closed"
    +"description": "Closed"
    +"custom_description": "Kapalı"
    +"color": "red"
    +"is_final": true
  }
]

Create two attributes to make it in the structure you want:
Color个属性:

<?php

declare(strict_types=1);

namespace App\Attributes;

use Attribute;

#[Attribute(Attribute::TARGET_CLASS_CONSTANT | Attribute::TARGET_CLASS)]
class Color
{
    public function __construct(
        public string $color,
    ) {
    }
}

IsFinal个属性:

<?php

declare(strict_types=1);

namespace App\Attributes;

use Attribute;

#[Attribute(Attribute::TARGET_CLASS_CONSTANT | Attribute::TARGET_CLASS)]
class IsFinal
{
    public function __construct(
        public bool $is_final,
    ) {
    }
}

下面是我实例化您的枚举的方式:

<?php

declare(strict_types=1);

namespace App\Enums;

use App\Attributes\Color;
use App\Attributes\IsFinal;
use BenSampo\Enum\Attributes\Description;
use BenSampo\Enum\Enum;
use Exception;

/**
 * Menu item types
 */
final class MenuItemType extends Enum
{
    public $color;
    public $isFinal;

    public function __construct(mixed $enumValue)
    {
        $this->color = $this->getCustomAttribute($enumValue, 'color');
        $this->isFinal = $this->getCustomAttribute($enumValue, 'is_final');
        parent::__construct($enumValue);
    }

    protected static function getCustomAttribute(mixed $value, $key)
    {
        $reflection = self::getReflection();
        $constantName = static::getKey($value);
        $constReflection = $reflection->getReflectionConstant($constantName);
        if ($constReflection === false) {
            return null;
        }

        switch ($key) {
            case 'color':
                $customAttributes = $constReflection->getAttributes(Color::class);
                break;
            case 'is_final':
                $customAttributes = $constReflection->getAttributes(IsFinal::class);
                break;
            default:
                break;
        }

        return match (count($customAttributes)) {
            0 => null,
            1 => $customAttributes[0]->newInstance()->$key,
            default => throw new Exception('You cannot use more than 1 custom attribute on ' . class_basename(static::class) . '::' . $constantName),
        };
    }

    const both = 0;
    const only_customer = 1;

    #[Color('blue')]
    #[Description('test')]
    #[IsFinal(true)]
    const only_vendor = 2;

    #[Color('red')]
    #[IsFinal(false)]
    const closed = 3;
}

当我使用以下命令打印屏幕时,按结果的dd(MenuItemType::getInstances());来执行此操作:

array:4 [▼ // app\Providers\AppServiceProvider.php:24
  "both" => App\Enums\MenuItemType {#1156 ▼
    +value: 0
    +key: "both"
    +description: "Both"
    +color: null
    +isFinal: null
  }
  "only_customer" => App\Enums\MenuItemType {#1157 ▼
    +value: 1
    +key: "only_customer"
    +description: "Only customer"
    +color: null
    +isFinal: null
  }
  "only_vendor" => App\Enums\MenuItemType {#1158 ▼
    +value: 2
    +key: "only_vendor"
    +description: "test"
    +color: "blue"
    +isFinal: true
  }
  "closed" => App\Enums\MenuItemType {#1160 ▼
    +value: 3
    +key: "closed"
    +description: "Closed"
    +color: "red"
    +isFinal: false
  }
]

享受你的工作吧.

Php相关问答推荐

将一个数字分配到一系列因素中(就像贪婪算法)

按制造商、型号和年份范围判断数据的存在性

如果再次调用SESSION_START(),会话.gc-max是否会重新启动?或者它是从第一次创建会话开始计算的?

LaravelEloquent 的地方条件父/子与第三模型多对多

如何在不指定symfony列的情况下从数据库中获取行数组

在WooCommerce中添加基于类别的固定费用

如何在Foreach语句中使用php和li按降序排序?

列出所有WooCommerce处理订单中的产品数量,SKU和品牌

如何在WordPress REST API中判断应用程序密码

WooCommerce在收据页面获取产品下载URL

Woocommerce单一产品Ajax添加到带有自定义购物车项目数据的购物车

根据WooCommerce的定制订单状态增加产品库存

对产品/库存结果集进行分组和计数,形成多维分层数组

在 php 中生成 MAC ISO/IEC 9797-1

在 WooCommerce 管理变量产品中启用其他变体图像

通过存储库检索 Blade 上的单值数据 出错

php如何删除括号内的百分比值

为什么 8.0 之前的 PHP 版本拒绝命名空间Random\Namespace作为无效语法?

Laravel Docker 几个数据库

升级到 PHP 8.2:ksort 和 krsort 更改