Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. CsvEncoder.php

function CsvEncoder::decode

Overrides DecoderInterface::decode

File

vendor/symfony/serializer/Encoder/CsvEncoder.php, line 134

Class

CsvEncoder
Encodes CSV data.

Namespace

Symfony\Component\Serializer\Encoder

Code

public function decode(string $data, string $format, array $context = []) : mixed {
    $handle = fopen('php://temp', 'r+');
    fwrite($handle, $data);
    rewind($handle);
    if (str_starts_with($data, self::UTF8_BOM)) {
        fseek($handle, \strlen(self::UTF8_BOM));
    }
    $headers = null;
    $nbHeaders = 0;
    $headerCount = [];
    $result = [];
    [
        $delimiter,
        $enclosure,
        $escapeChar,
        $keySeparator,
        ,
        ,
        ,
        $asCollection,
    ] = $this->getCsvOptions($context);
    while (false !== ($cols = fgetcsv($handle, 0, $delimiter, $enclosure, $escapeChar))) {
        $nbCols = \count($cols);
        if (null === $headers) {
            $nbHeaders = $nbCols;
            if ($context[self::NO_HEADERS_KEY] ?? $this->defaultContext[self::NO_HEADERS_KEY]) {
                for ($i = 0; $i < $nbCols; ++$i) {
                    $headers[] = [
                        $i,
                    ];
                }
                $headerCount = array_fill(0, $nbCols, 1);
            }
            else {
                foreach ($cols as $col) {
                    $header = explode($keySeparator, $col ?? '');
                    $headers[] = $header;
                    $headerCount[] = \count($header);
                }
                continue;
            }
        }
        $item = [];
        for ($i = 0; $i < $nbCols && $i < $nbHeaders; ++$i) {
            $depth = $headerCount[$i];
            $arr =& $item;
            for ($j = 0; $j < $depth; ++$j) {
                $headerName = $headers[$i][$j];
                if ('' === $headerName) {
                    $headerName = $i;
                }
                // Handle nested arrays
                if ($j === $depth - 1) {
                    $arr[$headerName] = $cols[$i];
                    continue;
                }
                if (!isset($arr[$headerName])) {
                    $arr[$headerName] = [];
                }
                $arr =& $arr[$headerName];
            }
        }
        $result[] = $item;
    }
    fclose($handle);
    if ($asCollection) {
        return $result;
    }
    if (!$result || isset($result[1])) {
        return $result;
    }
    // If there is only one data line in the document, return it (the line), the result is not considered as a collection
    return $result[0];
}
RSS feed
Powered by Drupal