Completed
Push — master ( f33bf1...6be0b2 )
by Freek
01:44
created

ArgumentValueProvider::getValue()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 15
nc 7
nop 4
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 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
     * @throws \Spatie\MailableTest\Exceptions\CouldNotDetermineValue
28
     */
29
    public function getValue(string $mailableClass, string $argumentName, string $argumentType = '', $defaultValue = null)
0 ignored issues
show
Unused Code introduced by
The parameter $mailableClass is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
30
    {
31
        if ($argumentType === 'int') {
32
            return $defaultValue ?? $this->faker->numberBetween(1, 100);
33
        }
34
35
        if ($argumentType === 'string') {
36
            return $defaultValue ?? $this->faker->sentence();
37
        }
38
39
        if ($argumentType === 'bool') {
40
            $defaultValue = ($defaultValue == 'false' ? false : $defaultValue);
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($argumentValue, $id = $defaultValue);
52
        }
53
54
        return $argumentValue;
55
    }
56
57
    /**
58
     * @param \Illuminate\Database\Eloquent\Model $model
59
     * @param string|int|null $id
60
     *
61
     * @return \Illuminate\Database\Eloquent\Model
62
     * @throws \Spatie\MailableTest\Exceptions\CouldNotDetermineValue
63
     */
64
    protected function getModelInstance(Model $model,  $id): Model
65
    {
66
        $modelInstance = $id ? $model->find($id) : $model->first();
67
68
        if (! $modelInstance) {
69
            throw CouldNotDetermineValue::noModelInstanceFound($model);
70
        }
71
72
        return $modelInstance;
73
    }
74
}
75