Refactored PHPWord_Exception to namespaces

This commit is contained in:
Gabriel Bull 2014-03-15 09:27:48 -04:00
parent 0c5e405937
commit 3b7dac452b
17 changed files with 213 additions and 208 deletions

View File

@ -34,6 +34,8 @@ if (!defined('PHPWORD_BASE_PATH')) {
} }
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
use PhpOffice\PhpWord\Exceptions\Exception;
/** /**
* PHPWord * PHPWord
*/ */
@ -252,17 +254,15 @@ class PHPWord
* *
* @param string $strFilename * @param string $strFilename
* @return PHPWord_Template * @return PHPWord_Template
* @throws Exception
*/ */
public function loadTemplate($strFilename) public function loadTemplate($strFilename)
{ {
if (file_exists($strFilename)) { if (file_exists($strFilename)) {
$template = new PHPWord_Template($strFilename); $template = new PHPWord_Template($strFilename);
return $template; return $template;
} else {
throw new PHPWord_Exception(
"Template file {$strFilename} not found."
);
} }
throw new Exception("Template file {$strFilename} not found.");
} }
/** /**

View File

@ -1,49 +0,0 @@
<?php
/**
* PHPWord
*
* Copyright (c) 2009 - 2010 PHPWord
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPWord
* @package PHPWord
* @copyright Copyright (c) 2014 PHPWord
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version 0.8.0
*/
/**
* Class PHPWord_Exception
*/
class PHPWord_Exception extends Exception
{
/**
* Error handler callback
*
* @param mixed $code
* @param mixed $string
* @param mixed $file
* @param mixed $line
* @param mixed $context
*/
public static function errorHandlerCallback($code, $string, $file, $line, $context)
{
$e = new self($string, $code);
$e->line = $line;
$e->file = $file;
throw $e;
}
}

View File

@ -0,0 +1,9 @@
<?php
namespace PhpOffice\PhpWord\Exceptions;
/**
* Class Exception
*/
class Exception extends \Exception
{
}

View File

@ -1,8 +1,6 @@
<?php <?php
namespace PhpOffice\PhpWord\Exceptions; namespace PhpOffice\PhpWord\Exceptions;
use Exception;
/** /**
* InvalidImageException * InvalidImageException
* *

View File

@ -12,4 +12,4 @@ use InvalidArgumentException;
*/ */
class InvalidStyleException extends InvalidArgumentException class InvalidStyleException extends InvalidArgumentException
{ {
} }

View File

@ -1,8 +1,6 @@
<?php <?php
namespace PhpOffice\PhpWord\Exceptions; namespace PhpOffice\PhpWord\Exceptions;
use Exception;
/** /**
* UnsupportedImageTypeException * UnsupportedImageTypeException
* *

View File

@ -25,12 +25,13 @@
* @version 0.8.0 * @version 0.8.0
*/ */
use PhpOffice\PhpWord\Exceptions\Exception;
/** /**
* Class PHPWord_IOFactory * Class PHPWord_IOFactory
*/ */
class PHPWord_IOFactory class PHPWord_IOFactory
{ {
/** /**
* Search locations * Search locations
* *
@ -73,13 +74,9 @@ class PHPWord_IOFactory
* @param array $value * @param array $value
* @throws Exception * @throws Exception
*/ */
public static function setSearchLocations($value) public static function setSearchLocations(array $value)
{ {
if (is_array($value)) { self::$_searchLocations = $value;
self::$_searchLocations = $value;
} else {
throw new Exception('Invalid parameter passed.');
}
} }
/** /**
@ -100,6 +97,7 @@ class PHPWord_IOFactory
* @param PHPWord $PHPWord * @param PHPWord $PHPWord
* @param string $writerType Example: Word2007 * @param string $writerType Example: Word2007
* @return PHPWord_Writer_IWriter * @return PHPWord_Writer_IWriter
* @throws Exception
*/ */
public static function createWriter(PHPWord $PHPWord, $writerType = '') public static function createWriter(PHPWord $PHPWord, $writerType = '')
{ {
@ -123,8 +121,9 @@ class PHPWord_IOFactory
/** /**
* Create PHPWord_Reader_IReader * Create PHPWord_Reader_IReader
* *
* @param string $readerType Example: Word2007 * @param string $readerType Example: Word2007
* @return PHPWord_Reader_IReader * @return PHPWord_Reader_IReader
* @throws Exception
*/ */
public static function createReader($readerType = '') public static function createReader($readerType = '')
{ {
@ -141,18 +140,19 @@ class PHPWord_IOFactory
} }
} }
throw new PHPWord_Exception("No $searchType found for type $readerType"); throw new Exception("No $searchType found for type $readerType");
} }
/** /**
* Loads PHPWord from file * Loads PHPWord from file
* *
* @param string $pFilename The name of the file * @param string $pFilename The name of the file
* @return PHPWord * @param string $readerType
* @return PHPWord
*/ */
public static function load($pFilename, $readerType = 'Word2007') public static function load($pFilename, $readerType = 'Word2007')
{ {
$reader = self::createReader($readerType); $reader = self::createReader($readerType);
return $reader->load($pFilename); return $reader->load($pFilename);
} }
} }

