|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* To change this license header, choose License Headers in Project Properties. |
|
5
|
|
|
* To change this template file, choose Tools | Templates |
|
6
|
|
|
* and open the template in the editor. |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace Maslosoft\Mangan\Transformers; |
|
10
|
|
|
|
|
11
|
|
|
use Maslosoft\Addendum\Interfaces\AnnotatedInterface; |
|
12
|
|
|
use Maslosoft\Mangan\Exceptions\TransformatorException; |
|
13
|
|
|
use Maslosoft\Mangan\Interfaces\Transformators\TransformatorInterface; |
|
14
|
|
|
use Symfony\Component\Yaml\Yaml; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* YamlString |
|
18
|
|
|
* |
|
19
|
|
|
* @author Piotr Maselkowski <pmaselkowski at gmail.com> |
|
20
|
|
|
*/ |
|
21
|
|
|
class YamlString implements TransformatorInterface |
|
22
|
|
|
{ |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* Returns the given object as an associative array |
|
26
|
|
|
* @param AnnotatedInterface|object $model |
|
27
|
|
|
* @param string[] $fields Fields to transform |
|
28
|
|
|
* @return array an associative array of the contents of this object |
|
29
|
|
|
*/ |
|
30
|
|
|
public static function fromModel(AnnotatedInterface $model, $fields = []) |
|
31
|
|
|
{ |
|
32
|
|
|
return Yaml::dump(YamlArray::fromModel($model, $fields)); |
|
|
|
|
|
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* Create document from array |
|
37
|
|
|
* |
|
38
|
|
|
* @param mixed[] $data |
|
39
|
|
|
* @param string|object $className |
|
40
|
|
|
* @param AnnotatedInterface $instance |
|
41
|
|
|
* @return AnnotatedInterface |
|
42
|
|
|
* @throws TransformatorException |
|
43
|
|
|
*/ |
|
44
|
|
|
public static function toModel($data, $className = null, AnnotatedInterface $instance = null) |
|
45
|
|
|
{ |
|
46
|
|
|
return YamlArray::toModel(Yaml::parse($data), $className, $instance); |
|
|
|
|
|
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
} |
|
50
|
|
|
|
If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.
Let’s take a look at an example:
Our function
my_functionexpects aPostobject, and outputs the author of the post. The base classPostreturns a simple string and outputting a simple string will work just fine. However, the child classBlogPostwhich is a sub-type ofPostinstead decided to return anobject, and is therefore violating the SOLID principles. If aBlogPostwere passed tomy_function, PHP would not complain, but ultimately fail when executing thestrtouppercall in its body.