[ Index ]

PHP Cross Reference of Unnamed Project

title

Body

[close]

/lib/spout/src/Spout/Writer/ -> AbstractWriter.php (source)

   1  <?php
   2  
   3  namespace Box\Spout\Writer;
   4  
   5  use Box\Spout\Common\Exception\IOException;
   6  use Box\Spout\Common\Exception\InvalidArgumentException;
   7  use Box\Spout\Writer\Exception\WriterAlreadyOpenedException;
   8  use Box\Spout\Writer\Exception\WriterNotOpenedException;
   9  use Box\Spout\Writer\Style\StyleBuilder;
  10  
  11  /**
  12   * Class AbstractWriter
  13   *
  14   * @package Box\Spout\Writer
  15   * @abstract
  16   */
  17  abstract class AbstractWriter implements WriterInterface
  18  {
  19      /** @var string Path to the output file */
  20      protected $outputFilePath;
  21  
  22      /** @var resource Pointer to the file/stream we will write to */
  23      protected $filePointer;
  24  
  25      /** @var bool Indicates whether the writer has been opened or not */
  26      protected $isWriterOpened = false;
  27  
  28      /** @var \Box\Spout\Common\Helper\GlobalFunctionsHelper Helper to work with global functions */
  29      protected $globalFunctionsHelper;
  30  
  31      /** @var Style\Style Style to be applied to the next written row(s) */
  32      protected $rowStyle;
  33  
  34      /** @var Style\Style Default row style. Each writer can have its own default style */
  35      protected $defaultRowStyle;
  36  
  37      /** @var string Content-Type value for the header - to be defined by child class */
  38      protected static $headerContentType;
  39  
  40      /**
  41       * Opens the streamer and makes it ready to accept data.
  42       *
  43       * @return void
  44       * @throws \Box\Spout\Common\Exception\IOException If the writer cannot be opened
  45       */
  46      abstract protected function openWriter();
  47  
  48      /**
  49       * Adds data to the currently openned writer.
  50       *
  51       * @param  array $dataRow Array containing data to be streamed.
  52       *          Example $dataRow = ['data1', 1234, null, '', 'data5'];
  53       * @param Style\Style $style Style to be applied to the written row
  54       * @return void
  55       */
  56      abstract protected function addRowToWriter(array $dataRow, $style);
  57  
  58      /**
  59       * Closes the streamer, preventing any additional writing.
  60       *
  61       * @return void
  62       */
  63      abstract protected function closeWriter();
  64  
  65      /**
  66       *
  67       */
  68      public function __construct()
  69      {
  70          $this->defaultRowStyle = $this->getDefaultRowStyle();
  71          $this->resetRowStyleToDefault();
  72      }
  73  
  74      /**
  75       * @param \Box\Spout\Common\Helper\GlobalFunctionsHelper $globalFunctionsHelper
  76       * @return AbstractWriter
  77       */
  78      public function setGlobalFunctionsHelper($globalFunctionsHelper)
  79      {
  80          $this->globalFunctionsHelper = $globalFunctionsHelper;
  81          return $this;
  82      }
  83  
  84      /**
  85       * Inits the writer and opens it to accept data.
  86       * By using this method, the data will be written to a file.
  87       *
  88       * @api
  89       * @param  string $outputFilePath Path of the output file that will contain the data
  90       * @return AbstractWriter
  91       * @throws \Box\Spout\Common\Exception\IOException If the writer cannot be opened or if the given path is not writable
  92       */
  93      public function openToFile($outputFilePath)
  94      {
  95          $this->outputFilePath = $outputFilePath;
  96  
  97          $this->filePointer = $this->globalFunctionsHelper->fopen($this->outputFilePath, 'wb+');
  98          $this->throwIfFilePointerIsNotAvailable();
  99  
 100          $this->openWriter();
 101          $this->isWriterOpened = true;
 102  
 103          return $this;
 104      }
 105  
 106      /**
 107       * Inits the writer and opens it to accept data.
 108       * By using this method, the data will be outputted directly to the browser.
 109       *
 110       * @codeCoverageIgnore
 111       *
 112       * @api
 113       * @param  string $outputFileName Name of the output file that will contain the data. If a path is passed in, only the file name will be kept
 114       * @return AbstractWriter
 115       * @throws \Box\Spout\Common\Exception\IOException If the writer cannot be opened
 116       */
 117      public function openToBrowser($outputFileName)
 118      {
 119          $this->outputFilePath = $this->globalFunctionsHelper->basename($outputFileName);
 120  
 121          $this->filePointer = $this->globalFunctionsHelper->fopen('php://output', 'w');
 122          $this->throwIfFilePointerIsNotAvailable();
 123  
 124          // Set headers
 125          $this->globalFunctionsHelper->header('Content-Type: ' . static::$headerContentType);
 126          $this->globalFunctionsHelper->header('Content-Disposition: attachment; filename="' . $this->outputFilePath . '"');
 127  
 128          /*
 129           * When forcing the download of a file over SSL,IE8 and lower browsers fail
 130           * if the Cache-Control and Pragma headers are not set.
 131           *
 132           * @see http://support.microsoft.com/KB/323308
 133           * @see https://github.com/liuggio/ExcelBundle/issues/45
 134           */
 135          $this->globalFunctionsHelper->header('Cache-Control: max-age=0');
 136          $this->globalFunctionsHelper->header('Pragma: public');
 137  
 138          $this->openWriter();
 139          $this->isWriterOpened = true;
 140  
 141          return $this;
 142      }
 143  
 144      /**
 145       * Checks if the pointer to the file/stream to write to is available.
 146       * Will throw an exception if not available.
 147       *
 148       * @return void
 149       * @throws \Box\Spout\Common\Exception\IOException If the pointer is not available
 150       */
 151      protected function throwIfFilePointerIsNotAvailable()
 152      {
 153          if (!$this->filePointer) {
 154              throw new IOException('File pointer has not be opened');
 155          }
 156      }
 157  
 158      /**
 159       * Checks if the writer has already been opened, since some actions must be done before it gets opened.
 160       * Throws an exception if already opened.
 161       *
 162       * @param string $message Error message
 163       * @return void
 164       * @throws \Box\Spout\Writer\Exception\WriterAlreadyOpenedException If the writer was already opened and must not be.
 165       */
 166      protected function throwIfWriterAlreadyOpened($message)
 167      {
 168          if ($this->isWriterOpened) {
 169              throw new WriterAlreadyOpenedException($message);
 170          }
 171      }
 172  
 173      /**
 174       * Write given data to the output. New data will be appended to end of stream.
 175       *
 176       * @param  array $dataRow Array containing data to be streamed.
 177       *                        If empty, no data is added (i.e. not even as a blank row)
 178       *                        Example: $dataRow = ['data1', 1234, null, '', 'data5', false];
 179       * @api
 180       * @return AbstractWriter
 181       * @throws \Box\Spout\Writer\Exception\WriterNotOpenedException If this function is called before opening the writer
 182       * @throws \Box\Spout\Common\Exception\IOException If unable to write data
 183       */
 184      public function addRow(array $dataRow)
 185      {
 186          if ($this->isWriterOpened) {
 187              // empty $dataRow should not add an empty line
 188              if (!empty($dataRow)) {
 189                  $this->addRowToWriter($dataRow, $this->rowStyle);
 190              }
 191          } else {
 192              throw new WriterNotOpenedException('The writer needs to be opened before adding row.');
 193          }
 194  
 195          return $this;
 196      }
 197  
 198      /**
 199       * Write given data to the output and apply the given style.
 200       * @see addRow
 201       *
 202       * @api
 203       * @param array $dataRow Array of array containing data to be streamed.
 204       * @param Style\Style $style Style to be applied to the row.
 205       * @return AbstractWriter
 206       * @throws \Box\Spout\Common\Exception\InvalidArgumentException If the input param is not valid
 207       * @throws \Box\Spout\Writer\Exception\WriterNotOpenedException If this function is called before opening the writer
 208       * @throws \Box\Spout\Common\Exception\IOException If unable to write data
 209       */
 210      public function addRowWithStyle(array $dataRow, $style)
 211      {
 212          if (!$style instanceof Style\Style) {
 213              throw new InvalidArgumentException('The "$style" argument must be a Style instance and cannot be NULL.');
 214          }
 215  
 216          $this->setRowStyle($style);
 217          $this->addRow($dataRow);
 218          $this->resetRowStyleToDefault();
 219  
 220          return $this;
 221      }
 222  
 223      /**
 224       * Write given data to the output. New data will be appended to end of stream.
 225       *
 226       * @api
 227       * @param  array $dataRows Array of array containing data to be streamed.
 228       *                         If a row is empty, it won't be added (i.e. not even as a blank row)
 229       *                         Example: $dataRows = [
 230       *                             ['data11', 12, , '', 'data13'],
 231       *                             ['data21', 'data22', null, false],
 232       *                         ];
 233       * @return AbstractWriter
 234       * @throws \Box\Spout\Common\Exception\InvalidArgumentException If the input param is not valid
 235       * @throws \Box\Spout\Writer\Exception\WriterNotOpenedException If this function is called before opening the writer
 236       * @throws \Box\Spout\Common\Exception\IOException If unable to write data
 237       */
 238      public function addRows(array $dataRows)
 239      {
 240          if (!empty($dataRows)) {
 241              if (!is_array($dataRows[0])) {
 242                  throw new InvalidArgumentException('The input should be an array of arrays');
 243              }
 244  
 245              foreach ($dataRows as $dataRow) {
 246                  $this->addRow($dataRow);
 247              }
 248          }
 249  
 250          return $this;
 251      }
 252  
 253      /**
 254       * Write given data to the output and apply the given style.
 255       * @see addRows
 256       *
 257       * @api
 258       * @param array $dataRows Array of array containing data to be streamed.
 259       * @param Style\Style $style Style to be applied to the rows.
 260       * @return AbstractWriter
 261       * @throws \Box\Spout\Common\Exception\InvalidArgumentException If the input param is not valid
 262       * @throws \Box\Spout\Writer\Exception\WriterNotOpenedException If this function is called before opening the writer
 263       * @throws \Box\Spout\Common\Exception\IOException If unable to write data
 264       */
 265      public function addRowsWithStyle(array $dataRows, $style)
 266      {
 267          if (!$style instanceof Style\Style) {
 268              throw new InvalidArgumentException('The "$style" argument must be a Style instance and cannot be NULL.');
 269          }
 270  
 271          $this->setRowStyle($style);
 272          $this->addRows($dataRows);
 273          $this->resetRowStyleToDefault();
 274  
 275          return $this;
 276      }
 277  
 278      /**
 279       * Returns the default style to be applied to rows.
 280       * Can be overriden by children to have a custom style.
 281       *
 282       * @return Style\Style
 283       */
 284      protected function getDefaultRowStyle()
 285      {
 286          return (new StyleBuilder())->build();
 287      }
 288  
 289      /**
 290       * Sets the style to be applied to the next written rows
 291       * until it is changed or reset.
 292       *
 293       * @param Style\Style $style
 294       * @return void
 295       */
 296      private function setRowStyle($style)
 297      {
 298          // Merge given style with the default one to inherit custom properties
 299          $this->rowStyle = $style->mergeWith($this->defaultRowStyle);
 300      }
 301  
 302      /**
 303       * Resets the style to be applied to the next written rows.
 304       *
 305       * @return void
 306       */
 307      private function resetRowStyleToDefault()
 308      {
 309          $this->rowStyle = $this->defaultRowStyle;
 310      }
 311  
 312      /**
 313       * Closes the writer. This will close the streamer as well, preventing new data
 314       * to be written to the file.
 315       *
 316       * @api
 317       * @return void
 318       */
 319      public function close()
 320      {
 321          $this->closeWriter();
 322  
 323          if (is_resource($this->filePointer)) {
 324              $this->globalFunctionsHelper->fclose($this->filePointer);
 325          }
 326  
 327          $this->isWriterOpened = false;
 328      }
 329  }
 330  


Generated: Thu Aug 11 10:00:09 2016 Cross-referenced by PHPXref 0.7.1