FakeDataGenerator::getFaker()   B
last analyzed

Complexity

Conditions 5
Paths 8

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 5

Importance

Changes 5
Bugs 3 Features 3
Metric Value
cc 5
eloc 12
c 5
b 3
f 3
nc 8
nop 2
dl 0
loc 24
ccs 6
cts 6
cp 1
crap 5
rs 8.5125
1
<?php namespace BuildR\TestTools\Traits;
2
3
use Faker\Factory as FakerFactory;
4
use PHPUnit_Framework_TestCase;
5
use \InvalidArgumentException;
6
7
/**
8
 * Common trait that allow easy integration of Faker PHP library
9
 *
10
 * BuildR PHP Framework
11
 *
12
 * @author Zoltán Borsos <[email protected]>
13
 * @package TestTools
14
 * @subpackage Traits
15
 *
16
 * @copyright    Copyright 2016, Zoltán Borsos.
17
 * @license      https://github.com/BuildrPHP/Test-Tools/blob/master/LICENSE.md
18
 * @link         https://github.com/BuildrPHP/Test-Tools
19
 */
20
trait FakeDataGenerator {
21
22
    /**
23
     * Store faker instances by locale
24
     *
25
     * @type \Faker\Generator[]
26
     */
27
    protected $fakerInstances = [];
28
29
    /**
30
     * Returns a new faker instance with the defined locale.
31
     * This function store created instances by locale, if you want to create
32
     * a new instance pass TRUE to $forceReCreate parameter
33
     *
34
     * @param string $locale The locale of the instance you want
35
     * @param bool $forceReCreate When passed any stored instance overwritten by a new one
36
     *
37
     * @return \Faker\Generator|NULL
38
     */
39 2
    public function getFaker($locale = 'en_US', $forceReCreate = FALSE) {
40 2
        if(isset($this->fakerInstances[$locale]) && $forceReCreate === FALSE) {
41 1
            return $this->fakerInstances[$locale];
42
        }
43
44
        try {
45 2
            $faker = FakerFactory::create($locale);
46 2
            $this->fakerInstances[$locale] = $faker;
47
48 2
            return $this->fakerInstances[$locale];
49
            //@codeCoverageIgnoreStart
50
        } catch(InvalidArgumentException $e) {
51
            //Probably this should never happen
52
53
            //If this is a PHPUnit test case we fail the test
54
            if($this instanceof PHPUnit_Framework_TestCase) {
55
                $msg = 'Failed to create Faker instance with locale: ' . $locale . ' Message: ' . $e->getMessage();
56
                $this->fail($msg);
57
            }
58
59
            return NULL;
60
            //@codeCoverageIgnoreEnd
61
        }
62
    }
63
64
}
65