PHP code example of k2gl / array-reader

1. Go to this page and download the library: Download k2gl/array-reader library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

k2gl / array-reader example snippets


use K2gl\ArrayReader\ArrayReader;

$request = ArrayReader::of($_GET);

$page    = $request->int('page');             // "5"   -> 5   (int)
$active  = $request->bool('active');          // "on"  -> true (bool)
$perPage = $request->intOr('per_page', 20);   // 20 if it is absent or not a valid number

$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int) $_GET['page'] : null;

$data = ['count' => '42', 'price' => '9.99', 'enabled' => 'yes'];

use K2gl\ArrayReader\ArrayReader;

$request = ArrayReader::of($data);

$request->int('count');        // 42        — "42" is a whole number
$request->float('price');      // 9.99      — numeric string
$request->bool('enabled');     // true      — "yes"
$request->int('price');        // throws TypeMismatchException — "9.99" is not an integer
$request->intOr('price', 0);   // 0         — the lenient variant returns the default, never throws

use K2gl\ArrayReader\StrictArrayReader;

$document = StrictArrayReader::of(['count' => 42, 'name' => 'Ada']);

$document->int('count');       // 42
$document->string('name');     // 'Ada'

StrictArrayReader::of(['count' => '42'])->int('count'); // throws — "42" is a string, not an int

use K2gl\ArrayReader\LooseArrayReader;

$loose = LooseArrayReader::of($data);

$loose->int('price');          // 9         — (int) "9.99"
$loose->bool('enabled');       // true
$loose->int('count');          // 42

LooseArrayReader::of(['x' => 'abc'])->int('x'); // 0   — (int) "abc"
$loose->int('missing');        // throws MissingKeyException — a missing key is always an error

$form = ArrayReader::of($_POST);

$email    = $form->string('email');          // string  (throws if missing / not producible)
$nickname = $form->stringOr('nickname');     // ?string (null when absent)
$age      = $form->intOr('age', 0);          // int     (0 when absent / invalid)
$price    = $form->float('price');           // float
$subscribe = $form->boolOr('subscribe', false);

$config = ArrayReader::of($decoded);

$config->array('options');               // array<array-key, mixed>
$config->list('tags');                   // list<mixed> — sequential, 0-based keys
$config->nested('database')->string('host');   // a reader of the same kind over the nested array

$config->arrayOr('options', []);         // lenient variants return the default instead of throwing
$config->listOr('tags', []);
$config->nestedOr('database');           // ?reader

$payload = ArrayReader::of(['items' => [['id' => 1], ['id' => 2]]]);

foreach ($payload->nestedList('items') as $item) {
    $item->int('id');                    // each element is a reader of the same kind
}

$payload->nestedListOr('missing');       // null when absent, not a list, or an element is not an array

$query = ArrayReader::of(['ids' => ['1', '2', '3'], 'tags' => ['php', 'json']]);

$query->ints('ids');         // list<int>    => [1, 2, 3]   ('1' cast in safe mode)
$query->strings('tags');     // list<string> => ['php', 'json']

// strict variant throws TypeMismatchException if any element cannot be produced;
// lenient *Or returns the default when the key is absent, the value is not a list,
// or any element cannot be produced (all-or-nothing):
$query->intsOr('ids', []);   // list<int>
$query->floatsOr('missing'); // null

$payload = ArrayReader::of(['points' => [['x' => 1], ['x' => 2]]]);

$payload->listOf('points', fn (mixed $p) => Point::fromArray((array) $p));  // list<Point>
$payload->listOfOr('points', $caster, []);   // default when absent / not a list (caster not run)

enum Suit: string { case Hearts = 'hearts'; case Spades = 'spades'; }

$card = ArrayReader::of($row);

$card->enum('suit', Suit::class);                 // Suit  (throws if missing / not a valid case)
$card->enumOr('suit', Suit::class);               // ?Suit (null when absent / invalid)
$card->enumOr('suit', Suit::class, Suit::Hearts); // Suit  (Suit::Hearts when absent / invalid)

$deck->enums('suits', Suit::class);               // list<Suit>  (strict: throws on a bad element)
$deck->enumsOr('suits', Suit::class, []);         // list<Suit>  (default when absent / any element invalid)

$row = ArrayReader::of(['created_at' => '2024-01-15T10:30:00+00:00', 'day' => '15/01/2024']);

$row->dateTime('created_at');              // DateTimeImmutable (throws if missing / unparsable)
$row->dateTime('day', 'd/m/Y');            // DateTimeImmutable, strict to the format
$row->dateTimeOr('missing');               // ?DateTimeImmutable (null when absent / unparsable)
$row->dateTimeOr('day', null, 'Y-m-d');    // pass a format as the third argument

$log->dateTimes('timestamps');             // list<DateTimeImmutable> (strict: throws on a bad element)
$log->dateTimesOr('timestamps', []);       // list<DateTimeImmutable> (default when absent / any unparsable)

$reader = ArrayReader::of(['user' => ['profile' => ['age' => 30]]]);

$reader->int('user.profile.age');     // 30
$reader->has('user.profile.age');     // true
$reader->nested('user.profile')->int('age'); // 30
$reader->intOr('user.profile.missing', 0);   // 0

// A literal "a.b" key still wins over the a -> b path:
ArrayReader::of(['a.b' => 1, 'a' => ['b' => 2]])->int('a.b'); // 1

$reader->intOrElse('page', fn (): int => $this->countPages());  // callback only runs when 'page' is absent / invalid

ArrayReader::of($payload)
    ->

$config = ArrayReader::of($decoded);
$config->has('debug');                   // bool — is the key present? (true even if its value is null)
$config->toArray();                      // the underlying array<array-key, mixed>

$request = ArrayReader::fromJson($body); // decode a JSON object/array straight into a reader

use K2gl\ArrayReader\ArrayReader;
use K2gl\ArrayReader\Exception\ArrayReaderException;

try {
    $email = ArrayReader::fromJson($body)->string('email');
} catch (ArrayReaderException $e) {
    // MissingKeyException | TypeMismatchException | InvalidJsonException
}