Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Services;
- /**
- * Class CSVGenerator
- * @package App\Services
- */
- class CSVGenerator
- {
- private const DELIMITER = ';';
- private const FORMULA_PREFIX = '="';
- private const FORMULA_POSTFIX = '"';
- /**
- * @var Collection
- */
- private $rows;
- /**
- * @var Collection
- */
- private $columns;
- /**
- * Создаем файл csv и отдаем результат
- *
- * @return mixed
- * @throws \Throwable
- */
- public function get()
- {
- try {
- $data = array_merge( [ $this->columns ], $this->rows );
- $content = '';
- foreach ( $data as $record ) {
- $content .= implode( self::DELIMITER, array_map( static::formatterCallback(), $record ) ) . "\n";
- }
- return $content;
- } catch ( \Exception $e ) {
- throw $e;
- }
- }
- /**
- * Устанавливаем строки
- *
- * @param array $rows
- * @return static
- */
- public function rows( array $rows = null ): self
- {
- $this->rows = $rows ?: [];
- return $this;
- }
- /**
- * Устанавливаем столбцы
- *
- * @param array $columns
- * @return static
- */
- public function columns( array $columns = null ): self
- {
- $this->columns = $columns ?: [];
- return $this;
- }
- /**
- * Форматируем значение под excel/csv
- * !!! ТОЛЬКО ДЛЯ Microsoft Excel !!!
- *
- * @param $value
- * @return mixed
- */
- protected static function formatter( $value )
- {
- if ( is_numeric( $value ) ) {
- return self::FORMULA_PREFIX . $value . self::FORMULA_POSTFIX;
- }
- return str_replace( [ ',', ';' ], '', $value );
- }
- /**
- * Используем форматер в качестве callback
- *
- * @return array
- */
- protected static function formatterCallback(): array
- {
- return [ static::class, 'formatter' ];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement