PHP code example of rhinox / input-data

1. Go to this page and download the library: Download rhinox/input-data 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/ */

    

rhinox / input-data example snippets


use Rhino\InputData\InputData;

$data = new InputData([
    'name' => 'John Doe',
    'age' => '30',
    'active' => 'true',
    'profile' => [
        'email' => '[email protected]'
    ]
]);

echo $data->string('name');           // "John Doe"
echo $data->int('age');              // 30
echo $data->bool('active');          // true
echo $data->string('profile.email'); // "[email protected]" (dot notation)
echo $data->string('missing', 'N/A'); // "N/A" (default value)

// HTTP request data
$post = new InputData($_POST);
$get = new InputData($_GET);

// JSON API requests
$body = InputData::tryJsonDecode(file_get_contents('php://input'));

$response = (new \GuzzleHttp\Client())->get('https://api.example.com/users/1');
$data = InputData::tryJsonDecode($response->getBody());

$userId = $data->int('id');
$userName = $data->string('name', 'Unknown User');
$createdAt = $data->dateTime('created_at', 'UTC');

// JSON files
$config = InputData::tryJsonDecodeFile('config.json');
$apiKey = $config->string('api_key');

// CSV processing
function readCsv(string $file) {
    $handle = fopen($file, 'r');
    for ($i = 0; $row = fgetcsv($handle); ++$i) {
        yield $i => new InputData($row);
    }
    fclose($handle);
}

foreach (readCsv('data.csv') as $i => $row) {
    if ($i === 0) continue; // Skip header
    $name = $row->string(0);
    $amount = $row->decimal(1);
    $date = $row->dateTime(2, 'UTC');
}

$data->string(?string $key = null, ?string $default = ''): ?string

$data = new InputData(['name' => 'John', 'age' => 30, 'tags' => ['dev', 'php']]);

$data->string('name');           // "John"
$data->string('age');            // "30"
$data->string('missing');        // ""
$data->string('missing', 'N/A'); // "N/A"
$data->string('tags');           // "" (arrays can't be cast to string)

$data->int(?string $key = null, ?int $default = 0): ?int

$data = new InputData(['count' => '42', 'price' => '19.99', 'name' => 'John']);

$data->int('count');           // 42
$data->int('price');           // 19
$data->int('name');            // 0 (default)
$data->int('missing', 100);    // 100

$data->decimal(?string $key = null, ?float $default = 0.0): ?float

$data = new InputData(['price' => '19.99', 'count' => '5', 'name' => 'John']);

$data->decimal('price');        // 19.99
$data->decimal('count');        // 5.0
$data->decimal('name');         // 0.0 (default)
$data->decimal('missing', 1.5); // 1.5

$data->bool(?string $key = null, ?bool $default = false): ?bool

$data = new InputData(['active' => 'true', 'count' => '0', 'name' => 'John']);

$data->bool('active');          // true
$data->bool('count');           // false
$data->bool('name');            // true (non-empty string)
$data->bool('missing');         // false (default)

$data->dateTime(?string $key, ?string $timezone = null, ?string $default = null): ?\DateTimeImmutable

$data = new InputData(['created' => '2023-07-15 10:30:00', 'timestamp' => '@1689422400']);

$data->dateTime('created');                    // DateTimeImmutable (server timezone)
$data->dateTime('created', 'UTC');             // DateTimeImmutable (UTC)
$data->dateTime('timestamp');                  // DateTimeImmutable from timestamp
$data->dateTime('missing', null, 'now');       // Current time
$data->dateTime('invalid', null, null);        // null

$data->arr(?string $key = null, ?array $default = []): InputData

$data = new InputData(['users' => [['name' => 'John'], ['name' => 'Jane']]]);

$users = $data->arr('users');
foreach ($users as $user) {
    echo $user->string('name'); // Access nested data
}

$data->arr('users')->count();     // 2
$data->arr('missing')->isEmpty(); // true

$data->object(?string $key = null, $default = null): InputData

$data = new InputData(['config' => ['debug' => true, 'timeout' => 30]]);

$config = $data->object('config');
$debug = $config->bool('debug'); // true

$data->json(?string $key = null, $default = []): InputData

$data = new InputData(['response' => '{"status":"ok","data":[1,2,3]}']);

$response = $data->json('response');
$status = $response->string('status');      // "ok"
$items = $response->arr('data')->count();   // 3

$data->raw(string $key, $default = null): mixed

$data = new InputData(['items' => ['a', 'b', 'c'], 'count' => '5']);

$data->raw('items');  // ['a', 'b', 'c'] (original array)
$data->raw('count');  // '5' (original string)

$data->exists(string $key): bool

$data = new InputData(['user' => ['profile' => ['name' => 'John']]]);

$data->exists('user');              // true
$data->exists('user.profile.name'); // true
$data->exists('user.missing');      // false

$data->isEmpty(): bool
$data->isArray(): bool
$data->count(): int

$data = new InputData(['a', 'b', 'c']);
$data->isEmpty(); // false
$data->isArray(); // true
$data->count();   // 3

InputData::jsonDecode(string $jsonString, bool $assoc = true): InputData

try {
    $data = InputData::jsonDecode('{"name":"John","age":30}');
    echo $data->string('name'); // "John"
} catch (\JsonException $e) {
    // Handle parsing error
}

InputData::tryJsonDecode(string $jsonString, bool $assoc = true): InputData

$data = InputData::tryJsonDecode('invalid json');
$data->isEmpty(); // true - no exception thrown

InputData::jsonDecodeFile(string $filename, bool $assoc = true): InputData

$config = InputData::tryJsonDecodeFile('config.json');
$apiKey = $config->string('api_key');

InputData::tryJsonDecodeFile(string $filename, bool $assoc = true): InputData

