php-gettext / Gettext

PHP library to collect and manipulate gettext (.po, .mo, .php, .json, etc)
MIT License
688 stars 134 forks source link

[Question] Simplest way to promote items in a Translations object to a subclass? #292

Closed rulatir closed 3 months ago

rulatir commented 1 year ago

Use case: I receive a Translations object $original containing vanilla Translation items, and I must return a Translations object $extended with the following properties:

This was easy while ->exchangeArray() was available. Now that it is gone, it seems I must do this:

Is there a simpler way with current API?

Translations is a collection object, and I believe it should provide fully featured collection API: map(), filter(), removeAll() etc.

oscarotero commented 1 year ago

Probably something like this?

$extended = clone $original;

foreach ($extended as $translation) {
    $extended->add(new ExtendedTranslation($translation));
}

If the old and new translations has the same id, it will be overrided, so you don't need to remove the first.

Another way is creating the ExtendedTranslations class:

class ExtendedTranslations extends Translations {
    public static function create(Translations $traslations) {
        $new = new static();
        $new->description = $translations->description;
        $new->headers = $translations->headers;
        $new->flags = $translations->flags;
        $new->translations = array_map(function ($translation) {
            return new ExtendedTranslation($translation))
        }, $translations->getTranslations());

        return $new;
    }
}

$extended = ExtendedTranslations::create($original);