Completed
Pull Request — master (#4)
by Kévin
03:15
created

Guesser::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 12
ccs 0
cts 6
cp 0
rs 9.4285
cc 1
eloc 9
nc 1
nop 4
crap 2
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace PostmanGeneratorBundle\Faker\Guesser;
13
14
use Doctrine\Common\Inflector\Inflector;
15
use Dunglas\ApiBundle\Api\IriConverterInterface;
16
use Dunglas\ApiBundle\Api\ResourceCollectionInterface;
17
use Dunglas\ApiBundle\Mapping\AttributeMetadataInterface;
18
use Dunglas\ApiBundle\Mapping\ClassMetadataFactoryInterface;
19
use Faker\Generator;
20
use Faker\Guesser\Name;
21
22
class Guesser extends Name
23
{
24
    /**
25
     * @var IriConverterInterface
26
     */
27
    private $iriConverter;
28
29
    /**
30
     * @var ResourceCollectionInterface
31
     */
32
    private $resourceCollection;
33
34
    /**
35
     * @var ClassMetadataFactoryInterface
36
     */
37
    private $classMetadataFactory;
38
39
    /**
40
     * @param Generator                     $generator
41
     * @param IriConverterInterface         $iriConverter
42
     * @param ResourceCollectionInterface   $resourceCollection
43
     * @param ClassMetadataFactoryInterface $classMetadataFactory
44
     */
45
    public function __construct(
46
        Generator $generator,
47
        IriConverterInterface $iriConverter,
48
        ResourceCollectionInterface $resourceCollection,
49
        ClassMetadataFactoryInterface $classMetadataFactory
50
    ) {
51
        parent::__construct($generator);
52
53
        $this->iriConverter = $iriConverter;
54
        $this->resourceCollection = $resourceCollection;
55
        $this->classMetadataFactory = $classMetadataFactory;
56
    }
57
58
    /**
59
     * @param AttributeMetadataInterface $attributeMetadata
60
     *
61
     * @return mixed
62
     */
63
    public function guess(AttributeMetadataInterface $attributeMetadata)
64
    {
65
        $value = null;
66
        $type = null;
67
        if (true === ($isDoctrine = isset($attributeMetadata->getTypes()[0]))) {
68
            $type = $attributeMetadata->getTypes()[0];
69
        }
70
71
        // Guess associations
72
        if ($isDoctrine && 'object' === $type->getType() && 'DateTime' !== $type->getClass()) {
73
            $class = $type->isCollection() ? $type->getCollectionType()->getClass() : $type->getClass();
74
            $resource = $this->resourceCollection->getResourceForEntity($class);
75
            $classMetadata = $this->classMetadataFactory->getMetadataFor(
76
                $resource->getEntityClass(),
77
                $resource->getNormalizationGroups(),
78
                $resource->getDenormalizationGroups(),
79
                $resource->getValidationGroups()
80
            );
81
            $id = $this->guess($classMetadata->getIdentifier());
82
            $value = $this->iriConverter->getIriFromResource($resource).'/'.$id;
83
84
            if ($type->isCollection()) {
85
                $value = [$value];
86
            }
87
        }
88
89
        // Guess by faker
90
        if (null === $value) {
91
            try {
92
                $value = call_user_func([$this->generator, $attributeMetadata->getName()]);
93
            } catch (\InvalidArgumentException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
94
            }
95
        }
96
97
        // Guess by field name
98
        if (null === $value) {
99
            $value = $this->guessFormat(Inflector::tableize($attributeMetadata->getName()));
100
        }
101
102
        // Guess by Doctrine type
103
        if (null === $value && $isDoctrine) {
104
            switch ($type->getType()) {
105
                case 'string':
106
                    $value = $this->generator->sentence;
107
                    break;
108
                case 'int':
109
                    $value = $this->generator->numberBetween;
0 ignored issues
show
Bug introduced by
The property numberBetween does not seem to exist in Faker\Generator.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
110
                    break;
111
                case 'bool':
112
                    $value = $this->generator->boolean;
0 ignored issues
show
Bug introduced by
The property boolean does not seem to exist in Faker\Generator.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
113
                    break;
114
                case 'object':
115
                    if ('DateTime' !== $type->getClass()) {
116
                        throw new \InvalidArgumentException(sprintf(
117
                            'Unknown Doctrine object type %s in field %s',
118
                            $type->getClass(),
119
                            $attributeMetadata->getName()
120
                        ));
121
                    }
122
123
                    $value = $this->generator->dateTime;
124
                    break;
125
            }
126
        }
127
128
        return $this->clean($value);
129
    }
130
131
    /**
132
     * @param string $name
133
     *
134
     * @return mixed
135
     */
136
    public function guessFormat($name)
137
    {
138
        if (null !== ($value = parent::guessFormat($name))) {
139
            return $value;
140
        }
141
142
        switch ($name) {
143
            case 'mobile':
144
            case 'mobile_phone':
145
            case 'mobilePhone':
146
                return $this->generator->mobileNumber;
147
            case 'fax':
148
                return $this->generator->phoneNumber;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->generator->phoneNumber; (string) is incompatible with the return type of the parent method Faker\Guesser\Name::guessFormat of type Closure|null.

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:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
149
        }
150
151
        if (preg_match('/_name$/', $name) || preg_match('/Name$/', $name)) {
152
            return $this->generator->name;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->generator->name; (string) is incompatible with the return type of the parent method Faker\Guesser\Name::guessFormat of type Closure|null.

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:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
153
        }
154
155
        if (preg_match('/_time$/', $name) || preg_match('/Time$/', $name)) {
156
            return $this->generator->time;
157
        }
158
    }
159
160
    /**
161
     * @param mixed $value
162
     *
163
     * @return mixed
164
     */
165
    private function clean($value)
166
    {
167
        if (is_array($value)) {
168
            $value = array_map([$this, 'clean'], $value);
169
        }
170
171
        if ($value instanceof \Closure) {
172
            $value = call_user_func($value);
173
        }
174
175
        if ($value instanceof \DateTime) {
176
            $value = $value->format('Y-m-d H:i:s');
177
        }
178
179
        return preg_replace("/\n/", ', ', $value);
180
    }
181
}
182