Skip to content

Commit

Permalink
Merge pull request #5 from Shureban/v1.0.0
Browse files Browse the repository at this point in the history
V1.0.0
  • Loading branch information
Shureban authored Dec 1, 2022
2 parents a85b562 + 249cfaa commit 9d32196
Show file tree
Hide file tree
Showing 39 changed files with 746 additions and 127 deletions.
206 changes: 200 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,212 @@ composer require shureban/laravel-object-mapper
Add the following class to the `providers` array in `config/app.php`:

```php
Shureban\LaravelSearcher\ObjectMapperServiceProvider::class,
Shureban\LaravelObjectMapper\ObjectMapperServiceProvider::class,
```

You can also publish the config file to change implementations (ie. interface to specific class).

```shell
php artisan vendor:publish --provider="Shureban\LaravelSearcher\ObjectMapperServiceProvider"
php artisan vendor:publish --provider="Shureban\LaravelObjectMapper\ObjectMapperServiceProvider"
```

## How to use

- base types
- class with constructor
- class without countruector
- setters
You have 3 options to use `ObjectMapper`

### Inheritance

Your mapped object (dto) must inheritance from `\Shureban\LaravelObjectMapper\MappableObject`

```php
class User extends MappableObject
{
public int $id;
}

$user1 = (new User())->mapFromJson('{"id": 10}');
$user2 = (new User())->mapFromArray(['id' => 10]);
$user3 = (new User())->mapFromRequest($formRequest);
```

### Using trait

Your mapped object (dto) must use `\Shureban\LaravelObjectMapper\MappableTrait`

```php
class User
{
use MappableTrait;

public int $id;
}

$user1 = (new User())->mapFromJson('{"id": 10}');
$user2 = (new User())->mapFromArray(['id' => 10]);
$user3 = (new User())->mapFromRequest($formRequest);
```

### Delegate mapping to ObjectMapper

```php
class User {
public int $id;
}

$user1 = (new ObjectMapper(new User()))->mapFromJson('{"id": 10}');
$user2 = (new ObjectMapper(new User()))->mapFromArray(['id' => 10]);
$user3 = (new ObjectMapper(new User()))->mapFromRequest($formRequest);
```

## Mappable cases

Below you will see cases which you can use for mapping data into your object

### Simple types

- `mixed`
- `string`
- `bool`, `boolean`
- `int`, `integer`
- `double`, `float`
- `array`
- `object`

### Box types

- `Carbon`
- `DateTime`
- `Collection`

### Custom types

- `CustomClass`
- `Enum`
- `EloquentModel`

### Array of types

That typo of mapping may be realized only via phpDoc notation

- `int[]`
- `int[][]`
- `DateTime[]`
- `CustomClass[]`

### Special cases

#### Constructor

If your type object has 1 required parameter and value is NOT an array, ObjectMapper will build instance of this type
via constructor call
If your type object has 0 or more than 1 required parameters, it will throw WrongConstructorParametersNumberException
exception

Correct case:

```php
class User
{
public int $id;

public function __construct(int $id) {
$this->id = $id;
}
}
```

Wrong case:

```php
class User
{
public int $id;
public string $name;

public function __construct(int $id, string $name) {
$this->id = $id;
$this->name = $name;
}
}
```

#### PhpDoc

PhpDoc type hinting has much more priority than main type.

```php
class User
{
/**
* @var int
*/
public int $id;
/**
* @var DateTime
*/
public $dateOfBirthday;
/**
* @var Address[]
*/
public array $addresses;
}
```

#### Setters

If you want to realize your own logic for setting value, you may place setter method in your mapped object
This setter should start from `set` word and been in camelCase notation.

```php
class User
{
public string $id;
public DateTime $dateOfBirthday;

public function setId(int $id, array $rawData = []): void
{
$this->id = Hash::make($id);
}

public function setDateOfBirthday(string $dateOfBirthday, array $rawData = []): void
{
$this->dateOfBirthday = new DateTime($dateOfBirthday);
}
}

$user = (new ObjectMapper(new User()))->mapFromArray(['id' => 10, 'dateOfBirthday' => '1991-01-01']);

echo $user->id; // $2y$10$XqHrk0oXa7.9AihthdVxW.dd637zj9EhlTJX0eUEKiV61dbs7a7ZO
echo $user->dateOfBirthday->format('Y'); // 1991
```

Some words about second parameter `$rawData`. Value of this parameter depends on method selected for mapping

- mapFromJson - $rawData will be JSON
- mapFromArray - $rawData will be Array
- mapFromRequest - $rawData will be FormRequest object

#### Readonly parameters

Readonly parameters will always be skipped

```php
class User
{
public readonly int $id;
}

$user = (new ObjectMapper(new User()))->mapFromArray(['id' => 10]);

echo $user->id; // 0
```

## Config rewriting

In `object_mapper.php` config file have been presented all mappable types classes. You have opportunity to rewrite
mapping flow or realize you own one.

If you need to create your own type mapping, follow this way:

