artem-prozorov /
prettybxfixtures
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace PrettyBx\Fixtures; |
||
| 6 | |||
| 7 | use PrettyBx\Support\Facades\FileManager; |
||
| 8 | use Faker\Generator; |
||
| 9 | |||
| 10 | class FixtureManager |
||
| 11 | { |
||
| 12 | /** |
||
| 13 | * @var string $folder |
||
| 14 | */ |
||
| 15 | protected $folder; |
||
| 16 | |||
| 17 | /** |
||
| 18 | * @var $faker |
||
|
0 ignored issues
–
show
Documentation
Bug
introduced
by
Loading history...
|
|||
| 19 | */ |
||
| 20 | protected static $faker; |
||
| 21 | |||
| 22 | public function __construct(string $folder) |
||
| 23 | { |
||
| 24 | if (! FileManager::exists($folder)) { |
||
| 25 | throw new \InvalidArgumentException('No such folder: ' . $folder); |
||
| 26 | } |
||
| 27 | |||
| 28 | $this->folder = $folder; |
||
| 29 | } |
||
| 30 | |||
| 31 | /** |
||
| 32 | * Returns a fixture |
||
| 33 | * |
||
| 34 | * @access public |
||
| 35 | * @param string $code |
||
| 36 | * @param array $additional Default: [] |
||
| 37 | * @return array |
||
| 38 | */ |
||
| 39 | public function make(string $code, array $additional = []): array |
||
| 40 | { |
||
| 41 | $code = str_replace('.', '/', $code); |
||
| 42 | |||
| 43 | $path = $this->folder . '/' . $code . '.php'; |
||
| 44 | |||
| 45 | if (! FileManager::exists($path)) { |
||
| 46 | throw new \InvalidArgumentException('No such fixture: ' . $path); |
||
| 47 | } |
||
| 48 | |||
| 49 | $fixture = FileManager::include($path); |
||
| 50 | |||
| 51 | if (! is_array($fixture)) { |
||
| 52 | throw new \InvalidArgumentException('Fixture must be a valid array'); |
||
| 53 | } |
||
| 54 | |||
| 55 | return array_merge($fixture, $additional); |
||
| 56 | } |
||
| 57 | |||
| 58 | /** |
||
| 59 | * makeMany. |
||
| 60 | * |
||
| 61 | * @access public |
||
| 62 | * @param string $code |
||
| 63 | * @param int $quantity |
||
| 64 | * @param array $additional Default: [] |
||
| 65 | * @return array |
||
| 66 | */ |
||
| 67 | public function makeMany(string $code, int $quantity, array $additional = []): array |
||
| 68 | { |
||
| 69 | $data = []; |
||
| 70 | |||
| 71 | while ($quantity > 0) { |
||
| 72 | $data[] = $this->make($code, $additional); |
||
| 73 | |||
| 74 | --$quantity; |
||
| 75 | } |
||
| 76 | |||
| 77 | return $data; |
||
| 78 | } |
||
| 79 | |||
| 80 | /** |
||
| 81 | * getFaker. |
||
| 82 | * |
||
| 83 | * @access public |
||
| 84 | * @return Generator |
||
| 85 | */ |
||
| 86 | public static function getFaker(): Generator |
||
| 87 | { |
||
| 88 | if (empty(static::$faker)) { |
||
| 89 | static::$faker = \Faker\Factory::create(); |
||
| 90 | } |
||
| 91 | |||
| 92 | return static::$faker; |
||
| 93 | } |
||
| 94 | } |
||
| 95 |