Repository navigation
Expand file tree
/
Copy pathSeedingFactory.php
More file actions
71 lines (57 loc) · 1.47 KB
/
Copy pathSeedingFactory.php
File metadata and controls
71 lines (57 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
namespace Gcd\Seeding;
use Faker\Factory;
use Faker\Generator;
use Rhubarb\Stem\Exceptions\RecordNotFoundException;
use Rhubarb\Stem\Filters\Equals;
class SeedingFactory
{
private function __construct()
{
$this->faker = self::getFaker();
}
public static function get()
{
return new static();
}
/**
* @var Generator
*/
private static $_globalFaker;
/**
* @var Generator
*/
protected $faker;
/**
* Returns a Faker instance seeded based upon the seeders class name to ensure consistancy
*
* @return Generator
*/
public static function getFaker():Generator
{
if (!self::$_globalFaker) {
self::$_globalFaker = Factory::create('en-gb');
}
return self::$_globalFaker;
}
public function findByColumns($modelClass, $keyValuePairs = [])
{
$filters = [];
foreach($keyValuePairs as $key => $value){
$filters[] = new Equals($key, $value);
}
return $modelClass::findFirst(...$filters);
}
public function findOrCreateByColumns($modelClass, $keyValuePairs = [])
{
try {
return $this->findByColumns($modelClass, $keyValuePairs);
} catch (RecordNotFoundException $er){
$model = new $modelClass();
foreach($keyValuePairs as $key => $value) {
$model[$key] = $value;
}
return $model;
}
}
}