$config = InputData::tryJsonDecodeFile('config.json');
if (!$config->isEmpty()) {
    $apiKey = $config->string('api_key');
}

use Rhino\InputData\MutableInputData;

$data = new MutableInputData(['a' => 1, 'b' => 2]);

$data->set('c', 3);              // Modifies $data
$data->extend(['d' => 4]);       // Modifies $data
$data->filter(fn($v) => $v->int() > 2); // Modifies $data

echo $data->count(); // 2 (only c=3, d=4 remain)

use Rhino\InputData\ImmutableInputData;

$original = new ImmutableInputData(['a' => 1, 'b' => 2]);

$modified = $original->set('c', 3);              // Returns new instance
$extended = $original->extend(['d' => 4]);       // Returns new instance
$filtered = $original->filter(fn($v) => $v->int() > 1); // Returns new instance

echo $original->count(); // 2 (unchanged)
echo $modified->count(); // 3 (new instance)

$data->extend(array ...$newData): static

$data = new MutableInputData(['user' => ['name' => 'John']]);
$data->extend(['user' => ['email' => '[email protected]'], 'active' => true]);
// Result: ['user' => ['name' => 'John', 'email' => '[email protected]'], 'active' => true]

$data->set(string $name, $value): static

$data = new MutableInputData([]);
$data->set('user.profile.name', 'John');
$data->set('user.profile.age', 30);
// Result: ['user' => ['profile' => ['name' => 'John', 'age' => 30]]]

$data->unset(string $name): static

$data = new MutableInputData(['user' => ['name' => 'John', 'email' => '[email protected]']]);
$data->unset('user.email');
// Result: ['user' => ['name' => 'John']]

$data->filter(?callable $callback = null): static

$data = new MutableInputData(['a' => 1, 'b' => null, 'c' => 3]);
$data->filter(); // Removes null values
// Result: ['a' => 1, 'c' => 3]

$data->filter(fn($value) => $value->int() > 1);
// Result: ['c' => 3]

$data->filterRecursive(?callable $callback = null): static

$data = new MutableInputData([
    'users' => [
        ['name' => 'John', 'active' => true],
        ['name' => 'Jane', 'active' => false]
    ]
]);
$data->filterRecursive(fn($value, $key) => $key->string() !== 'active' || $value->bool());

$data->map(callable $callback): static

$data = new MutableInputData(['a' => 1, 'b' => 2, 'c' => 3]);
$data->map(fn($value) => $value->int() * 2);
// Result: ['a' => 2, 'b' => 4, 'c' => 6]

$data->mapRecursive(callable $callback): static

$data = new MutableInputData(['numbers' => [1, 2], 'single' => 3]);
$data->mapRecursive(fn($value) => $value->int() * 2);
// Result: ['numbers' => [2, 4], 'single' => 6]

$data->values(): static

$data = new MutableInputData(['a' => 1, 'c' => 2, 'x' => 3]);
$data->values();
// Result: [0 => 1, 1 => 2, 2 => 3]

$data->merge($data): static

$data1 = new MutableInputData(['a' => 1, 'b' => 2]);
$data1->merge(['c' => 3, 'd' => 4]);
// Result: ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4]

$data->keys(): static

$data = new MutableInputData(['a' => 1, 'b' => 2, 'c' => 3]);
$data->keys();
// Result: ['a', 'b', 'c']

$data->unique(): static

$data = new MutableInputData(['a', 'b', 'a', 'c', 'b']);
$data->unique();
// Result: [0 => 'a', 1 => 'b', 3 => 'c']

$data->sort(?callable $callback = null): static

$data = new MutableInputData(['item10', 'Item2', 'item1']);
$data->sort();
// Result: [2 => 'item1', 1 => 'Item2', 0 => 'item10']

$data = new MutableInputData(['x' => 3, 'y' => 1, 'z' => 2]);
$data->sort(fn($a, $b) => $a->int() <=> $b->int());
// Result: ['y' => 1, 'z' => 2, 'x' => 3]

$data = new InputData([
    'user' => [
        'profile' => [
            'social' => [
                'twitter' => '@johndoe'
            ]
        ]
    ]
]);

$twitter = $data->string('user.profile.social.twitter'); // "@johndoe"

$data = new InputData(['name' => 'John', 'age' => 30]);

echo $data['name']->string(); // "John"
echo $data['age']->int();     // 30
isset($data['name']);         // true

// Note: Setting/unsetting throws MutationException for base InputData

$data = new InputData(['a' => 1, 'b' => 2, 'c' => 3]);

foreach ($data as $key => $value) {
    echo $key->string() . ': ' . $value->int();
}

$users = new InputData([
    ['name' => 'John', 'active' => true],
    ['name' => 'Jane', 'active' => false],
    ['name' => 'Bob', 'active' => true]
]);

$activeUser = $users->find(fn($user) => $user->bool('active'));
echo $activeUser->string('name'); // "John"

$data = new InputData(['foo' => 1, 'bar' => 2]);

$total = $data->pipe(fn($o) => ['baz' => $o->int('foo') + $o->int('bar')]);
echo $total->int('baz'); // 3

class CustomInputData extends InputData
{
    public function uuid(?string $name = null, ?string $default = null): ?string
    {
        $value = $this->string($name, $default);

        if ($value && preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i', $value)) {
            return $value;
        }

        return $default;
    }

    public function email(?string $name = null, ?string $default = null): ?string
    {
        $value = $this->string($name, $default);

        if ($value && filter_var($value, FILTER_VALIDATE_EMAIL)) {
            return $value;
        }

        return $default;
    }
}

$data = new CustomInputData(['id' => 'f47ac10b-58cc-4372-a567-0e02b2c3d479']);
$uuid = $data->uuid('id'); // Returns the UUID or null if invalid