From 3b7dac452bba46c740b202a659e5fb09c13d7ace Mon Sep 17 00:00:00 2001 From: Gabriel Bull Date: Sat, 15 Mar 2014 09:27:48 -0400 Subject: [PATCH] Refactored PHPWord_Exception to namespaces --- Classes/PHPWord.php | 8 +- Classes/PHPWord/Exception.php | 49 ---------- Classes/PHPWord/Exceptions/Exception.php | 9 ++ .../Exceptions/InvalidImageException.php | 2 - .../Exceptions/InvalidStyleException.php | 2 +- .../UnsupportedImageTypeException.php | 2 - Classes/PHPWord/IOFactory.php | 26 ++--- Classes/PHPWord/Reader/Abstract.php | 29 +++--- Classes/PHPWord/Reader/Word2007.php | 97 ++++++++----------- Classes/PHPWord/Section.php | 32 +++--- Classes/PHPWord/Settings.php | 7 +- Classes/PHPWord/Template.php | 83 +++++++++------- Tests/PHPWord/Exceptions/ExceptionTest.php | 16 +++ .../Exceptions/InvalidImageExceptionTest.php | 16 +++ .../Exceptions/InvalidStyleExceptionTest.php | 16 +++ .../UnsupportedImageTypeExceptionTest.php | 16 +++ Tests/PHPWord/IOFactoryTest.php | 11 +-- 17 files changed, 213 insertions(+), 208 deletions(-) delete mode 100755 Classes/PHPWord/Exception.php create mode 100755 Classes/PHPWord/Exceptions/Exception.php create mode 100644 Tests/PHPWord/Exceptions/ExceptionTest.php create mode 100644 Tests/PHPWord/Exceptions/InvalidImageExceptionTest.php create mode 100644 Tests/PHPWord/Exceptions/InvalidStyleExceptionTest.php create mode 100644 Tests/PHPWord/Exceptions/UnsupportedImageTypeExceptionTest.php diff --git a/Classes/PHPWord.php b/Classes/PHPWord.php index 43ba3e7e..d591b94e 100755 --- a/Classes/PHPWord.php +++ b/Classes/PHPWord.php @@ -34,6 +34,8 @@ if (!defined('PHPWORD_BASE_PATH')) { } // @codeCoverageIgnoreEnd +use PhpOffice\PhpWord\Exceptions\Exception; + /** * PHPWord */ @@ -252,17 +254,15 @@ class PHPWord * * @param string $strFilename * @return PHPWord_Template + * @throws Exception */ public function loadTemplate($strFilename) { if (file_exists($strFilename)) { $template = new PHPWord_Template($strFilename); return $template; - } else { - throw new PHPWord_Exception( - "Template file {$strFilename} not found." - ); } + throw new Exception("Template file {$strFilename} not found."); } /** diff --git a/Classes/PHPWord/Exception.php b/Classes/PHPWord/Exception.php deleted file mode 100755 index d6a90510..00000000 --- a/Classes/PHPWord/Exception.php +++ /dev/null @@ -1,49 +0,0 @@ -line = $line; - $e->file = $file; - throw $e; - } -} diff --git a/Classes/PHPWord/Exceptions/Exception.php b/Classes/PHPWord/Exceptions/Exception.php new file mode 100755 index 00000000..11cb0516 --- /dev/null +++ b/Classes/PHPWord/Exceptions/Exception.php @@ -0,0 +1,9 @@ +load($pFilename); } -} +} \ No newline at end of file diff --git a/Classes/PHPWord/Reader/Abstract.php b/Classes/PHPWord/Reader/Abstract.php index 8c185cb2..ba7f6565 100644 --- a/Classes/PHPWord/Reader/Abstract.php +++ b/Classes/PHPWord/Reader/Abstract.php @@ -25,6 +25,8 @@ * @version 0.8.0 */ +use PhpOffice\PhpWord\Exceptions\Exception; + /** * PHPWord_Reader_Abstract * @@ -35,17 +37,19 @@ abstract class PHPWord_Reader_Abstract implements PHPWord_Reader_IReader /** * Read data only? * - * @var boolean + * @var bool */ protected $readDataOnly = true; + /** + * @var bool|resource + */ protected $fileHandle = true; - /** * Read data only? * - * @return boolean + * @return bool */ public function getReadDataOnly() { @@ -56,8 +60,8 @@ abstract class PHPWord_Reader_Abstract implements PHPWord_Reader_IReader /** * Set read data only * - * @param boolean $pValue - * @return PHPWord_Reader_IReader + * @param bool $pValue + * @return PHPWord_Reader_IReader */ public function setReadDataOnly($pValue = true) { @@ -69,29 +73,28 @@ abstract class PHPWord_Reader_Abstract implements PHPWord_Reader_IReader * Open file for reading * * @param string $pFilename - * @throws PHPWord_Exception * @return resource + * @throws Exception */ protected function openFile($pFilename) { // Check if file exists 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 $this->fileHandle = fopen($pFilename, 'r'); 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? * - * @param string $pFilename - * @return boolean - * @throws PHPWord_Exception + * @param string $pFilename + * @return bool */ public function canRead($pFilename) { @@ -102,6 +105,6 @@ abstract class PHPWord_Reader_Abstract implements PHPWord_Reader_IReader return false; } fclose($this->fileHandle); - return $readable; + return true; } -} +} \ No newline at end of file diff --git a/Classes/PHPWord/Reader/Word2007.php b/Classes/PHPWord/Reader/Word2007.php index b217a018..1aa94f86 100644 --- a/Classes/PHPWord/Reader/Word2007.php +++ b/Classes/PHPWord/Reader/Word2007.php @@ -31,32 +31,25 @@ if (!defined('PHPWORD_BASE_PATH')) { require(PHPWORD_BASE_PATH . 'PHPWord/Autoloader.php'); } +use PhpOffice\PhpWord\Exceptions\Exception; + /** * PHPWord_Reader_Word2007 */ -class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements - PHPWord_Reader_IReader +class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements PHPWord_Reader_IReader { - /** - * Create a new PHPWord_Reader_Word2007 instance - */ - public function __construct() - { - } - /** * Can the current PHPWord_Reader_IReader read the file? * - * @param string $pFilename - * @return bool + * @param string $pFilename + * @return bool + * @throws Exception */ public function canRead($pFilename) { // Check if file exists if (!file_exists($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."); } $return = false; @@ -86,15 +79,13 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements /** * Get from zip archive * - * @param ZipArchive $archive - * @param string $fileName - * @param bool $removeNamespace + * @param ZipArchive $archive + * @param string $fileName + * @param bool $removeNamespace + * @return mixed */ - public function getFromZipArchive( - $archive, - $fileName = '', - $removeNamespace = false - ) { + public function getFromZipArchive($archive, $fileName = '', $removeNamespace = false) + { // Root-relative paths if (strpos($fileName, '//') !== false) { $fileName = substr($fileName, strpos($fileName, '//') + 1); @@ -115,18 +106,17 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements return $contents; } - /** * Loads PHPWord from file * - * @param string $pFilename - * @return PHPWord|null + * @param string $pFilename + * @return PHPWord|null */ public function load($pFilename) { // Check if file exists and can be read if (!$this->canRead($pFilename)) { - return; + return null; } // Initialisations @@ -146,15 +136,15 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements $xmlCore->registerXPathNamespace("dcterms", "http://purl.org/dc/terms/"); $xmlCore->registerXPathNamespace("cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"); $docProps = $word->getProperties(); - $docProps->setCreator((string) self::arrayItem($xmlCore->xpath("dc:creator"))); - $docProps->setLastModifiedBy((string) self::arrayItem($xmlCore->xpath("cp:lastModifiedBy"))); + $docProps->setCreator((string)self::arrayItem($xmlCore->xpath("dc:creator"))); + $docProps->setLastModifiedBy((string)self::arrayItem($xmlCore->xpath("cp:lastModifiedBy"))); $docProps->setCreated(strtotime(self::arrayItem($xmlCore->xpath("dcterms:created")))); $docProps->setModified(strtotime(self::arrayItem($xmlCore->xpath("dcterms:modified")))); - $docProps->setTitle((string) self::arrayItem($xmlCore->xpath("dc:title"))); - $docProps->setDescription((string) self::arrayItem($xmlCore->xpath("dc:description"))); - $docProps->setSubject((string) self::arrayItem($xmlCore->xpath("dc:subject"))); - $docProps->setKeywords((string) self::arrayItem($xmlCore->xpath("cp:keywords"))); - $docProps->setCategory((string) self::arrayItem($xmlCore->xpath("cp:category"))); + $docProps->setTitle((string)self::arrayItem($xmlCore->xpath("dc:title"))); + $docProps->setDescription((string)self::arrayItem($xmlCore->xpath("dc:description"))); + $docProps->setSubject((string)self::arrayItem($xmlCore->xpath("dc:subject"))); + $docProps->setKeywords((string)self::arrayItem($xmlCore->xpath("cp:keywords"))); + $docProps->setCategory((string)self::arrayItem($xmlCore->xpath("cp:category"))); } break; // Extended properties @@ -163,10 +153,10 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements if (is_object($xmlCore)) { $docProps = $word->getProperties(); if (isset($xmlCore->Company)) { - $docProps->setCompany((string) $xmlCore->Company); + $docProps->setCompany((string)$xmlCore->Company); } if (isset($xmlCore->Manager)) { - $docProps->setManager((string) $xmlCore->Manager); + $docProps->setManager((string)$xmlCore->Manager); } } break; @@ -178,10 +168,10 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements foreach ($xmlCore as $xmlProperty) { $cellDataOfficeAttributes = $xmlProperty->attributes(); if (isset($cellDataOfficeAttributes['name'])) { - $propertyName = (string) $cellDataOfficeAttributes['name']; + $propertyName = (string)$cellDataOfficeAttributes['name']; $cellDataOfficeChildren = $xmlProperty->children("http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"); $attributeType = $cellDataOfficeChildren->getName(); - $attributeValue = (string) $cellDataOfficeChildren->{$attributeType}; + $attributeValue = (string)$cellDataOfficeChildren->{$attributeType}; $attributeValue = PHPWord_DocumentProperties::convertProperty($attributeValue, $attributeType); $attributeType = PHPWord_DocumentProperties::convertPropertyType($attributeType); $docProps->setCustomProperty($propertyName, $attributeValue, $attributeType); @@ -219,7 +209,7 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements $elm->r->t, $this->loadFontStyle($elm->r) ); - // w:r more than 1? It's a textrun + // w:r more than 1? It's a textrun } else { $textRun = $section->createTextRun(); 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 { $section->addTextBreak(); } @@ -282,8 +272,8 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements /** * Load section settings from SimpleXMLElement * - * @param SimpleXMLElement $elm - * @return array|string|null + * @param SimpleXMLElement $elm + * @return array|string|null * * @todo Implement gutter */ @@ -337,16 +327,15 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements } } return $setting; - } else { - return null; } + return null; } /** * Load paragraph style from SimpleXMLElement * - * @param SimpleXMLElement $elm - * @return array|string|null + * @param SimpleXMLElement $elm + * @return array|string|null */ private function loadParagraphStyle($elm) { @@ -399,16 +388,15 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements $style['pageBreakBefore'] = true; } return $style; - } else { - return null; } + return null; } /** * Load font style from SimpleXMLElement * - * @param SimpleXMLElement $elm - * @return array|string|null + * @param SimpleXMLElement $elm + * @return array|string|null */ private function loadFontStyle($elm) { @@ -449,20 +437,19 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements } } return $style; - } else { - return null; } + return null; } /** * Get array item * - * @param array $array - * @param mixed $key - * @return mixed|null + * @param array $array + * @param mixed $key + * @return mixed|null */ private static function arrayItem($array, $key = 0) { return (isset($array[$key]) ? $array[$key] : null); } -} +} \ No newline at end of file diff --git a/Classes/PHPWord/Section.php b/Classes/PHPWord/Section.php index 07a17a31..a9402dab 100755 --- a/Classes/PHPWord/Section.php +++ b/Classes/PHPWord/Section.php @@ -25,12 +25,13 @@ * @version 0.8.0 */ +use PhpOffice\PhpWord\Exceptions\Exception; + /** * Class PHPWord_Section */ class PHPWord_Section { - /** * Section count * @@ -83,7 +84,7 @@ class PHPWord_Section /** * Set Section Settings * - * @param array $settings + * @param array $settings */ public function setSettings($settings = null) { @@ -157,8 +158,8 @@ class PHPWord_Section * Add a TextBreak Element * * @param int $count - * @param null|string|array|PHPWord_Style_Font $fontStyle - * @param null|string|array|PHPWord_Style_Paragraph $paragraphStyle + * @param null|string|array|PHPWord_Style_Font $fontStyle + * @param null|string|array|PHPWord_Style_Paragraph $paragraphStyle */ public function addTextBreak($count = 1, $fontStyle = null, $paragraphStyle = null) { @@ -214,6 +215,7 @@ class PHPWord_Section * @param string $src * @param mixed $style * @return PHPWord_Section_Object + * @throws Exception */ public function addObject($src, $style = null) { @@ -244,11 +246,8 @@ class PHPWord_Section $this->_elementCollection[] = $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 mixed $style * @return PHPWord_Section_Image + * @throws Exception */ public function addImage($src, $style = null) { @@ -268,11 +268,8 @@ class PHPWord_Section $this->_elementCollection[] = $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 mixed $style * @return PHPWord_Section_MemoryImage + * @throws Exception */ public function addMemoryImage($link, $style = null) { @@ -291,11 +289,8 @@ class PHPWord_Section $this->_elementCollection[] = $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 * + * @param mixed $styleParagraph * @return PHPWord_Section_TextRun */ public function createTextRun($styleParagraph = null) @@ -430,7 +426,7 @@ class PHPWord_Section /** * Create a new Footnote Element * - * @param string $text + * @param mixed $styleParagraph * @return PHPWord_Section_Footnote */ public function createFootnote($styleParagraph = null) @@ -441,4 +437,4 @@ class PHPWord_Section $this->_elementCollection[] = $footnote; return $footnote; } -} +} \ No newline at end of file diff --git a/Classes/PHPWord/Settings.php b/Classes/PHPWord/Settings.php index 241694f6..0869f215 100644 --- a/Classes/PHPWord/Settings.php +++ b/Classes/PHPWord/Settings.php @@ -50,8 +50,7 @@ class PHPWord_Settings return true; } return false; - } // function setCompatibility() - + } /** * Return the compatibility option used by the XMLWriter @@ -61,5 +60,5 @@ class PHPWord_Settings public static function getCompatibility() { return self::$_xmlWriterCompatibility; - } // function getCompatibility() -} + } +} \ No newline at end of file diff --git a/Classes/PHPWord/Template.php b/Classes/PHPWord/Template.php index 9db3edba..752fa792 100755 --- a/Classes/PHPWord/Template.php +++ b/Classes/PHPWord/Template.php @@ -25,6 +25,8 @@ * @version 0.8.0 */ +use PhpOffice\PhpWord\Exceptions\Exception; + /** * PHPWord_DocumentProperties */ @@ -57,50 +59,52 @@ class PHPWord_Template * Create a new Template Object * * @param string $strFilename + * @throws Exception */ public function __construct($strFilename) { $this->_tempFileName = tempnam(sys_get_temp_dir(), ''); - if ($this->_tempFileName !== false) { - // Copy the source File to the temp File - 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.'); + if ($this->_tempFileName === false) { + throw new 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 * - * @param DOMDocument &$xslDOMDocument - * @param array $xslOptions = array() - * @param string $xslOptionsURI = '' + * @param DOMDocument $xslDOMDocument + * @param array $xslOptions + * @param string $xslOptionsURI + * @throws Exception */ public function applyXslStyleSheet(&$xslDOMDocument, $xslOptions = array(), $xslOptionsURI = '') { - $processor = new \XSLTProcessor(); + $processor = new XSLTProcessor(); $processor->importStylesheet($xslDOMDocument); 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) { - 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); 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; @@ -155,7 +159,9 @@ class PHPWord_Template /** * 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) { @@ -165,7 +171,6 @@ class PHPWord_Template } if (!$rowStart) { throw new Exception("Can not find the start position of the row to clone."); - return false; } return $rowStart; } @@ -173,7 +178,8 @@ class PHPWord_Template /** * Find the end position of the nearest table row after $offset * - * @param mixed $offset + * @param int $offset + * @return int */ private function _findRowEnd($offset) { @@ -184,7 +190,9 @@ class PHPWord_Template /** * Get a slice of a string * - * @param mixed $offset + * @param int $startPosition + * @param int $endPosition + * @return string */ private function _getSlice($startPosition, $endPosition = 0) { @@ -197,32 +205,32 @@ class PHPWord_Template /** * Clone a table row in a template document * - * @param mixed $search - * @param mixed $numberOfClones + * @param string $search + * @param int $numberOfClones + * @throws Exception */ public function cloneRow($search, $numberOfClones) { if (substr($search, 0, 2) !== '${' && substr($search, -1) !== '}') { - $search = '${'.$search.'}'; + $search = '${' . $search . '}'; } $tagPos = strpos($this->_documentXML, $search); if (!$tagPos) { throw new Exception("Can not clone row, template variable not found or variable contains markup."); - return false; } $rowStart = $this->_findRowStart($tagPos); - $rowEnd = $this->_findRowEnd($tagPos); - $xmlRow = $this->_getSlice($rowStart, $rowEnd); + $rowEnd = $this->_findRowEnd($tagPos); + $xmlRow = $this->_getSlice($rowStart, $rowEnd); // Check if there's a cell spanning multiple rows. if (preg_match('##', $xmlRow)) { - $extraRowStart = $rowEnd; - $extraRowEnd = $rowEnd; + $extraRowStart = $rowEnd; + $extraRowEnd = $rowEnd; while (true) { - $extraRowStart = $this->_findRowStart($extraRowEnd + 1); - $extraRowEnd = $this->_findRowEnd($extraRowEnd + 1); + $extraRowStart = $this->_findRowStart($extraRowEnd + 1); + $extraRowEnd = $this->_findRowEnd($extraRowEnd + 1); // If extraRowEnd is lower then 7, there was no next row found. 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. - $tmpXmlRow = $this->_getSlice($extraRowStart, $extraRowEnd); + $tmpXmlRow = $this->_getSlice($extraRowStart, $extraRowEnd); if (!preg_match('##', $tmpXmlRow) && !preg_match('##', $tmpXmlRow)) { break; } @@ -242,7 +250,7 @@ class PHPWord_Template $result = $this->_getSlice(0, $rowStart); for ($i = 1; $i <= $numberOfClones; $i++) { - $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#'.$i.'}', $xmlRow); + $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlRow); } $result .= $this->_getSlice($rowEnd); @@ -253,6 +261,7 @@ class PHPWord_Template * Save Template * * @return string + * @throws Exception */ public function save() { @@ -281,4 +290,4 @@ class PHPWord_Template rename($tempFilename, $strFilename); } -} +} \ No newline at end of file diff --git a/Tests/PHPWord/Exceptions/ExceptionTest.php b/Tests/PHPWord/Exceptions/ExceptionTest.php new file mode 100644 index 00000000..a403aa28 --- /dev/null +++ b/Tests/PHPWord/Exceptions/ExceptionTest.php @@ -0,0 +1,16 @@ +assertAttributeEquals(array(), '_searchLocations', 'PHPWord_IOFactory'); } - /** - * @expectedException Exception - * @expectedExceptionMessage Invalid parameter passed. - */ - public function testSetSearchLocationsWithNotArray() - { - PHPWord_IOFactory::setSearchLocations('String'); - } - public function testAddSearchLocation() { PHPWord_IOFactory::setSearchLocations(array()); @@ -69,4 +60,4 @@ class IOFactoryTest extends \PHPUnit_Framework_TestCase new PHPWord_Writer_Word2007($oPHPWord) ); } -} +} \ No newline at end of file