View File

@ -25,6 +25,8 @@
* @version 0.8.0 * @version 0.8.0
*/ */
use PhpOffice\PhpWord\Exceptions\Exception;
/** /**
* PHPWord_Reader_Abstract * PHPWord_Reader_Abstract
* *
@ -35,17 +37,19 @@ abstract class PHPWord_Reader_Abstract implements PHPWord_Reader_IReader
/** /**
* Read data only? * Read data only?
* *
* @var boolean * @var bool
*/ */
protected $readDataOnly = true; protected $readDataOnly = true;
/**
* @var bool|resource
*/
protected $fileHandle = true; protected $fileHandle = true;
/** /**
* Read data only? * Read data only?
* *
* @return boolean * @return bool
*/ */
public function getReadDataOnly() public function getReadDataOnly()
{ {
@ -56,8 +60,8 @@ abstract class PHPWord_Reader_Abstract implements PHPWord_Reader_IReader
/** /**
* Set read data only * Set read data only
* *
* @param boolean $pValue * @param bool $pValue
* @return PHPWord_Reader_IReader * @return PHPWord_Reader_IReader
*/ */
public function setReadDataOnly($pValue = true) public function setReadDataOnly($pValue = true)
{ {
@ -69,29 +73,28 @@ abstract class PHPWord_Reader_Abstract implements PHPWord_Reader_IReader
* Open file for reading * Open file for reading
* *
* @param string $pFilename * @param string $pFilename
* @throws PHPWord_Exception
* @return resource * @return resource
* @throws Exception
*/ */
protected function openFile($pFilename) protected function openFile($pFilename)
{ {
// Check if file exists // Check if file exists
if (!file_exists($pFilename) || !is_readable($pFilename)) { if (!file_exists($pFilename) || !is_readable($pFilename)) {
throw new PHPWord_Exception("Could not open " . $pFilename . " for reading! File does not exist."); throw new Exception("Could not open " . $pFilename . " for reading! File does not exist.");
} }
// Open file // Open file
$this->fileHandle = fopen($pFilename, 'r'); $this->fileHandle = fopen($pFilename, 'r');
if ($this->fileHandle === false) { if ($this->fileHandle === false) {
throw new PHPWord_Exception("Could not open file " . $pFilename . " for reading."); throw new Exception("Could not open file " . $pFilename . " for reading.");
} }
} }
/** /**
* Can the current PHPWord_Reader_IReader read the file? * Can the current PHPWord_Reader_IReader read the file?
* *
* @param string $pFilename * @param string $pFilename
* @return boolean * @return bool
* @throws PHPWord_Exception
*/ */
public function canRead($pFilename) public function canRead($pFilename)
{ {
@ -102,6 +105,6 @@ abstract class PHPWord_Reader_Abstract implements PHPWord_Reader_IReader
return false; return false;
} }
fclose($this->fileHandle); fclose($this->fileHandle);
return $readable; return true;
} }
} }

View File

