cloudbear / class-mapper
dev-main
2025-07-02 11:16 UTC
Requires
- php: ^8.4
- psr/http-message: ^2.0
- symfony/yaml: ^7.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.75
- phpstan/phpstan: ^2.1
This package is auto-updated.
Last update: 2025-07-02 10:07:01 UTC
README
Allows any array structure to be mapped to a class object.
Example
use Cloudbear\Common\Models\AutoResolvingModel;
class MyObject extends AutoResolvingModel
{
public string $hello;
}
new MyObject(['hello' => 'world'])->hello //-> (string) world
Supported Types
- Primitives
- DateTime
- stdClass (used when resulting value is unknown structure.)
- BackedEnum
- Any other
AutoResolvingModel
orAutoResolvingArrayModel
class
DateTime
The date format is adjustable via static::DATE_FORMAT
.
You can parse any int into a datetime as well:
use Cloudbear\Common\Models\AutoResolvingModel;
class MyObject extends AutoResolvingModel
{
public DateTime $timestamp;
}
new MyObject(['timestamp' => 1751446865])->timestamp //-> (DateTime) 2025-07-02T09:01:05Z
Array of Models
class MyObjectList extends AutoResolvingArrayModel
{
/**
* This const is used to determine the api property that's representing the array of objects. Default: 'items'.
*/
protected const string LIST_KEY = 'objects';
protected function getItemClass(): string
{
return MyObject::class;
}
}
new MyObjectList(['objects' => [['hello' => 'world']]])->items //-> MyObject[]
Changing property name
Keys are case-sensitive, so if you're changing cases, you'll need to map app your properties.
use Cloudbear\ClassMapper\Attributes\Key;
use Cloudbear\Common\Models\AutoResolvingModel;
class MyObject extends AutoResolvingModel
{
#[Key('hello')]
public string $foo;
}
new MyObject(['hello' => 'world'])->foo //-> (string) world
Excluding properties
The parser expects all properties to be part of the data that you are providing.
If you want certain properties to be ignored you can add the Exclude
attribute.
use Cloudbear\ClassMapper\Attributes\Exclude;
use Cloudbear\Common\Models\AutoResolvingModel;
class MyObject extends AutoResolvingModel
{
#[Exclude]
public string $foo;
#[Exclude]
public string $hello;
}
new MyObject(['hello' => 'world'])->foo //-> Uninitialized property exception