Advertisement
evg_rz_gf

CSVGenerator

Nov 18th, 2019
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.11 KB | None | 0 0
  1. <?php
  2. namespace App\Services;
  3.  
  4.  
  5. /**
  6.  * Class CSVGenerator
  7.  * @package App\Services
  8.  */
  9. class CSVGenerator
  10. {
  11.     private const DELIMITER = ';';
  12.     private const FORMULA_PREFIX = '="';
  13.     private const FORMULA_POSTFIX = '"';
  14.  
  15.     /**
  16.      * @var Collection
  17.      */
  18.     private $rows;
  19.  
  20.     /**
  21.      * @var Collection
  22.      */
  23.     private $columns;
  24.  
  25.     /**
  26.      * Создаем файл csv и отдаем результат
  27.      *
  28.      * @return mixed
  29.      * @throws \Throwable
  30.      */
  31.     public function get()
  32.     {
  33.         try {
  34.             $data = array_merge( [ $this->columns ], $this->rows );
  35.  
  36.             $content = '';
  37.             foreach ( $data as $record ) {
  38.                 $content .= implode( self::DELIMITER, array_map( static::formatterCallback(), $record ) ) . "\n";
  39.             }
  40.  
  41.             return $content;
  42.         } catch ( \Exception $e ) {
  43.             throw $e;
  44.         }
  45.     }
  46.  
  47.     /**
  48.      * Устанавливаем строки
  49.      *
  50.      * @param array $rows
  51.      * @return static
  52.      */
  53.     public function rows( array $rows = null ): self
  54.     {
  55.         $this->rows = $rows ?: [];
  56.  
  57.         return $this;
  58.     }
  59.  
  60.     /**
  61.      * Устанавливаем столбцы
  62.      *
  63.      * @param array $columns
  64.      * @return static
  65.      */
  66.     public function columns( array $columns = null ): self
  67.     {
  68.         $this->columns = $columns ?: [];
  69.  
  70.         return $this;
  71.     }
  72.  
  73.     /**
  74.      * Форматируем значение под excel/csv
  75.      * !!! ТОЛЬКО ДЛЯ Microsoft Excel !!!
  76.      *
  77.      * @param $value
  78.      * @return mixed
  79.      */
  80.     protected static function formatter( $value )
  81.     {
  82.         if ( is_numeric( $value ) ) {
  83.             return self::FORMULA_PREFIX . $value . self::FORMULA_POSTFIX;
  84.         }
  85.  
  86.         return str_replace( [ ',', ';' ], '', $value );
  87.     }
  88.  
  89.     /**
  90.      * Используем форматер в качестве callback
  91.      *
  92.      * @return array
  93.      */
  94.     protected static function formatterCallback(): array
  95.     {
  96.         return [ static::class, 'formatter' ];
  97.     }
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement