From 00849bc3ba454821c12552301b72cc9fb8a994ad Mon Sep 17 00:00:00 2001 From: Vincent Vanwaelscappel Date: Mon, 8 Jul 2019 14:18:49 +0200 Subject: [PATCH] #2868 --- src/Translate.php | 106 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 src/Translate.php diff --git a/src/Translate.php b/src/Translate.php new file mode 100644 index 0000000..ed27c8a --- /dev/null +++ b/src/Translate.php @@ -0,0 +1,106 @@ +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 = '