PHP code example of beeblebrox3 / caster

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

    

beeblebrox3 / caster example snippets


$types = [
    'must_be_integer' => 'integer',
];
$input = [
    'must_be_integer' => '0.9',
];

$caster = new Beeblebrox3\Caster\Caster();
$res = $caster->cast($types, $input);

// $res will be ['must_be_integer' => 0]


$types = [
    'a' => 'integer',
    'b' => 'string',
    'c' => 'bool',
]

$types = [
    'a' => 'integer',
    'b' => 'string|lpad:10,0', // will cast to string and after apply a left string pad
]

$types = [
    // string up to 60 characters
    'a' => 'string:60',

    // will cast to float and then round with precision of two specifying the mode in which rounding occurs
    // (see https://php.net/round for details)
    'b' => 'float:2,' . PHP_ROUND_HALF_DOWN,
];

$res = $caster->cast(
    ['level1.level2.level3.key' => 'integer'],
    ['level1' => ['level2' => ['level3' => ['key' => '999']]]]
);

// $res wil be ['level1' => ['level2' => ['level3' => ['key' => 999]]]]



use Beeblebrox3\Caster\Rules\IRule;
use Beeblebrox3\Caster\Caster;

class PipeRule implements IRule {
  public function handle($value, ...$args) {
    return $value;
  }
}

$caster = new Caster();
$caster->addCustomRule('pipe', PipeRule::class);

$res = $caster->cast(['a' => 'pipe'], ['a' => '199']);

$caster = new Caster();
$caster->addCustomrule('pipe', function ($value) { return $value; });