Composite.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. *
  4. * Cube Framework $Id$ 8ayRqQn16Y9D2mRwM9m/NmlHqAWKvGZGjuwEFXObHjc=
  5. *
  6. * @link http://codecu.be/framework
  7. * @copyright Copyright (c) 2014 CodeCube SRL
  8. * @license http://codecu.be/framework/license Commercial License
  9. *
  10. * @version 1.0
  11. */
  12. /**
  13. * composite translate adapter
  14. * will combine the sentences from multiple adapters, based on the data inserted
  15. */
  16. namespace Ppb\Translate\Adapter;
  17. use Cube\Translate\Adapter,
  18. Cube\Config\AbstractConfig,
  19. Cube\Locale;
  20. class Composite extends Adapter\AbstractAdapter
  21. {
  22. public function addTranslation($options = array())
  23. {
  24. if (!is_array($options) && !($options instanceof AbstractConfig)) {
  25. throw new \InvalidArgumentException("The translation object requires an
  26. array or an object of type \Cube\ConfigAbstract.");
  27. }
  28. else {
  29. if ($options instanceof AbstractConfig) {
  30. $options = $options->getData();
  31. }
  32. if (!isset($options['path'])) {
  33. throw new \InvalidArgumentException("The 'path' key must be set.");
  34. }
  35. $locale = (isset($options['locale'])) ? $options['locale'] : null;
  36. if (Locale::isLocale($locale) === false) {
  37. throw new \InvalidArgumentException(
  38. sprintf("Add translation method error: '%s' is an invalid locale.", $locale));
  39. }
  40. if (!array_key_exists($locale, $this->_translate)) {
  41. $this->_translate[$locale] = array();
  42. }
  43. if (!empty($options['sources'])) {
  44. foreach ($options['sources'] as $source) {
  45. if (!isset($source['adapter'])) {
  46. throw new \InvalidArgumentException("The 'adapter' sub-key must be set.");
  47. }
  48. if (!isset($source['extension'])) {
  49. throw new \InvalidArgumentException("The 'extension' sub-key must be set.");
  50. }
  51. $translateAdapter = $source['adapter'];
  52. if (!class_exists($translateAdapter)) {
  53. throw new \InvalidArgumentException(
  54. sprintf("Class %s doesn't exist", $translateAdapter));
  55. }
  56. /** @var \Cube\Translate\Adapter\AbstractAdapter $adapter */
  57. $adapter = new $translateAdapter(array(
  58. 'file' => $options['path'] . '.' . $source['extension'],
  59. 'locale' => $locale,
  60. ));
  61. $translation = $adapter->getTranslate();
  62. foreach ($translation as $locale => $sentences) {
  63. $this->_translate[$locale] = array_merge($this->_translate[$locale], $sentences);
  64. }
  65. }
  66. }
  67. }
  68. return $this;
  69. }
  70. }