PHP code example of om / from-array

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

    

om / from-array example snippets


class Example {
  use \DataLoader\FromArray;

  public ?string $a = null;
  public ?string $b = null;
  public ?string $c = null;
}

$example = Example::fromArray(
  [
    'a' => 'value of A',
    'b' => 'value of B',
    'c' => 'value of C'
  ]
);

echo json_encode($example, JSON_PRETTY_PRINT);



 SchemeExample {
  use \DataLoader\FromArray;

  const SCHEME = [
    'id' => 'intval',
    'date' => DateTime::class
  ];
  public ?int $id = null;
  public ?DateTime $date = null;
  public bool $alwaysFalse = true;
}

$example = SchemeExample::fromArray(
  data: ['id' => '12345', 'alwaysFalse' => true, 'date' => '2020-01-01'],
  scheme: ['alwaysFalse' => fn() => false]
);

var_dump($example->id); // will return integer 12345
var_dump($example->alwaysFalse); // will return false
var_dump($example->date->format('c')); // will return date


class NestedData {
  public array $data = [];

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

class NestedExample {
  use \DataLoader\FromArray;

  const SCHEME = ['nested' => NestedData::class];
  public ?NestedData $nested = null;
}

$example = NestedExample::fromArray(['nested' => ['some', 'data', 'here']]);
var_dump($example->nested); // will return instance of Nested class

class One {
  use \DataLoader\FromArray;
  public ?string $value = null;
}

class Two {
  use \DataLoader\FromArray;
  public ?string $value = null;
}

class Multiple {
  use \DataLoader\FromArray;
  const SCHEME = ['one' => One::class, 'two' => Two::class];
  public ?One $one = null;
  public ?Two $two = null;
}

$nested = Multiple::fromArray(
  [
    'one' => ['value' => 'set value for one'],
    'two' => ['value' => 'set value for two']
  ]
);

$scheme = Nested::fromArray(data: $data, filter: ['a' => function($data) { return $data; }]);

class Example {
  use \DataLoader\FromArray;
  const MAPPING = ['anotherId'=>'id'];
  public ?int $id = null;
}
$example = Example::fromArray(['anotherId' => 1234]);
var_dump($example->id); // will return 1234

class Filter {
  public ?DateTime $date = null;
  public string $notDate = '';
}

$data = ['date'=> '2017-11-01', 'notDate'=> '2017-11-01'];
$example = Filter::fromArray($data, function ($value, $property) {
  return ($property === 'date') ? new DateTime($value) : $value;
});

echo $example->notDate; // will return '2017-11-01' string
var_dump($example->date); // will return DateTime object

function ($value, $property) {
  if ($property === '_id') return new \MongoId((string)$value);
  if ($value instanceof \MongoDate) return new \DateTime('@' . $value->sec);
  return $value;
}