[Translation] Added CsvFileLoader to support csv translation resources.

This commit is contained in:
umpirsky 2011-01-08 15:09:18 +01:00 committed by Fabien Potencier
parent 10fee8c8bb
commit bdada47fad
4 changed files with 96 additions and 0 deletions

View File

@ -0,0 +1,55 @@
<?php
namespace Symfony\Component\Translation\Loader;
use Symfony\Component\Translation\Resource\FileResource;
/*
* This file is part of the Symfony framework.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
/**
* CsvFileLoader loads translations from CSV files.
*
* @author Saša Stamenković <umpirsky@gmail.com>
*/
class CsvFileLoader extends ArrayLoader implements LoaderInterface
{
/**
* {@inheritdoc}
*/
public function load($resource, $locale, $domain = 'messages')
{
$messages = array();
$file = @fopen($resource, 'rb');
if (!$file) {
throw new \InvalidArgumentException(sprintf('Error opening file "%s".', $resource));
}
while(($data = fgetcsv($file, 0, ';')) !== false) {
if (substr($data[0], 0, 1) === '#') {
continue;
}
if (!isset($data[1])) {
continue;
}
if (count($data) == 2) {
$messages[$data[0]] = $data[1];
} else {
continue;
}
}
$catalogue = parent::load($messages, $locale, $domain);
$catalogue->addResource(new FileResource($resource));
return $catalogue;
}
}

View File

@ -0,0 +1,40 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Tests\Component\Translation\Loader;
use Symfony\Component\Translation\Loader\CsvFileLoader;
use Symfony\Component\Translation\Resource\FileResource;
class CsvFileLoaderTest extends \PHPUnit_Framework_TestCase
{
public function testLoad()
{
$loader = new CsvFileLoader();
$resource = __DIR__.'/../fixtures/resources.csv';
$catalogue = $loader->load($resource, 'en', 'domain1');
$this->assertEquals(array('foo' => 'bar'), $catalogue->all('domain1'));
$this->assertEquals('en', $catalogue->getLocale());
$this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
}
public function testLoadDoesNothingIfEmpty()
{
$loader = new CsvFileLoader();
$resource = __DIR__.'/../fixtures/empty.csv';
$catalogue = $loader->load($resource, 'en', 'domain1');
$this->assertEquals(array(), $catalogue->all('domain1'));
$this->assertEquals('en', $catalogue->getLocale());
$this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
}
}

View File

@ -0,0 +1 @@
"foo"; "bar"
1 foo bar