Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.3.x will end 7 October 2024 (12 months).
  • Bug fixes for security issues in 4.3.x will end 21 April 2025 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.2.x is supported too.
   1  <?php
   2  
   3  declare(strict_types=1);
   4  
   5  namespace OpenSpout\Reader\Wrapper;
   6  
   7  use OpenSpout\Reader\Exception\XMLProcessingException;
   8  
   9  /**
  10   * @internal
  11   */
  12  trait XMLInternalErrorsHelper
  13  {
  14      /** @var bool Stores whether XML errors were initially stored internally - used to reset */
  15      private bool $initialUseInternalErrorsValue;
  16  
  17      /**
  18       * To avoid displaying lots of warning/error messages on screen,
  19       * stores errors internally instead.
  20       */
  21      private function useXMLInternalErrors(): void
  22      {
  23          libxml_clear_errors();
  24          $this->initialUseInternalErrorsValue = libxml_use_internal_errors(true);
  25      }
  26  
  27      /**
  28       * Throws an XMLProcessingException if an error occured.
  29       * It also always resets the "libxml_use_internal_errors" setting back to its initial value.
  30       *
  31       * @throws \OpenSpout\Reader\Exception\XMLProcessingException
  32       */
  33      private function resetXMLInternalErrorsSettingAndThrowIfXMLErrorOccured(): void
  34      {
  35          if ($this->hasXMLErrorOccured()) {
  36              $this->resetXMLInternalErrorsSetting();
  37  
  38              throw new XMLProcessingException($this->getLastXMLErrorMessage());
  39          }
  40  
  41          $this->resetXMLInternalErrorsSetting();
  42      }
  43  
  44      private function resetXMLInternalErrorsSetting(): void
  45      {
  46          libxml_use_internal_errors($this->initialUseInternalErrorsValue);
  47      }
  48  
  49      /**
  50       * Returns whether the a XML error has occured since the last time errors were cleared.
  51       *
  52       * @return bool TRUE if an error occured, FALSE otherwise
  53       */
  54      private function hasXMLErrorOccured(): bool
  55      {
  56          return false !== libxml_get_last_error();
  57      }
  58  
  59      /**
  60       * Returns the error message for the last XML error that occured.
  61       *
  62       * @see libxml_get_last_error
  63       *
  64       * @return string Last XML error message or null if no error
  65       */
  66      private function getLastXMLErrorMessage(): string
  67      {
  68          $errorMessage = '';
  69          $error = libxml_get_last_error();
  70  
  71          if (false !== $error) {
  72              $errorMessage = trim($error->message);
  73          }
  74  
  75          return $errorMessage;
  76      }
  77  }