@ -31,32 +31,25 @@ if (!defined('PHPWORD_BASE_PATH')) {
require(PHPWORD_BASE_PATH . 'PHPWord/Autoloader.php'); require(PHPWORD_BASE_PATH . 'PHPWord/Autoloader.php');
} }
use PhpOffice\PhpWord\Exceptions\Exception;
/** /**
* PHPWord_Reader_Word2007 * PHPWord_Reader_Word2007
*/ */
class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements PHPWord_Reader_IReader
PHPWord_Reader_IReader
{ {
/**
* Create a new PHPWord_Reader_Word2007 instance
*/
public function __construct()
{
}
/** /**
* Can the current PHPWord_Reader_IReader read the file? * Can the current PHPWord_Reader_IReader read the file?
* *
* @param string $pFilename * @param string $pFilename
* @return bool * @return bool
* @throws Exception
*/ */
public function canRead($pFilename) public function canRead($pFilename)
{ {
// Check if file exists // Check if file exists
if (!file_exists($pFilename)) { if (!file_exists($pFilename)) {
throw new PHPWord_Exception( throw new Exception("Could not open {$pFilename} for reading! File does not exist.");
"Could not open {$pFilename} for reading! File does not exist."
);
} }
$return = false; $return = false;
@ -86,15 +79,13 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements
/** /**
* Get from zip archive * Get from zip archive
* *
* @param ZipArchive $archive * @param ZipArchive $archive
* @param string $fileName * @param string $fileName
* @param bool $removeNamespace * @param bool $removeNamespace
* @return mixed
*/ */
public function getFromZipArchive( public function getFromZipArchive($archive, $fileName = '', $removeNamespace = false)
$archive, {
$fileName = '',
$removeNamespace = false
) {
// Root-relative paths // Root-relative paths
if (strpos($fileName, '//') !== false) { if (strpos($fileName, '//') !== false) {
$fileName = substr($fileName, strpos($fileName, '//') + 1); $fileName = substr($fileName, strpos($fileName, '//') + 1);
@ -115,18 +106,17 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements
return $contents; return $contents;
} }
/** /**
* Loads PHPWord from file * Loads PHPWord from file
* *
* @param string $pFilename * @param string $pFilename
* @return PHPWord|null * @return PHPWord|null
*/ */
public function load($pFilename) public function load($pFilename)
{ {
// Check if file exists and can be read // Check if file exists and can be read
if (!$this->canRead($pFilename)) { if (!$this->canRead($pFilename)) {
return; return null;
} }
// Initialisations // Initialisations
@ -146,15 +136,15 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements
$xmlCore->registerXPathNamespace("dcterms", "http://purl.org/dc/terms/"); $xmlCore->registerXPathNamespace("dcterms", "http://purl.org/dc/terms/");
$xmlCore->registerXPathNamespace("cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"); $xmlCore->registerXPathNamespace("cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties");
$docProps = $word->getProperties(); $docProps = $word->getProperties();
$docProps->setCreator((string) self::arrayItem($xmlCore->xpath("dc:creator"))); $docProps->setCreator((string)self::arrayItem($xmlCore->xpath("dc:creator")));
$docProps->setLastModifiedBy((string) self::arrayItem($xmlCore->xpath("cp:lastModifiedBy"))); $docProps->setLastModifiedBy((string)self::arrayItem($xmlCore->xpath("cp:lastModifiedBy")));
$docProps->setCreated(strtotime(self::arrayItem($xmlCore->xpath("dcterms:created")))); $docProps->setCreated(strtotime(self::arrayItem($xmlCore->xpath("dcterms:created"))));
$docProps->setModified(strtotime(self::arrayItem($xmlCore->xpath("dcterms:modified")))); $docProps->setModified(strtotime(self::arrayItem($xmlCore->xpath("dcterms:modified"))));
$docProps->setTitle((string) self::arrayItem($xmlCore->xpath("dc:title"))); $docProps->setTitle((string)self::arrayItem($xmlCore->xpath("dc:title")));
$docProps->setDescription((string) self::arrayItem($xmlCore->xpath("dc:description"))); $docProps->setDescription((string)self::arrayItem($xmlCore->xpath("dc:description")));
$docProps->setSubject((string) self::arrayItem($xmlCore->xpath("dc:subject"))); $docProps->setSubject((string)self::arrayItem($xmlCore->xpath("dc:subject")));
$docProps->setKeywords((string) self::arrayItem($xmlCore->xpath("cp:keywords"))); $docProps->setKeywords((string)self::arrayItem($xmlCore->xpath("cp:keywords")));
$docProps->setCategory((string) self::arrayItem($xmlCore->xpath("cp:category"))); $docProps->setCategory((string)self::arrayItem($xmlCore->xpath("cp:category")));
} }
break; break;
// Extended properties // Extended properties
@ -163,10 +153,10 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements
if (is_object($xmlCore)) { if (is_object($xmlCore)) {
$docProps = $word->getProperties(); $docProps = $word->getProperties();
if (isset($xmlCore->Company)) { if (isset($xmlCore->Company)) {
$docProps->setCompany((string) $xmlCore->Company); $docProps->setCompany((string)$xmlCore->Company);
} }
if (isset($xmlCore->Manager)) { if (isset($xmlCore->Manager)) {
$docProps->setManager((string) $xmlCore->Manager); $docProps->setManager((string)$xmlCore->Manager);
} }
} }
break; break;
@ -178,10 +168,10 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements
foreach ($xmlCore as $xmlProperty) { foreach ($xmlCore as $xmlProperty) {
$cellDataOfficeAttributes = $xmlProperty->attributes(); $cellDataOfficeAttributes = $xmlProperty->attributes();
if (isset($cellDataOfficeAttributes['name'])) { if (isset($cellDataOfficeAttributes['name'])) {
$propertyName = (string) $cellDataOfficeAttributes['name']; $propertyName = (string)$cellDataOfficeAttributes['name'];
$cellDataOfficeChildren = $xmlProperty->children("http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"); $cellDataOfficeChildren = $xmlProperty->children("http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes");
$attributeType = $cellDataOfficeChildren->getName(); $attributeType = $cellDataOfficeChildren->getName();
$attributeValue = (string) $cellDataOfficeChildren->{$attributeType}; $attributeValue = (string)$cellDataOfficeChildren->{$attributeType};
$attributeValue = PHPWord_DocumentProperties::convertProperty($attributeValue, $attributeType); $attributeValue = PHPWord_DocumentProperties::convertProperty($attributeValue, $attributeType);
$attributeType = PHPWord_DocumentProperties::convertPropertyType($attributeType); $attributeType = PHPWord_DocumentProperties::convertPropertyType($attributeType);
$docProps->setCustomProperty($propertyName, $attributeValue, $attributeType); $docProps->setCustomProperty($propertyName, $attributeValue, $attributeType);
@ -219,7 +209,7 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements
$elm->r->t, $elm->r->t,
$this->loadFontStyle($elm->r) $this->loadFontStyle($elm->r)
); );
// w:r more than 1? It's a textrun // w:r more than 1? It's a textrun
} else { } else {
$textRun = $section->createTextRun(); $textRun = $section->createTextRun();
foreach ($elm->r as $r) { foreach ($elm->r as $r) {
@ -229,7 +219,7 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements
); );
} }
} }
// No, it's a textbreak // No, it's a textbreak
} else { } else {
$section->addTextBreak(); $section->addTextBreak();
} }
@ -282,8 +272,8 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements
/** /**
* Load section settings from SimpleXMLElement * Load section settings from SimpleXMLElement
* *
* @param SimpleXMLElement $elm * @param SimpleXMLElement $elm
* @return array|string|null * @return array|string|null
* *
* @todo Implement gutter * @todo Implement gutter
*/ */
@ -337,16 +327,15 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements
} }
} }
return $setting; return $setting;
} else {
return null;
} }
return null;
} }
/** /**
* Load paragraph style from SimpleXMLElement * Load paragraph style from SimpleXMLElement
* *
* @param SimpleXMLElement $elm * @param SimpleXMLElement $elm
* @return array|string|null * @return array|string|null
*/ */
private function loadParagraphStyle($elm) private function loadParagraphStyle($elm)
{ {
@ -399,16 +388,15 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements
$style['pageBreakBefore'] = true; $style['pageBreakBefore'] = true;
} }
return $style; return $style;
} else {
return null;
} }
return null;
} }
/** /**
* Load font style from SimpleXMLElement * Load font style from SimpleXMLElement
* *
* @param SimpleXMLElement $elm * @param SimpleXMLElement $elm
* @return array|string|null * @return array|string|null
*/ */
private function loadFontStyle($elm) private function loadFontStyle($elm)
{ {
@ -449,20 +437,19 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements
} }
} }
return $style; return $style;
} else {
return null;
} }
return null;
} }
/** /**
* Get array item * Get array item
* *
* @param array $array * @param array $array
* @param mixed $key * @param mixed $key
* @return mixed|null * @return mixed|null
*/ */
private static function arrayItem($array, $key = 0) private static function arrayItem($array, $key = 0)
{ {
return (isset($array[$key]) ? $array[$key] : null); return (isset($array[$key]) ? $array[$key] : null);
} }
} }