- create class inherited from `\Shureban\LaravelObjectMapper\Types\Type`
- place you type into config file in `type -> box` array
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
}
],
"minimum-stability": "dev",
"version": "0.4.0",
"version": "1.0.0",
"autoload": {
"psr-4": {
"Shureban\\LaravelObjectMapper\\": "src/"
Expand Down
4 changes: 0 additions & 4 deletions config/mapper.php

This file was deleted.

48 changes: 48 additions & 0 deletions config/object_mapper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

use Carbon\Carbon;
use Illuminate\Support\Carbon as CarbonSupport;
use Illuminate\Support\Collection;
use Shureban\LaravelObjectMapper\Types\BoxTypes\CarbonType;
use Shureban\LaravelObjectMapper\Types\BoxTypes\CollectionType;
use Shureban\LaravelObjectMapper\Types\BoxTypes\DateTimeType;
use Shureban\LaravelObjectMapper\Types\Custom\CustomType;
use Shureban\LaravelObjectMapper\Types\Custom\EnumType;
use Shureban\LaravelObjectMapper\Types\Custom\ModelType;
use Shureban\LaravelObjectMapper\Types\SimpleTypes\ArrayType;
use Shureban\LaravelObjectMapper\Types\SimpleTypes\BoolType;
use Shureban\LaravelObjectMapper\Types\SimpleTypes\FloatType;
use Shureban\LaravelObjectMapper\Types\SimpleTypes\IntType;
use Shureban\LaravelObjectMapper\Types\SimpleTypes\MixedType;
use Shureban\LaravelObjectMapper\Types\SimpleTypes\ObjectType;
use Shureban\LaravelObjectMapper\Types\SimpleTypes\StringType;

return [
'types' => [
'simple' => [
'string' => StringType::class,
'float' => FloatType::class,
'double' => FloatType::class,
'int' => IntType::class,
'integer' => IntType::class,
'bool' => BoolType::class,
'boolean' => BoolType::class,
'array' => ArrayType::class,
'object' => ObjectType::class,
'mixed' => MixedType::class,
],
'box' => [
DateTime::class => DateTimeType::class,
CarbonSupport::class => CarbonType::class,
Carbon::class => CarbonType::class,
'Carbon' => CarbonType::class,
Collection::class => CollectionType::class,
'Collection' => CollectionType::class,
],
'other' => [
'custom' => CustomType::class,
'enum' => EnumType::class,
'model' => ModelType::class,
],
],
];
9 changes: 4 additions & 5 deletions src/ClassExtraInformation.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ class ClassExtraInformation
private ReflectionClass $class;
private string $content = '';

/**
* @param ReflectionClass $class
*/
public function __construct(ReflectionClass $class)
{
$this->class = $class;
Expand Down Expand Up @@ -45,11 +48,7 @@ public function getFullObjectUseNamespace(string $objectName): ?string

$namespace = sprintf('%s\%s', $this->getNamespace(), $objectName);

if (class_exists($namespace)) {
return $namespace;
}

return null;
return class_exists($namespace) ? $namespace : null;
}

/**
Expand Down
9 changes: 9 additions & 0 deletions src/Exceptions/ObjectMapperException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace Shureban\LaravelObjectMapper\Exceptions;

use Exception;

abstract class ObjectMapperException extends Exception
{
}
18 changes: 18 additions & 0 deletions src/Exceptions/ParseJsonException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace Shureban\LaravelObjectMapper\Exceptions;

use Throwable;

class ParseJsonException extends ObjectMapperException
{
/**
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct(string $message, int $code = 0, ?Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
}
3 changes: 1 addition & 2 deletions src/Exceptions/UnknownDataFormatException.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@

namespace Shureban\LaravelObjectMapper\Exceptions;

use Exception;
use Throwable;

class UnknownDataFormatException extends Exception
class UnknownDataFormatException extends ObjectMapperException
{
public function __construct(int $code = 0, ?Throwable $previous = null)
{
Expand Down
3 changes: 1 addition & 2 deletions src/Exceptions/UnknownPropertyTypeException.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@

namespace Shureban\LaravelObjectMapper\Exceptions;

use Exception;
use Throwable;

class UnknownPropertyTypeException extends Exception
class UnknownPropertyTypeException extends ObjectMapperException
{
/**
* @param string $property
Expand Down
20 changes: 20 additions & 0 deletions src/Exceptions/WrongConstructorParametersNumberException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace Shureban\LaravelObjectMapper\Exceptions;

use Throwable;

class WrongConstructorParametersNumberException extends ObjectMapperException
{
/**
* @param string $class
* @param int $code
* @param Throwable|null $previous
*/
public function __construct(string $class, int $code = 0, ?Throwable $previous = null)
{
$message = sprintf('Wrong constructor parameters number: %s', $class);

parent::__construct($message, $code, $previous);
}
}
8 changes: 8 additions & 0 deletions src/MappableObject.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace Shureban\LaravelObjectMapper;

abstract class MappableObject
{
use MappableTrait;
}
Loading

0 comments on commit 9d32196

Please sign in to comment.