Skip to content

Add option to extract messages from static method calls #9

@ybelenko

Description

@ybelenko

I'm not sure, maybe this issue should be submitted to nikic/php-parser repo instead. I use own Translator helper class with static methods and I cannot extract messages from it method invocations.

Translator helper class:

use Gettext\Loader\PoLoader;
use Gettext\Translation;

final class Translator
{
    /** @var Gettext\Loader\LoaderInterface|null */
    protected static $loader;

    /** @var Gettext\Translations|null */
    protected static $translations;

    /**
     * Loads translations from PO file with php/gettext package.
     * @ref https://github.com/php-gettext/Gettext
     *
     * @param string $filePath Path to PO file
     */
    public static function loadPo(string $filePath)
    {
        if (!static::$loader) {
            static::$loader = new PoLoader();
        }
        static::$translations = static::$loader->loadFile($filePath);
    }

    /**
     * Translates message.
     *
     * @param string $msg Original message
     *
     * @return string Localized message or original if doesn't exist in PO file
     */
    public static function translate(string $msg): string
    {
        $t = static::$translations->find(null, $msg);
        if (
            $t instanceof Translation
            && $t->isTranslated()
        ) {
            return $t->getTranslation();
        }

        return $msg;
    }
}

scanner configuration:

//Create a new scanner, adding a translation for each domain we want to get:
$phpScanner = new PhpScanner(
    Translations::create('domain')
);

$phpScanner->setFunctions(
    array_merge(
        $phpScanner->getFunctions(),
        // none of following works
        ['Translator::translate' => 'gettext'],
        ['::translate' => 'gettext'],
        ['translate' => 'gettext']
    )
);

scanned file example:

Translator::loadPo('../locale/en/LC_MESSAGES/domain.po');
// i18n: 'Hello World' should be extracted
$msg = Translator::translate('Hello World');
echo $msg;

// po file saving omitted

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions