PHP code example of jildertmiedema / fill

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

    

jildertmiedema / fill example snippets


    $result = array_map(mapTo(Target::class), $data);

use function JildertMiedema\Fill\mapTo;

class Demo
{
    private $name;

    public function __construct($name)
    {
        $this->name = $name;
    }

    public function name()
    {
        return $this->name;
    }
}

$data = [
    ['name' => 'test name 1'],
    ['name' => 'test name 1'],
];

$result = array_map(mapTo(Demo::class), $data);

var_dump($result);

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use JildertMiedema\Fill\Build\ReflectionBuilder;
use JildertMiedema\Fill\Fill;
use JildertMiedema\Fill\Normalizer\CallbackNormalizer;
use JildertMiedema\Fill\Normalizer\SimpleNormalizer;

function mapTo($targetClass): \Closure
{
    $normalizer = new CallbackNormalizer(new SimpleNormalizer());
    $normalizer->register(Model::class, function (Model $model) {
        $data = $model->toArray();
        $keys = array_map(function ($key) {
            return Str::camel($key);
        }, array_keys($data));
        $data = array_combine($keys, array_values($data));

        return $data;
    });
    $fill = new Fill(new ReflectionBuilder($targetClass), $normalizer);

    return $fill->map();
}

class DemoModel extends Model
{
    protected $guarded = [];
}

class Target
{
    private $name;
    private $otherValue;

    public function __construct($name, $otherValue)
    {
        $this->name = $name;
        $this->otherValue = $otherValue;
    }

    public function name()
    {
        return $this->name;
    }
}

$data = [
    new DemoModel(['name' => 'test', 'other_value' => 'value']),
];

$result = array_map(mapTo(Target::class), $data);

var_dump($result);