View File

@ -25,12 +25,13 @@
* @version 0.8.0 * @version 0.8.0
*/ */
use PhpOffice\PhpWord\Exceptions\Exception;
/** /**
* Class PHPWord_Section * Class PHPWord_Section
*/ */
class PHPWord_Section class PHPWord_Section
{ {
/** /**
* Section count * Section count
* *
@ -83,7 +84,7 @@ class PHPWord_Section
/** /**
* Set Section Settings * Set Section Settings
* *
* @param array $settings * @param array $settings
*/ */
public function setSettings($settings = null) public function setSettings($settings = null)
{ {
@ -157,8 +158,8 @@ class PHPWord_Section
* Add a TextBreak Element * Add a TextBreak Element
* *
* @param int $count * @param int $count
* @param null|string|array|PHPWord_Style_Font $fontStyle * @param null|string|array|PHPWord_Style_Font $fontStyle
* @param null|string|array|PHPWord_Style_Paragraph $paragraphStyle * @param null|string|array|PHPWord_Style_Paragraph $paragraphStyle
*/ */
public function addTextBreak($count = 1, $fontStyle = null, $paragraphStyle = null) public function addTextBreak($count = 1, $fontStyle = null, $paragraphStyle = null)
{ {
@ -214,6 +215,7 @@ class PHPWord_Section
* @param string $src * @param string $src
* @param mixed $style * @param mixed $style
* @return PHPWord_Section_Object * @return PHPWord_Section_Object
* @throws Exception
*/ */
public function addObject($src, $style = null) public function addObject($src, $style = null)
{ {
@ -244,11 +246,8 @@ class PHPWord_Section
$this->_elementCollection[] = $object; $this->_elementCollection[] = $object;
return $object; return $object;
} else {
throw new PHPWord_Exception(
'Source does not exist or unsupported object type.'
);
} }
throw new Exception('Source does not exist or unsupported object type.');
} }
/** /**
@ -257,6 +256,7 @@ class PHPWord_Section
* @param string $src * @param string $src
* @param mixed $style * @param mixed $style
* @return PHPWord_Section_Image * @return PHPWord_Section_Image
* @throws Exception
*/ */
public function addImage($src, $style = null) public function addImage($src, $style = null)
{ {
@ -268,11 +268,8 @@ class PHPWord_Section
$this->_elementCollection[] = $image; $this->_elementCollection[] = $image;
return $image; return $image;
} else {
throw new PHPWord_Exception(
'Source does not exist or unsupported image type.'
);
} }
throw new Exception('Source does not exist or unsupported image type.');
} }
/** /**
@ -281,6 +278,7 @@ class PHPWord_Section
* @param string $link * @param string $link
* @param mixed $style * @param mixed $style
* @return PHPWord_Section_MemoryImage * @return PHPWord_Section_MemoryImage
* @throws Exception
*/ */
public function addMemoryImage($link, $style = null) public function addMemoryImage($link, $style = null)
{ {
@ -291,11 +289,8 @@ class PHPWord_Section
$this->_elementCollection[] = $memoryImage; $this->_elementCollection[] = $memoryImage;
return $memoryImage; return $memoryImage;
} else {
throw new PHPWord_Exception(
'Unsupported image type.'
);
} }
throw new Exception('Unsupported image type.');
} }
/** /**
@ -347,6 +342,7 @@ class PHPWord_Section
/** /**
* Create a new TextRun * Create a new TextRun
* *
* @param mixed $styleParagraph
* @return PHPWord_Section_TextRun * @return PHPWord_Section_TextRun
*/ */
public function createTextRun($styleParagraph = null) public function createTextRun($styleParagraph = null)
@ -430,7 +426,7 @@ class PHPWord_Section
/** /**
* Create a new Footnote Element * Create a new Footnote Element
* *
* @param string $text * @param mixed $styleParagraph
* @return PHPWord_Section_Footnote * @return PHPWord_Section_Footnote
*/ */
public function createFootnote($styleParagraph = null) public function createFootnote($styleParagraph = null)
@ -441,4 +437,4 @@ class PHPWord_Section
$this->_elementCollection[] = $footnote; $this->_elementCollection[] = $footnote;
return $footnote; return $footnote;
} }
} }

