byjg/anydataset-text

Anydataset Text File abstraction. Anydataset is an agnostic data source abstraction layer in PHP.

4.1.0 2019-02-19 06:00 UTC

README

Opensource ByJG Build Status

Text file abstraction dataset. Anydataset is an agnostic data source abstraction layer in PHP.

See more about Anydataset here.

Examples

Text File Delimited

<?php
$file = "Joao;Magalhaes
John;Doe
Jane;Smith";
    
$dataset = new \ByJG\AnyDataset\Text\TextFileDataset(
    $file,
    ["name", "surname"],
    \ByJG\AnyDataset\Text\TextFileDataset::CSVFILE
);
$iterator = $dataset->getIterator();

foreach ($iterator as $row) {
    echo $row->get('name');     // Print "Joao", "John", "Jane"
    echo $row->get('surname');  // Print "Magalhaes", "Doe", "Smith"
}

Text File Fixed sized columns

<?php
$file = "".
    "001JOAO   S1520\n".
    "002GILBERTS1621\n";

$fieldDefinition = [
    new \ByJG\AnyDataset\Text\Enum\FixedTextDefinition('id', 0, 3),
    new \ByJG\AnyDataset\Text\Enum\FixedTextDefinition('name', 3, 7),
    new \ByJG\AnyDataset\Text\Enum\FixedTextDefinition('enable', 10, 1, 'S|N'), // Required value --> S or N
    new \ByJG\AnyDataset\Text\Enum\FixedTextDefinition('code', 11, 4),
];

$dataset = new \ByJG\AnyDataset\Text\FixedTextFileDataset(
    $file,
    $fieldDefinition
);

$iterator = $dataset->getIterator();
foreach ($iterator as $row) {
    echo $row->get('id');
    echo $row->get('name');
    echo $row->get('enabled');
    echo $row->get('code');
}

Text File Fixed sized columns with conditional type of fields

<?php
$file = "".
    "001JOAO   S1520\n".
    "002GILBERTS1621\n";

$fieldDefinition = [
    new \ByJG\AnyDataset\Text\Enum\FixedTextDefinition('id', 0, 3),
    new \ByJG\AnyDataset\Text\Enum\FixedTextDefinition('name', 3, 7),
    new \ByJG\AnyDataset\Text\Enum\FixedTextDefinition(
        'enable',
        10,
        1,
        null,
        [
            "S" => [
                new \ByJG\AnyDataset\Text\Enum\FixedTextDefinition('first', 11, 1),
                new \ByJG\AnyDataset\Text\Enum\FixedTextDefinition('second', 12, 3),
            ],
            "N" => [
                new \ByJG\AnyDataset\Text\Enum\FixedTextDefinition('reason', 11, 4),
            ]
        ]
    ),
];

$dataset = new \ByJG\AnyDataset\Text\FixedTextFileDataset(
    $file,
    $fieldDefinition
);

$iterator = $dataset->getIterator();
foreach ($iterator as $row) {
    echo $row->get('id');
    echo $row->get('name');
    echo $row->get('enabled');
    echo $row->get('first');       // Not empty if `enabled` == "S"
    echo $row->get('second');      // Not empty if `enabled` == "S"
    echo $row->get('reason');      // Not empty if `enabled` == "N"
}

Read from remote url

TextFileDataset and FixedTextFileDataset support read file from remote http or https

Install

Just type: composer require "byjg/anydataset-text=4.0.*"

Running Unit tests

vendor/bin/phpunit

Open source ByJG