HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/SBogers95/rentman.io/app/Komma/Kms/Transfer/AbstractCsvExportService.php
<?php

namespace App\Komma\Kms\Transfer;

/**
 * Class AbstractCsvExportService
 */
abstract class AbstractCsvExportService extends AbstractCsvTransferService
{
    /**
     * Returns an array of arrays that represent products.
     * Each row represents an item in the form of an array. In the case of products an example could be:
     * [
     *  ['1', 'my awesome product', 'product description']
     *  ['1', 'my awesome second product', 'product description 2']
     * ]
     *
     * @return array
     */
    abstract public function export():array;

    /**
     * Returns a csv file as an array
     * Each item in the array represents a row.
     * Each row item is an array of column values.
     *
     * @return array
     */
    public function exportToCsvArray():array
    {
        $csvArray = $this->export();

        if (self::HASHEADERROW) {
            array_unshift($csvArray, $this->getHeaderNames());
        }

        return $csvArray;
    }

    /**
     * Creates a string that represents a CSV file
     *
     * @return string
     */
    public function exportToCsvFileString():string
    {
        return $this->strPutCsv($this->exportToCsvArray(), self::HASHEADERROW);
    }

    /**
     * Convert a multi-dimensional, associative array to a CSV data string
     *
     * @param array $data the array of data
     * @param bool $hasHeaderRow
     * @return string CSV text
     */
    private function strPutCsv($data, $hasHeaderRow = true):string
    {
        // Generate CSV data from array
        $fh = fopen('php://temp', 'rw'); // don't create a file, attempt
        // to use memory instead

        foreach ($data as $row) {
            fputcsv($fh, $row, self::DELIMITER);
        }
        rewind($fh);
        $csv = stream_get_contents($fh);
        fclose($fh);

        return $csv;
    }
}