View File

@ -50,8 +50,7 @@ class PHPWord_Settings
return true; return true;
} }
return false; return false;
} // function setCompatibility() }
/** /**
* Return the compatibility option used by the XMLWriter * Return the compatibility option used by the XMLWriter
@ -61,5 +60,5 @@ class PHPWord_Settings
public static function getCompatibility() public static function getCompatibility()
{ {
return self::$_xmlWriterCompatibility; return self::$_xmlWriterCompatibility;
} // function getCompatibility() }
} }

View File

@ -25,6 +25,8 @@
* @version 0.8.0 * @version 0.8.0
*/ */
use PhpOffice\PhpWord\Exceptions\Exception;
/** /**
* PHPWord_DocumentProperties * PHPWord_DocumentProperties
*/ */
@ -57,50 +59,52 @@ class PHPWord_Template
* Create a new Template Object * Create a new Template Object
* *
* @param string $strFilename * @param string $strFilename
* @throws Exception
*/ */
public function __construct($strFilename) public function __construct($strFilename)
{ {
$this->_tempFileName = tempnam(sys_get_temp_dir(), ''); $this->_tempFileName = tempnam(sys_get_temp_dir(), '');
if ($this->_tempFileName !== false) { if ($this->_tempFileName === false) {
// Copy the source File to the temp File throw new Exception('Could not create temporary file with unique name in the default temporary directory.');
if (!copy($strFilename, $this->_tempFileName)) {
throw new PHPWord_Exception("Could not copy the template from {$strFilename} to {$this->_tempFileName}.");
}
$this->_objZip = new ZipArchive();
$this->_objZip->open($this->_tempFileName);
$this->_documentXML = $this->_objZip->getFromName('word/document.xml');
} else {
throw new PHPWord_Exception('Could not create temporary file with unique name in the default temporary directory.');
} }
// Copy the source File to the temp File
if (!copy($strFilename, $this->_tempFileName)) {
throw new Exception("Could not copy the template from {$strFilename} to {$this->_tempFileName}.");
}
$this->_objZip = new ZipArchive();
$this->_objZip->open($this->_tempFileName);
$this->_documentXML = $this->_objZip->getFromName('word/document.xml');
} }
/** /**
* Applies XSL style sheet to template's parts * Applies XSL style sheet to template's parts
* *
* @param DOMDocument &$xslDOMDocument * @param DOMDocument $xslDOMDocument
* @param array $xslOptions = array() * @param array $xslOptions
* @param string $xslOptionsURI = '' * @param string $xslOptionsURI
* @throws Exception
*/ */
public function applyXslStyleSheet(&$xslDOMDocument, $xslOptions = array(), $xslOptionsURI = '') public function applyXslStyleSheet(&$xslDOMDocument, $xslOptions = array(), $xslOptionsURI = '')
{ {
$processor = new \XSLTProcessor(); $processor = new XSLTProcessor();
$processor->importStylesheet($xslDOMDocument); $processor->importStylesheet($xslDOMDocument);
if ($processor->setParameter($xslOptionsURI, $xslOptions) === false) { if ($processor->setParameter($xslOptionsURI, $xslOptions) === false) {
throw new \Exception('Could not set values for the given XSL style sheet parameters.'); throw new Exception('Could not set values for the given XSL style sheet parameters.');
} }
$xmlDOMDocument = new \DOMDocument(); $xmlDOMDocument = new DOMDocument();
if ($xmlDOMDocument->loadXML($this->_documentXML) === false) { if ($xmlDOMDocument->loadXML($this->_documentXML) === false) {
throw new \Exception('Could not load XML from the given template.'); throw new Exception('Could not load XML from the given template.');
} }
$xmlTransformed = $processor->transformToXml($xmlDOMDocument); $xmlTransformed = $processor->transformToXml($xmlDOMDocument);
if ($xmlTransformed === false) { if ($xmlTransformed === false) {
throw new \Exception('Could not transform the given XML document.'); throw new Exception('Could not transform the given XML document.');
} }
$this->_documentXML = $xmlTransformed; $this->_documentXML = $xmlTransformed;
@ -155,7 +159,9 @@ class PHPWord_Template
/** /**
* Find the start position of the nearest table row before $offset * Find the start position of the nearest table row before $offset
* *
* @param mixed $offset * @param int $offset
* @return int
* @throws Exception
*/ */
private function _findRowStart($offset) private function _findRowStart($offset)
{ {
@ -165,7 +171,6 @@ class PHPWord_Template
} }
if (!$rowStart) { if (!$rowStart) {
throw new Exception("Can not find the start position of the row to clone."); throw new Exception("Can not find the start position of the row to clone.");
return false;
} }
return $rowStart; return $rowStart;
} }
@ -173,7 +178,8 @@ class PHPWord_Template
/** /**
* Find the end position of the nearest table row after $offset * Find the end position of the nearest table row after $offset
* *
* @param mixed $offset * @param int $offset
* @return int
*/ */
private function _findRowEnd($offset) private function _findRowEnd($offset)
{ {
@ -184,7 +190,9 @@ class PHPWord_Template
/** /**
* Get a slice of a string * Get a slice of a string
* *
* @param mixed $offset * @param int $startPosition
* @param int $endPosition
* @return string
*/ */
private function _getSlice($startPosition, $endPosition = 0) private function _getSlice($startPosition, $endPosition = 0)
{ {
@ -197,32 +205,32 @@ class PHPWord_Template
/** /**
* Clone a table row in a template document * Clone a table row in a template document
* *
* @param mixed $search * @param string $search
* @param mixed $numberOfClones * @param int $numberOfClones
* @throws Exception
*/ */
public function cloneRow($search, $numberOfClones) public function cloneRow($search, $numberOfClones)
{ {
if (substr($search, 0, 2) !== '${' && substr($search, -1) !== '}') { if (substr($search, 0, 2) !== '${' && substr($search, -1) !== '}') {
$search = '${'.$search.'}'; $search = '${' . $search . '}';
} }
$tagPos = strpos($this->_documentXML, $search); $tagPos = strpos($this->_documentXML, $search);
if (!$tagPos) { if (!$tagPos) {
throw new Exception("Can not clone row, template variable not found or variable contains markup."); throw new Exception("Can not clone row, template variable not found or variable contains markup.");
return false;
} }
$rowStart = $this->_findRowStart($tagPos); $rowStart = $this->_findRowStart($tagPos);
$rowEnd = $this->_findRowEnd($tagPos); $rowEnd = $this->_findRowEnd($tagPos);
$xmlRow = $this->_getSlice($rowStart, $rowEnd); $xmlRow = $this->_getSlice($rowStart, $rowEnd);
// Check if there's a cell spanning multiple rows. // Check if there's a cell spanning multiple rows.
if (preg_match('#<w:vMerge w:val="restart"/>#', $xmlRow)) { if (preg_match('#<w:vMerge w:val="restart"/>#', $xmlRow)) {
$extraRowStart = $rowEnd; $extraRowStart = $rowEnd;
$extraRowEnd = $rowEnd; $extraRowEnd = $rowEnd;
while (true) { while (true) {
$extraRowStart = $this->_findRowStart($extraRowEnd + 1); $extraRowStart = $this->_findRowStart($extraRowEnd + 1);
$extraRowEnd = $this->_findRowEnd($extraRowEnd + 1); $extraRowEnd = $this->_findRowEnd($extraRowEnd + 1);
// If extraRowEnd is lower then 7, there was no next row found. // If extraRowEnd is lower then 7, there was no next row found.
if ($extraRowEnd < 7) { if ($extraRowEnd < 7) {
@ -230,7 +238,7 @@ class PHPWord_Template
} }
// If tmpXmlRow doesn't contain continue, this row is no longer part of the spanned row. // If tmpXmlRow doesn't contain continue, this row is no longer part of the spanned row.
$tmpXmlRow = $this->_getSlice($extraRowStart, $extraRowEnd); $tmpXmlRow = $this->_getSlice($extraRowStart, $extraRowEnd);
if (!preg_match('#<w:vMerge/>#', $tmpXmlRow) && !preg_match('#<w:vMerge w:val="continue" />#', $tmpXmlRow)) { if (!preg_match('#<w:vMerge/>#', $tmpXmlRow) && !preg_match('#<w:vMerge w:val="continue" />#', $tmpXmlRow)) {
break; break;
} }
@ -242,7 +250,7 @@ class PHPWord_Template
$result = $this->_getSlice(0, $rowStart); $result = $this->_getSlice(0, $rowStart);
for ($i = 1; $i <= $numberOfClones; $i++) { for ($i = 1; $i <= $numberOfClones; $i++) {
$result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#'.$i.'}', $xmlRow); $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlRow);
} }
$result .= $this->_getSlice($rowEnd); $result .= $this->_getSlice($rowEnd);
@ -253,6 +261,7 @@ class PHPWord_Template
* Save Template * Save Template
* *
* @return string * @return string
* @throws Exception
*/ */
public function save() public function save()
{ {
@ -281,4 +290,4 @@ class PHPWord_Template
rename($tempFilename, $strFilename); rename($tempFilename, $strFilename);
} }
} }

View File

@ -0,0 +1,16 @@
<?php
namespace PHPWord\Tests\Exceptions;
use PhpOffice\PhpWord\Exceptions\Exception;
class ExceptionTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \PhpOffice\PhpWord\Exceptions\Exception
* @covers \PhpOffice\PhpWord\Exceptions\Exception
*/
public function testThrowException()
{
throw new Exception;
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace PHPWord\Tests\Exceptions;
use PhpOffice\PhpWord\Exceptions\InvalidImageException;
class InvalidImageExceptionTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \PhpOffice\PhpWord\Exceptions\InvalidImageException
* @covers \PhpOffice\PhpWord\Exceptions\InvalidImageException
*/
public function testThrowException()
{
throw new InvalidImageException;
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace PHPWord\Tests\Exceptions;
use PhpOffice\PhpWord\Exceptions\InvalidStyleException;
class InvalidStyleExceptionTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \PhpOffice\PhpWord\Exceptions\InvalidStyleException
* @covers \PhpOffice\PhpWord\Exceptions\InvalidStyleException
*/
public function testThrowException()
{
throw new InvalidStyleException;
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace PHPWord\Tests\Exceptions;
use PhpOffice\PhpWord\Exceptions\UnsupportedImageTypeException;
class UnsupportedImageTypeExceptionTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \PhpOffice\PhpWord\Exceptions\UnsupportedImageTypeException
* @covers \PhpOffice\PhpWord\Exceptions\UnsupportedImageTypeException
*/
public function testThrowException()
{
throw new UnsupportedImageTypeException;
}
}

View File

@ -28,15 +28,6 @@ class IOFactoryTest extends \PHPUnit_Framework_TestCase
$this->assertAttributeEquals(array(), '_searchLocations', 'PHPWord_IOFactory'); $this->assertAttributeEquals(array(), '_searchLocations', 'PHPWord_IOFactory');
} }
/**
* @expectedException Exception
* @expectedExceptionMessage Invalid parameter passed.
*/
public function testSetSearchLocationsWithNotArray()
{
PHPWord_IOFactory::setSearchLocations('String');
}
public function testAddSearchLocation() public function testAddSearchLocation()
{ {
PHPWord_IOFactory::setSearchLocations(array()); PHPWord_IOFactory::setSearchLocations(array());
@ -69,4 +60,4 @@ class IOFactoryTest extends \PHPUnit_Framework_TestCase
new PHPWord_Writer_Word2007($oPHPWord) new PHPWord_Writer_Word2007($oPHPWord)
); );
} }
} }