This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
symfony/src/Symfony/Bundle/FrameworkBundle/Translation/PhpExtractor.php

124 lines
2.9 KiB
PHP
Raw Normal View History

<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Translation;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\Extractor\ExtractorInterface;
/**
* PhpExtractor extracts translation messages from a php template.
2011-10-29 11:05:45 +01:00
*
* @author Michel Salib <michelsalib@hotmail.com>
*/
class PhpExtractor implements ExtractorInterface
{
const MESSAGE_TOKEN = 300;
const IGNORE_TOKEN = 400;
2011-10-29 11:05:45 +01:00
/**
* Prefix for new found message.
*
* @var string
*/
private $prefix = '';
/**
* The sequence that captures translation messages.
2011-10-29 11:05:45 +01:00
*
* @var array
*/
protected $sequences = array(
array(
'$view',
'[',
'\'translator\'',
']',
'->',
'trans',
'(',
self::MESSAGE_TOKEN,
')',
),
);
/**
* {@inheritDoc}
*/
public function extract($directory, MessageCatalogue $catalog)
{
// load any existing translation files
$finder = new Finder();
$files = $finder->files()->name('*.php')->in($directory);
foreach ($files as $file) {
$this->parseTokens(token_get_all(file_get_contents($file)), $catalog);
}
}
2011-10-29 11:05:45 +01:00
/**
* {@inheritDoc}
*/
public function setPrefix($prefix)
{
$this->prefix = $prefix;
}
/**
* Normalizes a token.
2011-10-29 11:05:45 +01:00
*
* @param mixed $token
2011-10-29 11:05:45 +01:00
* @return string
*/
protected function normalizeToken($token)
{
if (is_array($token)) {
return $token[1];
}
2011-10-29 11:05:45 +01:00
return $token;
}
/**
* Extracts trans message from php tokens.
2011-10-29 11:05:45 +01:00
*
* @param array $tokens
2011-10-29 11:05:45 +01:00
* @param MessageCatalogue $catalog
*/
protected function parseTokens($tokens, MessageCatalogue $catalog)
{
foreach ($tokens as $key => $token) {
foreach ($this->sequences as $sequence) {
$message = '';
foreach ($sequence as $id => $item) {
if($this->normalizeToken($tokens[$key + $id]) == $item) {
continue;
} elseif (self::MESSAGE_TOKEN == $item) {
$message = $this->normalizeToken($tokens[$key + $id]);
} elseif (self::IGNORE_TOKEN == $item) {
continue;
} else {
break;
}
}
$message = trim($message, '\'');
2011-10-29 11:05:45 +01:00
if ($message) {
$catalog->set($message, $this->prefix.$message);
break;
}
}
}
}
}