PHPWord/Tests/_inc/TestHelperDOCX.php

124 lines
2.8 KiB
PHP
Raw Normal View History

2013-12-11 16:09:58 -05:00
<?php
namespace PHPWord\Tests;
use PHPWord;
use DOMDocument;
2014-02-24 19:17:06 +01:00
class TestHelperDOCX
2013-12-11 16:09:58 -05:00
{
2014-02-24 19:17:06 +01:00
static protected $file;
2013-12-11 16:09:58 -05:00
/**
* @param \PHPWord $PHPWord
2014-02-24 19:17:06 +01:00
* @return \PHPWord\Tests\Xml_Document
2013-12-11 16:09:58 -05:00
*/
public static function getDocument(PHPWord $PHPWord)
{
2014-02-24 19:17:06 +01:00
self::$file = tempnam(sys_get_temp_dir(), 'PHPWord');
if(!is_dir(sys_get_temp_dir().'/PHPWord_Unit_Test/')){
mkdir(sys_get_temp_dir().'/PHPWord_Unit_Test/');
}
2013-12-11 16:09:58 -05:00
$objWriter = \PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
2014-02-24 19:17:06 +01:00
$objWriter->save(self::$file);
2013-12-11 16:09:58 -05:00
$zip = new \ZipArchive;
2014-02-24 19:17:06 +01:00
$res = $zip->open(self::$file);
2013-12-11 16:09:58 -05:00
if ($res === true) {
2014-02-24 19:17:06 +01:00
$zip->extractTo(sys_get_temp_dir().'/PHPWord_Unit_Test/');
2013-12-11 16:09:58 -05:00
$zip->close();
}
2014-02-24 19:17:06 +01:00
return new Xml_Document(sys_get_temp_dir().'/PHPWord_Unit_Test/');
2013-12-11 16:09:58 -05:00
}
public static function clear()
{
2014-02-24 19:17:06 +01:00
if(file_exists(self::$file)){
unlink(self::$file);
}
if(is_dir(sys_get_temp_dir().'/PHPWord_Unit_Test/')){
self::deleteDir(sys_get_temp_dir().'/PHPWord_Unit_Test/');
}
2013-12-11 16:09:58 -05:00
}
/**
* @param string $dir
*/
public static function deleteDir($dir)
{
foreach (scandir($dir) as $file) {
if ($file === '.' || $file === '..') {
continue;
} else if (is_file($dir . "/" . $file)) {
unlink($dir . "/" . $file);
} else if (is_dir($dir . "/" . $file)) {
self::deleteDir($dir . "/" . $file);
}
}
rmdir($dir);
}
}
2014-02-24 19:17:06 +01:00
class Xml_Document
2013-12-11 16:09:58 -05:00
{
/** @var string $path */
private $path;
/** @var \DOMDocument $dom */
private $dom;
/** @var \DOMXpath $xpath */
private $xpath;
/** @var string $file */
private $file;
/**
* @param string $path
*/
public function __construct($path)
{
$this->path = realpath($path);
}
/**
* @param string $file
* @return \DOMDocument
*/
public function getFileDom($file = 'word/document.xml')
{
if (null !== $this->dom && $file === $this->file) {
return $this->dom;
}
$this->xpath = null;
$this->file = $file;
$file = $this->path . '/' . $file;
$this->dom = new DOMDocument();
$this->dom->load($file);
return $this->dom;
}
/**
* @param string $path
* @param string $file
* @return \DOMElement
*/
public function getElement($path, $file = 'word/document.xml')
{
if ($this->dom === null || $file !== $this->file) {
$this->getFileDom($file);
}
if (null === $this->xpath) {
$this->xpath = new \DOMXpath($this->dom);
}
$elements = $this->xpath->query($path);
return $elements->item(0);
}
}