1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\MailableTest; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use Faker\Generator; |
7
|
|
|
use Illuminate\Database\Eloquent\Model; |
8
|
|
|
use Spatie\MailableTest\Exceptions\CouldNotDetermineValue; |
9
|
|
|
|
10
|
|
|
class FakerArgumentValueProvider implements ArgumentValueProvider |
11
|
|
|
{ |
12
|
|
|
/** @var \Faker\Generator */ |
13
|
|
|
protected $faker; |
14
|
|
|
|
15
|
|
|
public function __construct(Generator $faker) |
16
|
|
|
{ |
17
|
|
|
$this->faker = $faker; |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @param string $mailableClass |
22
|
|
|
* @param string $argumentName |
23
|
|
|
* @param string $argumentType |
24
|
|
|
* @param string|null $defaultValue |
25
|
|
|
* |
26
|
|
|
* @return mixed |
27
|
|
|
*/ |
28
|
|
|
public function getValue(string $mailableClass, string $argumentName, string $argumentType = '', $defaultValue = null) |
29
|
|
|
{ |
30
|
|
|
if ($argumentType === 'int') { |
31
|
|
|
return $defaultValue ?? $this->faker->numberBetween(1, 100); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
if ($argumentType === 'string') { |
35
|
|
|
return $defaultValue ?? $this->faker->sentence(); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
if ($argumentType === 'bool') { |
39
|
|
|
$defaultValue = ($defaultValue == 'false' ? false : $defaultValue); |
40
|
|
|
|
41
|
|
|
return $defaultValue ?? $this->faker->boolean(50); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
try { |
45
|
|
|
$argumentValue = app($argumentType); |
46
|
|
|
} catch (Exception $exception) { |
47
|
|
|
throw CouldNotDetermineValue::create($argumentType, $argumentName, $exception); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
if ($argumentValue instanceof Model) { |
51
|
|
|
return $this->getModelInstance($mailableClass, $argumentName, $argumentValue, $id = $defaultValue); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return $argumentValue; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @param string $mailableClass |
59
|
|
|
* @param string $argumentName |
60
|
|
|
* @param \Illuminate\Database\Eloquent\Model $model |
61
|
|
|
* @param string|int|null $id |
62
|
|
|
* |
63
|
|
|
* @return \Illuminate\Database\Eloquent\Model |
64
|
|
|
* @throws \Spatie\MailableTest\Exceptions\CouldNotDetermineValue |
65
|
|
|
*/ |
66
|
|
|
protected function getModelInstance(string $mailableClass, string $argumentName, Model $model, $id): Model |
|
|
|
|
67
|
|
|
{ |
68
|
|
|
$modelInstance = $id ? $model->find($id) : $model->first(); |
69
|
|
|
|
70
|
|
|
if (! $modelInstance) { |
71
|
|
|
throw CouldNotDetermineValue::noModelInstanceFound($model); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return $modelInstance; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.