Class luya\yii\helpers\ExportHelper

Inheritanceluya\yii\helpers\ExportHelper
Subclassesluya\helpers\ExportHelper
Available since version1.0.0

Exporting into Formats.

Public Methods

Hide inherited methods

Method Description Defined By
csv() Export an Array or QueryInterface instance into a CSV formated string. luya\yii\helpers\ExportHelper
sanitizeValue() Sanitize Certain Values to increase security from user generated output. luya\yii\helpers\ExportHelper
xlsx() Export an Array or QueryInterface instance into a Excel formatted string. luya\yii\helpers\ExportHelper

Protected Methods

Hide inherited methods

Method Description Defined By
generateContentArray() Generate content by rows. luya\yii\helpers\ExportHelper
generateOutputString() Generate the output string with delimiters. luya\yii\helpers\ExportHelper
generateRow() Generate a row by its items. luya\yii\helpers\ExportHelper
transformInput() Check type of input and return correct array. luya\yii\helpers\ExportHelper

Method Details

Hide inherited methods

csv() public static method

Export an Array or QueryInterface instance into a CSV formated string.

public static string csv ( $input, array $keys = [], $header true, array $options = [] )
$input array|yii\db\QueryInterface

The data to export into a csv

$keys array

Defines which keys should be packed into the generated CSV. The defined keys does not change the sort behavior of the generated csv.

$header boolean

Whether the column name should be set as header inside the csv or not.

$options array

Options

  • sort: boolean, whether they row should be sorted by its keys, default is true.
return string

The generated CSV as string.

                public static function csv($input, array $keys = [], $header = true, array $options = [])
{
    $delimiter = ",";
    $input = self::transformInput($input);
    $array = self::generateContentArray($input, $keys, $header, $options);
    return self::generateOutputString($array, $delimiter);
}

            
generateContentArray() protected static method

Generate content by rows.

protected static array generateContentArray ( $contentRows, array $keys, $generateHeader true, $options = [] )
$contentRows array|string
$keys array
$generateHeader boolean
$options array

Options

  • sort: boolean, whether they row should be sorted by its keys, default is true.
throws luya\Exception

                protected static function generateContentArray($contentRows, array $keys, $generateHeader = true, $options  = [])
{
    if (is_scalar($contentRows)) {
        throw new Exception("Content must be either an array, object or traversable.");
    }
    $attributeKeys = $keys;
    $header = [];
    $rows = [];
    $i = 0;
    foreach ($contentRows as $content) {
        // handle rows content
        if (!empty($keys) && is_array($content)) {
            foreach ($content as $k => $v) {
                if (!in_array($k, $keys)) {
                    unset($content[$k]);
                }
            }
        } elseif (!empty($keys) && is_object($content)) {
            $attributeKeys[get_class($content)] = $keys;
        }
        $row = ArrayHelper::toArray($content, $attributeKeys, false);
        if (ArrayHelper::getValue($options, 'sort', true)) {
            ksort($row);
        }
        $rows[$i] = $row;
        // handle header
        if ($i == 0 && $generateHeader) {
            if ($content instanceof Model) {
                /** @var Model $content */
                foreach ($content as $k => $v) {
                    if (empty($keys)) {
                        $header[$k] = $content->getAttributeLabel($k);
                    } elseif (in_array($k, $keys)) {
                        $header[$k] = $content->getAttributeLabel($k);
                    }
                }
            } else {
                $header = array_keys($rows[0]);
            }
            if (ArrayHelper::getValue($options, 'sort', true)) {
                ksort($header);
            }
        }
        unset($row);
        gc_collect_cycles();
        $i++;
    }
    if ($generateHeader) {
        return ArrayHelper::merge([$header], $rows);
    }
    return $rows;
}

            
generateOutputString() protected static method

Generate the output string with delimiters.

protected static null|string generateOutputString ( array $input, $delimiter )
$input array
$delimiter string

                protected static function generateOutputString(array $input, $delimiter)
{
    $output = null;
    foreach ($input as $row) {
        $output.= self::generateRow($row, $delimiter, '"');
    }
    return $output;
}

            
generateRow() protected static method

Generate a row by its items.

protected static string generateRow ( array $row, $delimiter, $enclose )
$row array
$delimiter string
$enclose string

                protected static function generateRow(array $row, $delimiter, $enclose)
{
    array_walk($row, function (&$item) use ($enclose) {
        if (is_bool($item)) {
            $item = (int) $item;
        } elseif (is_null($item)) {
            $item = '';
        } elseif (!is_scalar($item)) {
            $item = "[array]";
        }
        $item = $enclose.self::sanitizeValue($item).$enclose;
    });
    return implode($delimiter, $row) . PHP_EOL;
}

            
sanitizeValue() public static method (available since version 1.2.1)

Sanitize Certain Values to increase security from user generated output.

See also https://owasp.org/www-community/attacks/CSV_Injection.

public static string sanitizeValue ( $value )
$value string

                public static function sanitizeValue($value)
{
    $value = str_replace([
        '"',
    ], [
        '""',
    ], trim($value));
    $firstChar = substr($value, 0, 1);
    if (in_array($firstChar, ['=', '+', '-', '@', PHP_EOL, "\t", "\n"])) {
        $value = StringHelper::replaceFirst($firstChar, "'$firstChar", $value);
    }
    return $value;
}

            
transformInput() protected static method

Check type of input and return correct array.

protected static array transformInput ( $input )
$input array|yii\db\QueryInterface

                protected static function transformInput($input)
{
    if ($input instanceof QueryInterface) {
        return $input->all();
    }
    return $input;
}

            
xlsx() public static method

Export an Array or QueryInterface instance into a Excel formatted string.

public static mixed xlsx ( $input, array $keys = [], $header true, array $options = [] )
$input array|yii\db\QueryInterface
$keys array

Defines which keys should be packed into the generated xlsx. The defined keys does not change the sort behavior of the generated xls.

$header boolean
$options array

Options

  • sort: boolean, whether they row should be sorted by its keys, default is true.
throws luya\Exception

                public static function xlsx($input, array $keys = [], $header = true, array $options = [])
{
    $input = self::transformInput($input);
    $array = self::generateContentArray($input, $keys, $header, $options);
    $writer = new XLSXWriter();
    $writer->writeSheet($array);
    return $writer->writeToString();
}