EntityGuesser::fake()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 11
rs 10
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Knp\FriendlyContexts\Guesser;
4
5
use Knp\FriendlyContexts\Record\Collection\Bag;
6
7
class EntityGuesser extends AbstractGuesser implements GuesserInterface
8
{
9
    public function __construct(Bag $bag)
10
    {
11
        $this->bag = $bag;
0 ignored issues
show
Bug Best Practice introduced by
The property bag does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
12
    }
13
14
    public function supports(array $mapping)
15
    {
16
        if (array_key_exists('targetEntity', $mapping)) {
17
18
            return $this->bag->getCollection($mapping['targetEntity'])->count() > 0;
19
        }
20
21
        return false;
22
    }
23
24
    public function transform($str, array $mapping)
25
    {
26
        $str = strlen((string) $str) ? $str : null;
27
28
        if (null !== $record = $this->bag->getCollection($mapping['targetEntity'])->search($str)) {
29
30
            return $record->getEntity();
31
        }
32
33
        return null;
34
    }
35
36
    public function fake(array $mapping)
37
    {
38
        $collection = $this->bag->getCollection($mapping['targetEntity']);
39
40
        if (0 === $collection->count()) {
41
            throw new \Exception(sprintf('There is no record for "%s"', $mapping['targetEntity']));
42
        }
43
44
        $records = array_values($collection->all());
45
46
        return $records[array_rand($records)]->getEntity();
47
    }
48
49
    public function getName()
50
    {
51
        return 'entity';
52
    }
53
}
54