PHP code example of mvkasatkin / typecast

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

    

mvkasatkin / typecast example snippets


use \Mvkasatkin\typecast\Cast;
use function \Mvkasatkin\typecast\cast;

cast('120',      Cast::INT);    // => 120 - same as (int)'120'
cast(120,        Cast::FLOAT);  // => 120.0 - same as (float)120
cast('1',        Cast::BOOL);   // => true - same as (true)'1'
cast(120,        Cast::STRING); // => '120' - same as (string)120
cast('120',      Cast::BINARY); // => '120' - binary string, same as (binary)'120'
cast('120',      Cast::ARRAY);  // => ['120'] - same as (array)'120'
cast('120',      Cast::UNSET);  // => null - same as (unset)'120'
cast(['a' => 1], Cast::OBJECT); // => stdClass - same as (object)['a' => 1']

use \Mvkasatkin\typecast\Cast;
use function \Mvkasatkin\typecast\cast;

cast(['1', 2, 3.0, null], [Cast::FLOAT]); // => [1.0, 2.0, 3.0, null]

use \Mvkasatkin\typecast\Cast;
use function \Mvkasatkin\typecast\cast;

cast('1', function($value) { return (int)$value + 1; });   // => 2

use \Mvkasatkin\typecast\Cast;
use \Mvkasatkin\typecast\type\TypeInt;
use function \Mvkasatkin\typecast\cast;

cast('110', new TypeInt(140));   // => 110
cast(null, new TypeInt(140));   // => 140

$importData = [...]; // some external data
$scheme = [
    'field.1' => Cast::INT,
    'field.2' => Cast::FLOAT,
    'field.3' => [
        'field.3.ids' => [Cast::INT], // array of integers
        'field.3.name' => Cast::STRING,
        'field.3.price' => function($value) { /* custom type casting */ }
    ],
    'field.4' => new TypeBool(false), // default false
];

$safeData = cast($importData, $scheme);

$importData = [...]; // some external data
$scheme = [...]; // previous scheme
$strict = true;

$safeData = cast($importData, $scheme, $strict);

$scheme = new scheme([
    'field.1' => new TypeInt(),
    'field.2' => new TypeFloat(),
    'field.3' => [
        'field.3.ids' => new TypeArrayOfType(new TypeInt()), // array of integers
        'field.3.name' => new TypeString(),
        'field.3.price' => new TypeClosure(function($value) { /* custom type casting */ })
    ],
    'field.4' => new TypeBool(false), // default false
]);

$cast = new Cast($scheme)
$cast->process($importData); // useful in iterations