--- /dev/null
+<?php
+
+namespace Cubist\Locale;
+class Translate
+{
+
+ protected $_paths = array();
+ protected $_extensions = array();
+ protected $_toTranslate = array();
+
+ public function __construct()
+ {
+ $this->addExtension('php');
+ $this->addExtension('phtml');
+ }
+
+ public function addPath($path)
+ {
+ $this->_paths[] = $path;
+ }
+
+ public function clearPaths()
+ {
+ $this->_paths = array();
+ $this->_toTranslate = array();
+ }
+
+ public function addExtension($ext)
+ {
+ $this->_extensions[] = $ext;
+ }
+
+ public function parseFiles()
+ {
+ $this->_extensions = array_unique($this->_extensions);
+ $this->_paths = array_unique($this->_paths);
+
+ foreach ($this->_paths as $path) {
+ $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
+ foreach ($iterator as $p) {
+ if ($p->isFile()) {
+ $this->_parseFile($p);
+ }
+ }
+ }
+ $this->_toTranslate = array_unique($this->_toTranslate);
+ }
+
+ protected function _parseFile(SplFileInfo $file)
+ {
+ $e = explode('.', $file);
+ $ext = $file->getExtension();
+
+ if (!in_array($ext, $this->_extensions)) {
+ return;
+ }
+
+ $this->_toTranslate = array_merge($this->_toTranslate, self::extractTextsToTranslate($file));
+ }
+
+ public static function extractTextsToTranslate(SplFileInfo $file)
+ {
+ $toTranslate = array();
+
+ if (!$file->isFile() || !$file->isReadable()) {
+ $toTranslate = array();
+ } else {
+ $c = file_get_contents($file);
+
+ // @link https://regex101.com/r/uD0eT1/4
+ if (preg_match_all('/__\(([\'\"]{1})(.*)(([^\\\\]{1})(\1))(.*)\)/Us', $c, $matches)) {
+ foreach ($matches[2] as $k => $m) {
+ if ($m == '') {
+ continue;
+ }
+ $m .= $matches[4][$k];
+ $toTranslate[] = stripcslashes($m);
+ }
+ }
+ }
+
+ return $toTranslate;
+ }
+
+ public function hasSomethingToTranslate()
+ {
+ return count($this->_toTranslate) > 0;
+ }
+
+
+ /**
+ *
+ * @return array
+ */
+ public function getStringToTranslate()
+ {
+ return $this->_toTranslate;
+ }
+
+ public static function saveTranslations($data, $path, $varname = '$translations')
+ {
+ $phpCode = '<?php return = ' . var_export($data, true) . ';';
+ file_put_contents($path, $phpCode);
+ }
+
+}