CakeDC / Enum

Enumeration list for CakePHP
MIT License
27 stars 17 forks source link

Constant Strategy Improvements #49

Closed rafaelqueiroz closed 3 years ago

rafaelqueiroz commented 3 years ago

Summary

Currently, the Constant Strategy don't return the Entity with Enum associated, only the field with the constant. This way, the Entity couldn't access to value of constants which can be used for display the value for final-users (on emails, subjects, templates, title, etc). The proposed solution is a implementation of beforeFind with formatResults where will be set a attribute, which is a new Entity representing the value of enum with attributes: label, prefix and value.

Example

Let's assuming we have this Table:

<?php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;

class TasksTable extends Table
{

    public const TYPE_MANAGEMENT = 'Management';
    public const TYPE_SERVER_ADMIN = 'Server Administration';
    public const TYPE_DEVELOPMENT = 'Development';
    public const TYPE_FEATURE = 'Feature';
    public const TYPE_BUG = 'Bug';

    public function initialize(array $config): void
    {
        ...
        $this->addBehavior('CakeDC/Enum.Enum', [
            'lists' => [
                'taskTypes' => [
                    'strategy' => 'const',
                    'prefix' => 'TYPE',
                    'field' => 'type',
                ],
            ],
        ]);
    }

}

So, I would to retrieve the tasks with the taskTypes enum:

$tasks = $this->Tasks->find()->contain(['TaskTypes']);

The result will be:

{
    "tasks": [
        {
            "id": "4cca79c2-1dbe-4266-94f7-263691a76cb8",
            "type": "BUG",
            "created": "2021-03-11T18:01:44+00:00",
            "modified": "2021-03-11T18:12:57+00:00",
            "task_type": {
                "label": "Bug",
                "prefix": "TYPE",
                "value": "BUG"
            }
        },
        {
            "id": "dda43d4b-d8ba-4c20-a1ab-ed02ed908650",
            "type": "SERVER_ADMIN",
            "created": "2021-03-11T18:07:32+00:00",
            "modified": "2021-03-11T18:07:32+00:00",
            "task_type": {
                "label": "Server Administration",
                "prefix": "TYPE",
                "value": "SERVER_ADMIN"
            }
        }
    ]
}