BaseFormRequest::translationMessages()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php namespace Modules\Core\Internationalisation;
2
3
use Illuminate\Foundation\Http\FormRequest;
4
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
5
6
abstract class BaseFormRequest extends FormRequest
7
{
8
    /**
9
     * Set the translation key prefix for attributes.
10
     * @var string
11
     */
12
    protected $translationsAttributesKey = 'validation.attributes.';
13
    /**
14
     * Current processed locale
15
     * @var string
16
     */
17
    protected $localeKey;
18
19
    /**
20
     * Return an array of rules for translatable fields
21
     * @return array
22
     */
23
    public function translationRules()
24
    {
25
        return [];
26
    }
27
28
    /**
29
     * Return an array of messages for translatable fields
30
     * @return array
31
     */
32
    public function translationMessages()
33
    {
34
        return [];
35
    }
36
37
    /**
38
     * Get the validator instance for the request.
39
     * @return \Illuminate\Validation\Validator
40
     */
41
    protected function getValidatorInstance()
42
    {
43
        $factory = $this->container->make('Illuminate\Validation\Factory');
44
        if (method_exists($this, 'validator')) {
45
            return $this->container->call([$this, 'validator'], compact('factory'));
46
        }
47
48
        $rules = $this->container->call([$this, 'rules']);
49
        $attributes = $this->attributes();
50
        $messages = [];
51
52
        $translationsAttributesKey = $this->getTranslationsAttributesKey();
53
54
        foreach ($this->requiredLocales() as $localeKey => $locale) {
55
            $this->localeKey = $localeKey;
0 ignored issues
show
Documentation Bug introduced by
It seems like $localeKey can also be of type integer. However, the property $localeKey is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
56
            foreach ($this->container->call([$this, 'translationRules']) as $attribute => $rule) {
57
                $key = $localeKey . '.' . $attribute;
58
                $rules[$key] = $rule;
59
                $attributes[$key] = trans($translationsAttributesKey . $attribute);
60
            }
61
62
            foreach ($this->container->call([$this, 'translationMessages']) as $attributeAndRule => $message) {
63
                $messages[$localeKey . '.' . $attributeAndRule] = $message;
64
            }
65
        }
66
67
        return $factory->make(
68
            $this->all(), $rules, array_merge($this->messages(), $messages), $attributes
69
        );
70
    }
71
72
    /**
73
     * @return array
74
     */
75
    public function withTranslations()
76
    {
77
        $results = $this->all();
78
        $translations = [];
79
        foreach ($this->requiredLocales() as $key => $locale) {
80
            $locales[] = $key;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$locales was never initialized. Although not strictly required by PHP, it is generally a good practice to add $locales = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
81
            $translations[$key] = $this->get($key);
82
        }
83
        $results['translations'] = $translations;
84
        array_forget($results, $locales);
0 ignored issues
show
Bug introduced by
The variable $locales does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
85
86
        return $results;
87
    }
88
89
    /**
90
     * @return \Illuminate\Support\Collection
91
     */
92
    public function requiredLocales()
93
    {
94
        return LaravelLocalization::getSupportedLocales();
95
    }
96
97
    /**
98
     * Get the validation for attributes key from the implementing class
99
     * or use a sensible default
100
     * @return string
101
     */
102
    private function getTranslationsAttributesKey()
103
    {
104
        return rtrim($this->translationsAttributesKey, '.') . '.';
105
    }
106
}
107