Skip to content
Permalink
Browse files

MINOR Added zend_translate_railsyaml dependency

  • Loading branch information...
chillu committed Nov 26, 2011
1 parent 7e7d988 commit 3342c84abedd6009abcd26bdbf5e0b6a6f0755d1
@@ -0,0 +1,8 @@
---
format: 1
handler:
commit: 2d5f2164b200309f6643f8f8486e0cdbbcae348d
branch: master
lock: false
repository_class: Piston::Git::Repository
repository_url: git://github.com/chillu/zend_translate_railsyaml.git
@@ -0,0 +1,24 @@
* Copyright (c) 2011, Ingo Schommer
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY Ingo Schommer. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL Silverstripe Ltd. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,61 @@
# Zend_Translate Adapter for Rails-style YAML files #

## Overview ##

Adds support for translations in YAML to [Zend_Translate](http://framework.zend.com/manual/en/zend.translate.html).
As Yaml is a very flexible format, the translation files need some conventions.
These conventions are adopted from Ruby on Rails (see [Rails' i18n docs](http://guides.rubyonrails.org/i18n.html)).
Note: You don't need Ruby or Rails to run this code, its just PHP with the same YAML conventions.

## Requirements ##

* Zend Framework (tested with 1.11.6)
* PHP 5.2

## Installation and Usage ##

Assumes a working `include_path` setup for Zend (see [tutorial](http://framework.zend.com/manual/en/learning.quickstart.create-project.html)).

Copy the files into your Zend directory (replace `<zend_path>` below):

cp -r library/Translate/Adapter/* <zend_path>/Zend/Translate/Adapter
cp -r tests/Translate/Adapter/* <zend_path>/Zend/tests/Translate/Adapter

Usage:

require_once 'Zend/Translate/Adapater/RailsYaml.php';
$adapter = new Zend_Translate_Adapter_RailsYaml('en.yml', 'en');
$adapter->addTranslation('de.yml', 'de');

Does not support namespace "fallbacks", as `Zend_Translate`
doesn't have built-in support for them - it just flattens nested keys.
Does not support multiple locales per translation file.

## Sample translation files

en.yml

en:
Message1: Message 1 (en)
Message2: Message 2 (en)
Namespace1:
Message1: Namespace 1 Message 2 (en)
Namespace1Message1: Namespace 1 Message 2 (en)

de.yml

de:
Message1: Message 1 (de)
Namespace1:
Message1: Namespace 1 Message 2 (de)
Namespace1Message1: Namespace 1 Message 2 (de)

## Running the unit tests ##

The tests assume the Zend Framework in a very specific location. See `tests/TestHelper.php` for details.
Its recommended that you copy the relevant files directly into the Zend directory structure.

## Links ##

* [`Zend_Translate_Yaml` Proposal on zend.com](http://framework.zend.com/wiki/display/ZFPROP/Zend_Translate_Yaml+-+Thomas+Weidner) - not actively pursued any longer
* [`Zend_Translate_Yaml` sample code](http://framework.zend.com/issues/browse/ZF-2152)
@@ -0,0 +1,104 @@
<?php
/** Zend_Locale */
require_once 'Zend/Locale.php';
/** Zend_Translate_Adapter */
require_once 'Zend/Translate/Adapter.php';
require_once 'thirdparty/sfYaml/lib/sfYaml.php';
class Translate_Adapter_RailsYaml extends Zend_Translate_Adapter {
/**
* Generates the adapter
*
* @param array|Zend_Config $options Translation content
*/
public function __construct($options = array()) {
$this->_options['keyDelimiter'] = ".";
parent::__construct($options);
}
/**
* Load translation data
*
* @param string|array $data Filename and full path to the translation source
* @param string $locale Locale/Language to add data for, identical with locale identifier,
* see Zend_Locale for more information
* @param array $option OPTIONAL Options to use
*/
protected function _loadTranslationData($data, $locale, array $options = array())
{
$options = array_merge($this->_options, $options);
if ($options['clear'] || !isset($this->_translate[$locale])) {
$this->_translate[$locale] = array();
}
if(is_array($data)) return array($locale => $data);
$this->_filename = $data;
if (!is_readable($this->_filename)) {
require_once 'Zend/Translate/Exception.php';
throw new Zend_Translate_Exception('Error opening translation file \'' . $this->_filename . '\'.');
}
$content = sfYaml::load(file_get_contents($this->_filename));
if($locale != 'auto' && !array_key_exists($locale, $content)) {
require_once 'Zend/Translate/Exception.php';
throw new Zend_Translate_Exception(sprintf('Locale "%s" not found in file %s', $locale, $this->_filename));
}
// Rails YML files supported arbitrarily nested keys, Zend_Translate doesn't - so we flatten them.
// See http://stackoverflow.com/questions/7011451/transaprently-flatten-an-array/7011675
$flattened = array();
if($content[$locale]) {
$iterator = new Translate_Adapter_RailsYaml_Iterator(new RecursiveArrayIterator($content[$locale]));
foreach($iterator as $k => $v) {
$flattened[implode($options['keyDelimiter'], $iterator->getKeyStack())] = $v;
}
}
return array($locale => $flattened);
}
/**
* returns the adapters name
*
* @return string
*/
public function toString()
{
return "RailsYaml";
}
}
class Translate_Adapter_RailsYaml_Iterator extends RecursiveIteratorIterator
{
protected $keyStack = array();
public function callGetChildren()
{
$this->keyStack[] = parent::key();
return parent::callGetChildren();
}
public function endChildren()
{
array_pop($this->keyStack);
parent::endChildren();
}
public function key()
{
return json_encode($this->getKeyStack());
}
public function getKeyStack()
{
return array_merge($this->keyStack, array(parent::key()));
}
}
@@ -0,0 +1,19 @@
Copyright (c) 2008-2009 Fabien Potencier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,15 @@
Symfony YAML: A PHP library that speaks YAML
============================================

Symfony YAML is a PHP library that parses YAML strings and converts them to
PHP arrays. It can also converts PHP arrays to YAML strings. Its official
website is at http://components.symfony-project.org/yaml/.

The documentation is to be found in the `doc/` directory.

Symfony YAML is licensed under the MIT license (see LICENSE file).

The Symfony YAML library is developed and maintained by the
[symfony](http://www.symfony-project.org/) project team. It has been extracted
from symfony to be used as a standalone library. Symfony YAML is part of the
[symfony components project](http://components.symfony-project.org/).
@@ -0,0 +1,135 @@
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 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.
*/
/**
* sfYaml offers convenience methods to load and dump YAML.
*
* @package symfony
* @subpackage yaml
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfYaml.class.php 8988 2008-05-15 20:24:26Z fabien $
*/
class sfYaml
{
static protected
$spec = '1.2';
/**
* Sets the YAML specification version to use.
*
* @param string $version The YAML specification version
*/
static public function setSpecVersion($version)
{
if (!in_array($version, array('1.1', '1.2')))
{
throw new InvalidArgumentException(sprintf('Version %s of the YAML specifications is not supported', $version));
}
self::$spec = $version;
}
/**
* Gets the YAML specification version to use.
*
* @return string The YAML specification version
*/
static public function getSpecVersion()
{
return self::$spec;
}
/**
* Loads YAML into a PHP array.
*
* The load method, when supplied with a YAML stream (string or file),
* will do its best to convert YAML in a file into a PHP array.
*
* Usage:
* <code>
* $array = sfYaml::load('config.yml');
* print_r($array);
* </code>
*
* @param string $input Path of YAML file or string containing YAML
*
* @return array The YAML converted to a PHP array
*
* @throws InvalidArgumentException If the YAML is not valid
*/
public static function load($input)
{
$file = '';
// if input is a file, process it
if (strpos($input, "\n") === false && is_file($input))
{
$file = $input;
ob_start();
$retval = include($input);
$content = ob_get_clean();
// if an array is returned by the config file assume it's in plain php form else in YAML
$input = is_array($retval) ? $retval : $content;
}
// if an array is returned by the config file assume it's in plain php form else in YAML
if (is_array($input))
{
return $input;
}
require_once dirname(__FILE__).'/sfYamlParser.php';
$yaml = new sfYamlParser();
try
{
$ret = $yaml->parse($input);
}
catch (Exception $e)
{
throw new InvalidArgumentException(sprintf('Unable to parse %s: %s', $file ? sprintf('file "%s"', $file) : 'string', $e->getMessage()));
}
return $ret;
}
/**
* Dumps a PHP array to a YAML string.
*
* The dump method, when supplied with an array, will do its best
* to convert the array into friendly YAML.
*
* @param array $array PHP array
* @param integer $inline The level where you switch to inline YAML
*
* @return string A YAML string representing the original PHP array
*/
public static function dump($array, $inline = 2)
{
require_once dirname(__FILE__).'/sfYamlDumper.php';
$yaml = new sfYamlDumper();
return $yaml->dump($array, $inline);
}
}
/**
* Wraps echo to automatically provide a newline.
*
* @param string $string The string to echo with new line
*/
function echoln($string)
{
echo $string."\n";
}

0 comments on commit 3342c84

Please sign in to comment.
You can’t perform that action at this time.