Score:0

Recommended way to use StringTranslationTrait in PHP8 enums

ru flag

PHP8 has that new cool "enum" feature that should replace all class constants and would make coding easier and safer. One problem I encoutered is that many common Drupal traits (foremost the translation trait) have properties and therefore can not be used in enums.

So what I would like to do is

<?php

use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslatableMarkup;

enum Season: string {

  // Can't use this because that trait has a property 
  // and enums can only use traits without properties.
  use StringTranslationTrait;

  case SUMMER = 'summer';
  case WINTER = 'winter';

  public function getLabel(): TranslatableMarkup {
    return match ($this) {
      Season::SUMMER => $this->t('summer'), // can't use OOP here :(
      Season::WINTER => $this->t('winter'),
    };
  }
}

I know that I can still use old-school procedural code

    return match ($this) {
      Season::SUMMER => t('summer'), // that's what we did 20 years ago
      Season::WINTER => t('winter'),
    };

but is there a "more beautiful" way? I'm on a D10/PHP8 project , procedural code is dicouraged, but traits with properties are very common in the Drupal ecosystem. Especially getting a translatable label of a constant is a very common use-case.

What is the recommended way of using/injecting Drupal traits (especially the StringTranslationTrait) into enums?

apaderno avatar
us flag
Instead of calling `t()`, create the `TranslatableMarkup` instance as `t()` does. Since enumerations cannot have properties, that is the only way I think possible.
id flag
You didn't use `match` in PHP twenty years ago...
Score:1
de flag

Following up on apaderno's comment, rather than using the Drupal API to create a TranslatableMarkup instance, you can instantiate the class yourself.

use Drupal\Core\StringTranslation\TranslatableMarkup;

enum Season: string {

  case SUMMER = 'summer';
  case WINTER = 'winter';

  public function getLabel(): TranslatableMarkup {
    return match ($this) {
      Season::SUMMER => new TranslatableMarkup('summer'),
      Season::WINTER => new TranslatableMarkup('winter'),
    };
  }
}
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.