| 1 |
<?php |
| 2 |
|
| 3 |
namespace Box\Spout\Reader\Wrapper; |
| 4 |
|
| 5 |
use Box\Spout\Reader\Exception\XMLProcessingException; |
| 6 |
|
| 7 |
/** |
| 8 |
* Trait XMLInternalErrorsHelper |
| 9 |
* |
| 10 |
* @package Box\Spout\Reader\Wrapper |
| 11 |
*/ |
| 12 |
trait XMLInternalErrorsHelper |
| 13 |
{ |
| 14 |
/** @var bool Stores whether XML errors were initially stored internally - used to reset */ |
| 15 |
protected $initialUseInternalErrorsValue; |
| 16 |
|
| 17 |
/** |
| 18 |
* To avoid displaying lots of warning/error messages on screen, |
| 19 |
* stores errors internally instead. |
| 20 |
* |
| 21 |
* @return void |
| 22 |
*/ |
| 23 |
protected function useXMLInternalErrors() |
| 24 |
{ |
| 25 |
libxml_clear_errors(); |
| 26 |
$this->initialUseInternalErrorsValue = libxml_use_internal_errors(true); |
| 27 |
} |
| 28 |
|
| 29 |
/** |
| 30 |
* Throws an XMLProcessingException if an error occured. |
| 31 |
* It also always resets the "libxml_use_internal_errors" setting back to its initial value. |
| 32 |
* |
| 33 |
* @return void |
| 34 |
* @throws \Box\Spout\Reader\Exception\XMLProcessingException |
| 35 |
*/ |
| 36 |
protected function resetXMLInternalErrorsSettingAndThrowIfXMLErrorOccured() |
| 37 |
{ |
| 38 |
if ($this->hasXMLErrorOccured()) { |
| 39 |
$this->resetXMLInternalErrorsSetting(); |
| 40 |
throw new XMLProcessingException($this->getLastXMLErrorMessage()); |
| 41 |
} |
| 42 |
|
| 43 |
$this->resetXMLInternalErrorsSetting(); |
| 44 |
} |
| 45 |
|
| 46 |
/** |
| 47 |
* Returns whether the a XML error has occured since the last time errors were cleared. |
| 48 |
* |
| 49 |
* @return bool TRUE if an error occured, FALSE otherwise |
| 50 |
*/ |
| 51 |
private function hasXMLErrorOccured() |
| 52 |
{ |
| 53 |
return (libxml_get_last_error() !== false); |
| 54 |
} |
| 55 |
|
| 56 |
/** |
| 57 |
* Returns the error message for the last XML error that occured. |
| 58 |
* @see libxml_get_last_error |
| 59 |
* |
| 60 |
* @return String|null Last XML error message or null if no error |
| 61 |
*/ |
| 62 |
private function getLastXMLErrorMessage() |
| 63 |
{ |
| 64 |
$errorMessage = null; |
| 65 |
$error = libxml_get_last_error(); |
| 66 |
|
| 67 |
if ($error !== false) { |
| 68 |
$errorMessage = trim($error->message); |
| 69 |
} |
| 70 |
|
| 71 |
return $errorMessage; |
| 72 |
} |
| 73 |
|
| 74 |
/** |
| 75 |
* @return void |
| 76 |
*/ |
| 77 |
protected function resetXMLInternalErrorsSetting() |
| 78 |
{ |
| 79 |
libxml_use_internal_errors($this->initialUseInternalErrorsValue); |
| 80 |
} |
| 81 |
|
| 82 |
} |
| 83 |
|