Handy array tools to creating and updating objects from arrays, converting objects to arrays and validating them.
Strictly requires PHP 7.4.
Via Composer
$ composer require midorikocak/arraytoolsLet's say you have a plain data object like this:
<?php
declare(strict_types=1);
namespace midorikocak\arraytools;
class User implements ArrayConvertableInterface, ArrayUpdateableInterface
{
use ArrayConvertableTrait;
use ArrayUpdateableTrait;
private ?string $id;
private string $username;
private string $email;
private string $password;
public function __construct(?string $id, string $username, string $email, string $password)
{
$this->id = $id;
$this->username = $username;
$this->password = $password;
$this->email = $email;
}
public function getId(): ?string
{
return $this->id;
}
public function setId(string $id)
{
$this->id = $id;
}
// Getters and settersIn order to convert this object to an array you should implement methods like toArray and fromArray like this.
public function toArray(): array
{
$toReturn = [
'username' => $this->getUsername(),
'email' => $this->getEmail(),
'password' => $this->getPassword(),
];
if ($this->getId()) {
$toReturn['id'] = $this->getId();
}
return $toReturn;
}
public static function fromArray($array): User
{
$id = $array['id'] ?? null;
$username = $array['username'];
$email = $array['email'];
$password = $array['password'];
return new User($id, $username, $email, $password);
}This would make may problems in case of change and resposibility. Instead you can use ArrayConvertableTrait in your data object implemetation.
<?php
declare(strict_types=1);
namespace midorikocak\arraytools;
class User implements ArrayConvertableInterface
{
use ArrayConvertableTrait;
private ?string $id;
private string $username;
private string $email;
private string $password;
// restSimply calling toArray() method from your object will return an array with your constructor params and their names as array keys.
Note: Trait expects that implemented object has getters.
$userData = [
'id' => '1',
'username' => 'midorikocak',
'password' => '24738956349lhksbvlhf',
'email' => '[email protected]',
];
$user = new User(
$userData['id'] ?? null,
$userData['username'],
$userData['email'],
$userData['password']
);
$userArray = $user->toArray();
print_r($userArray);Will output to:
Array
(
[id] => 1
[username] => midorikocak
[password] => 24738956349lhksbvlhf
[email] => [email protected]
)
ArrayConvertableTrait also adds fromArray functionality into your object. It expects that the array has same keys with constructor parameters.
$userData = [
'username' => 'midorikocak',
'password' => '24738956349lhksbvlhf',
'email' => '[email protected]',
];
$user = User::fromArray($userData);If you use ArrayUpdateableTrait you can use setFromArray() method into your object. It will update object instance with array data.
Note: It expects that the array has same keys with setters.
$userData = [
'id' => '2',
'username' => 'update',
'password' => 'updatedpw',
'email' => '[email protected]',
];
$user->setFromArray($userData);You can use ArrayValidator class to validate your arrays according to the rules you define.
use midorikocak\arraytools\ArrayValidator;
$arrayValidator = new ArrayValidator();use midorikocak\arraytools\ArrayValidator;
$toValidate = [
'id'=>'1',
'username'=>'uname',
'password'=>''
];
$arrayValidator = new ArrayValidator();
$arrayValidator->hasKey('id');
echo $arrayValidator->validate($toValidate); // true
$arrayValidator->hasKey('hasan');
echo $arrayValidator->validate($toValidate); // false$arrayValidator->hasKeys('id', 'username');
echo $arrayValidator->validate($toValidate); // true$arrayValidator->keys('id', 'username', 'password');
echo $arrayValidator->validate($toValidate); // true$arrayValidator->notEmpty('password');
echo $arrayValidator->validate($toValidate); // falseecho $arrayValidator
->keys('id', 'username', 'password')
->notEmpty('password')
->hasKeys('id', 'username')
->validate($toValidate); // falseA simple schema structure can be used for checking array values. Schema values can be one of boolean, domain, int, email, mac, float, regexp and string.
$schema = [
'username' => 'string',
'password' => 'string',
'email' => 'email',
];
$arrayValidator->schema($schema); // trueA function that accepts an array and returns bool value can be appended to last validation.
echo $arrayValidator->validate($toValidate, function($array){
return array_key_exists('key', $array);
}); // falseTo create custom validators, you may extend AbstractValidator class. Please check the source for details.
Mostly educational purposes. Please use at your own risk.
Please see CHANGELOG for more information on what has changed recently.
$ composer testPlease see CONTRIBUTING and CODE_OF_CONDUCT for details.
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.