PHPackages                             emirhanbalkac/utf8-supported-mapper-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. emirhanbalkac/utf8-supported-mapper-php

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

emirhanbalkac/utf8-supported-mapper-php
=======================================

Model mapping, unmapping and validation

v2.2.16(9y ago)05421MITPHP

Since Sep 3Pushed 3y agoCompare

[ Source](https://github.com/emirhanbalkac/utf8-supported-mapper-php)[ Packagist](https://packagist.org/packages/emirhanbalkac/utf8-supported-mapper-php)[ RSS](/packages/emirhanbalkac-utf8-supported-mapper-php/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (5)Dependencies (2)Versions (23)Used By (0)

PHP Model Mapper
================

[](#php-model-mapper)

Feature list:
-------------

[](#feature-list)

- Map PHP class properties from json, xml, arrays and other objects.
- Unmap from model to json, xml, array and stdClass
- Nested models supported
- Annotations provide custom naming, types and rules for model properties
- Properly annotated, mapped models can be validated for different types and rules

Installation
------------

[](#installation)

```
composer require runz0rd/mapper-php

```

How it works
------------

[](#how-it-works)

The mapper goes trough all the property names (with @name you could change property name mappings) of your model and maps the ones with the same name from the source (json/xml/array/stdClass), if available. The mapped model can be used as is, but it is recommended you validate it after mapping. Required properties (@required) must always be set and of the appropriate type (if set with @var or @rule). Not required properties may not be set (null), but if set, must match defined types or rules (if set with @var or @rule) to pass validation. So, if you have:

```
{
  "name": "Jack",
  "type": "human",
  "age": 35,
  "isEmployed": true,
  "custom-desc": "lazy"
}
```

You could make a model like this:

```
class SomeGuy {

    /**
     * @required
     * @var string
     */
    public $name;

    /**
     * @required createSomeGuy
     * @var string
     */
    public $type;

    /**
     * @rule limit(1,150)
     * @var integer
     */
    public $age;

    /**
     * @var boolean
     */
    public $isEmployed;

    /**
     * @name custom-desc
     * @var string
     */
    public $description
}
```

Validation would **fail** if:

- You use **createSomeGuy** action, without (null) **$type** (required only on createSomeGuy action)
- Without (null) **$name** (always required)
- You use **createSomething** action, and **$type** is not a string
- **$name** is not a string
- **$age** is set (not null), but not an integer, or between 1 and 150 (rule)
- **$isEmployed** is set (not null) but not a boolean

Note that **$description** would get mapped because it has the @name annotation set, and there is a property in the source matching that name (custom-desc).

Annotations
-----------

[](#annotations)

Heres a list of annotations we can use in models:

annotationused abovedescription@varpropertyUsed to declare the type of the property (validation). This is an alias for @rule annotation. See below for a list of pre-defined types (rules) for model validation@namepropertyUsed to change the property name, while mapping and unmapping (can be used with special characters, but be careful if youre working with XML)@requiredpropertyUsed to declare that a property is required for a specific action (validation). Use without the action to make the property always required@rulepropertyUsed to enforce specific rules and filters on the property value (validation). You can use the predefined rules or create and import your own@xmlRootclassUsed to name the xml root name of the element (only for xml mapping)@xmlVersionclassVersion of xml document (only for xml mapping)@xmlEncodingclassEncoding document. Default utf-8. (only for xml mapping)@xmlNamespacesclassDocument namespaces. Without prefix xmlns. Example : "" xhtml="". (only for xml mapping)@xmlAttributepropertyUsed to declare that a property is a xml attribute for the element. Also used for namespaces (only for xml mapping)@xmlNodeValuepropertyUsed to declare that a property contains the text node value (only for xml mapping). Please see the models in tests/ (XmlTestModel)**@var** annotation type list:

typedescriptionanyanythingstringstring typeintegerinteger typebooleanboolean typedoubledouble typefloatfloat typearrayarray type\[\]array typeobjectstdClass for examplestring\[\]string array typeinteger\[\]integer array typeboolean\[\]boolean array typeobject\[\]object array typeNamedModelany named class (model) (if from another namespace, make sure you include it!)NamedModel\[\]any model arrayUsage
-----

[](#usage)

### Mapping

[](#mapping)

Use MappableTrait inside your model to call methods from the model itself:

```
$model->mapFromArray($myArray);
$model->mapFromJson($myJson);
$model->mapFromXml($myXml);
$model->mapFromObject($myObject);
```

Or by using the ModelMapper class, providing it with the instance of the model you want mapped and the source object:

```
$model = new Model();
$mapper = new ModelMapper();
$mapper->map($sourceObject, $model);
```

### Unmapping

[](#unmapping)

Use ConvertibleTrait inside your model to call methods from the model itself:

```
$myArray = $model->toArray();
$myJson = $model->toJson();
$myXml = $model->toXml();
$myObject = $model->toObject();
```

Or by using the ModelMapper class, providing it with the mapped model (converts to stdClass):

```
$mapper = new ModelMapper();
$myObject = $mapper->unmap($myModel);
```

### Validation

[](#validation)

Validation will check your mapped model's property types, custom rules, and whether the property is required or not.

Validate your mapped models with ValidatableTrait, by providing it with the desired validation action:

```
$model->validate('createAction');
```

Or if you want to validate only the properties that are always required:

```
$model->validate();
```

You can also use the validator itself:

```
$model = new Model();
$validator = new ModelValidator();
$validator->validate($model, 'myAction');
```

### Rules

[](#rules)

Rules are used for custom validation of mapped property values.

```
/**
 * @rule email
 */
public $email;
```

This would check if the property value contains a valid email string.

You can pass additional parameters for rules.

```
/**
 * @rule limit(0,99)
 */
public $value;
```

If setup properly this custom rule would check if the property value is between 0 and 99.

### Rule setup

[](#rule-setup)

Lets use the limit rule example from above, to create a new custom rule:

```
use Common\ModelReflection\ModelProperty;
use Validator\IRule;
use Validator\ModelValidatorException;

class LimitRule implements IRule {

    function getNames() {
        return ['limit'];
    }

    function validate(ModelProperty $property, array $params = []) {
        if($property->getPropertyValue() < $params[0] || $property->getPropertyValue() > $params[1]) {
            throw new ModelValidatorException('Value is not between '.$params[0].' and '.$params[1]);
        }
    }
}
```

In the example above, we can configure a new rule, by:

- Defining an array of names (aliases) which serve as the name of the rule in the annotation (getNames)
- Providing a validation definition and throwing an exception if it doesnt pass (validate)
- The rule parameters (0,99) come in through the $params array, in order in which they were provided

For more information please take a look at the pre-defined rule classes and the IRule interface.

### Loading your rules

[](#loading-your-rules)

```
$model = new Model();
$myCustomRule = new MyCustomRule();
$validator = new ModelValidator();
$validator->useRule($myCustomRule);
$validator->loadRules('/path/to/rules/');
$validator->validate($model, 'myAction');
```

In the example above we can use custom rules by providing them to the validator one by one (useRule) or providing a path to a directory containing rules (loadRules).

Code examples
-------------

[](#code-examples)

Please see the tests and models used in it.

Stuff that got me inspired:
---------------------------

[](#stuff-that-got-me-inspired)

[cweiske/jsonmapper](https://github.com/cweiske/jsonmapper)

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity13

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity73

Established project with proven stability

 Bus Factor1

Top contributor holds 51.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~113 days

Recently: every ~398 days

Total

20

Last Release

1397d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/38dc5f0ea745ca8cf6e841a1180e38a2a22727ff33902e2d52377dc4706c9231?d=identicon)[emirhanbalkac](/maintainers/emirhanbalkac)

---

Top Contributors

[![runz0rd](https://avatars.githubusercontent.com/u/11473751?v=4)](https://github.com/runz0rd "runz0rd (21 commits)")[![milos-pejanovic-devtech](https://avatars.githubusercontent.com/u/10724671?v=4)](https://github.com/milos-pejanovic-devtech "milos-pejanovic-devtech (8 commits)")[![emirhanbalkac](https://avatars.githubusercontent.com/u/48518989?v=4)](https://github.com/emirhanbalkac "emirhanbalkac (6 commits)")[![somov](https://avatars.githubusercontent.com/u/6071978?v=4)](https://github.com/somov "somov (2 commits)")[![uguurozkan](https://avatars.githubusercontent.com/u/6731054?v=4)](https://github.com/uguurozkan "uguurozkan (2 commits)")[![myigituzun](https://avatars.githubusercontent.com/u/112015990?v=4)](https://github.com/myigituzun "myigituzun (1 commits)")[![snezana-ralic-devtech](https://avatars.githubusercontent.com/u/6009795?v=4)](https://github.com/snezana-ralic-devtech "snezana-ralic-devtech (1 commits)")

---

Tags

phpvalidatorlibraryobjectmappertraits

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/emirhanbalkac-utf8-supported-mapper-php/health.svg)

```
[![Health](https://phpackages.com/badges/emirhanbalkac-utf8-supported-mapper-php/health.svg)](https://phpackages.com/packages/emirhanbalkac-utf8-supported-mapper-php)
```

###  Alternatives

[runz0rd/mapper-php

Model mapping, unmapping and validation

17451.9k2](/packages/runz0rd-mapper-php)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
