Guesser   A
last analyzed

Complexity

Total Complexity 32

Size/Duplication

Total Lines 163
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 32
lcom 1
cbo 8
dl 0
loc 163
ccs 0
cts 82
cp 0
rs 9.6
c 1
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 1
D guess() 0 67 17
D guessFormat() 0 25 10
A clean() 0 16 4
1
<?php
2
3
/*
4
 * This file is part of the PostmanGeneratorBundle package.
5
 *
6
 * (c) Vincent Chalamon <[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;
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
     * @param int|null $size Length of field, if known
134
     *
135
     * @return mixed
136
     */
137
    public function guessFormat($name, $size = null)
138
    {
139
        if (null !== ($value = parent::guessFormat($name))) {
140
            return $value;
141
        }
142
143
        switch ($name) {
144
            case 'mobile':
145
            case 'mobile_phone':
146
            case 'mobilePhone':
147
                return $this->generator->mobileNumber;
148
            case 'fax':
149
                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...
150
        }
151
152
        if (preg_match('/_name$/', $name) || preg_match('/Name$/', $name)) {
153
            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...
154
        }
155
156
        if (preg_match('/_time$/', $name) || preg_match('/Time$/', $name)) {
157
            return $this->generator->time;
158
        }
159
160
        return;
161
    }
162
163
    /**
164
     * @param mixed $value
165
     *
166
     * @return mixed
167
     */
168
    private function clean($value)
169
    {
170
        if (is_array($value)) {
171
            $value = array_map([$this, 'clean'], $value);
172
        }
173
174
        if ($value instanceof \Closure) {
175
            $value = call_user_func($value);
176
        }
177
178
        if ($value instanceof \DateTime) {
179
            $value = $value->format('Y-m-d H:i:s');
180
        }
181
182
        return preg_replace("/\n/", ', ', $value);
183
    }
184
}
185