tmgmt_xtm-8.x-5.x-dev/src/Plugin/tmgmt/Translator/XmlFilesProvider.php
src/Plugin/tmgmt/Translator/XmlFilesProvider.php
<?php
namespace Drupal\tmgmt_xtm\Plugin\tmgmt\Translator;
use Masterminds\HTML5\Exception;
/**
* Class XmlFilesProvider.
*
* Provides XML files from the obtained XTM file.
*
* @package Drupal\tmgmt_xtm\Plugin\tmgmt\Translator
*/
class XmlFilesProvider {
/**
* The XTM file object.
*
* @var object
*/
private $xtmFile;
/**
* Constructs a new XmlFilesProvider object.
*
* @param object $xtmFile
* The XTM file object.
*/
public function __construct($xtmFile) {
$this->xtmFile = $xtmFile;
}
/**
* Retrieves XML files from the XTM file.
*
* @return array
* An array of SimpleXMLElement objects representing the XML files.
*
* @throws \Masterminds\HTML5\Exception
* Throws an exception if the XTM file cannot be read from the ZIP archive.
*/
public function getXmlFiles() {
$this->unpack();
$xmls = $this->loadXmls();
$this->removeFolder();
if (empty($xmls)) {
throw new Exception("Could not read XTM file from Zip");
}
return $xmls;
}
/**
* Unpacks the XTM file.
*/
private function unpack() {
ZipHelper::unpack(FileHelper::getTemp($this->xtmFile), ZipHelper::get_unpack_folder($this->xtmFile));
}
/**
* Finds the paths of XML files in the unpacked folder.
*
* @return array|false
* An array of file paths, or false if no XML files are found.
*/
private function findPaths() {
$globFilePaths = glob(ZipHelper::get_unpack_folder($this->xtmFile) . '/' . $this->xtmFile->targetLanguage . '/' . "*.xml");
if (empty($globFilePaths)) {
$globFilePaths = glob(ZipHelper::get_unpack_folder($this->xtmFile) . '/' . "*.xml");
}
return $globFilePaths;
}
/**
* Loads XML files from the found paths.
*
* @return array
* An array of SimpleXMLElement objects.
*
* @throws \Masterminds\HTML5\Exception
* Throws an exception if no XML data is found.
*/
private function loadXmls() {
$xmls = [];
foreach ($this->findPaths() as $globFilePath) {
$xml = simplexml_load_string(file_get_contents($globFilePath), NULL, LIBXML_NOCDATA);
if (FALSE === $xml) {
throw new Exception("No XML DATA");
}
$xmls[] = $xml;
}
return $xmls;
}
/**
* Removes the unpacked folder.
*/
private function removeFolder() {
$filename = ZipHelper::get_unpack_folder($this->xtmFile);
if (is_dir($filename)) {
FileHelper::removeFolder($filename);
}
}
}
