Passed
Push — master ( aae7cc...acea2e )
by Anton
29s
created

JsonApiParser::parseMemberNames()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/**
3
 * @author Anton Tuyakhov <[email protected]>
4
 */
5
6
namespace tuyakhov\jsonapi;
7
8
use yii\helpers\ArrayHelper;
9
use \yii\web\JsonParser;
10
11
class JsonApiParser extends JsonParser
12
{
13
    /**
14
     * Converts 'type' member to form name
15
     * If not set, type will be converted to singular form.
16
     * For example, 'articles' will be converted to 'Article'
17
     * @var callable
18
     */
19
    public $formNameCallback = ['tuyakhov\jsonapi\Inflector', 'type2form'];
20
21
    /**
22
     * Converts member names to variable names
23
     * If not set, all special characters will be replaced by underscore
24
     * For example, 'first-name' will be converted to 'first_name'
25
     * @var callable
26
     */
27
    public $memberNameCallback = ['tuyakhov\jsonapi\Inflector', 'member2var'];
28
29
    /**
30
     * Parse resource object into the input data to populates the model
31
     * @inheritdoc
32
     */
33
    public function parse($rawBody, $contentType)
34
    {
35
        $array = parent::parse($rawBody, $contentType);
36
        if ($type = ArrayHelper::getValue($array, 'data.type')) {
37
            $formName = $this->typeToFormName($type);
38
            if ($attributes = ArrayHelper::getValue($array, 'data.attributes')) {
39
                $result[$formName] = array_combine($this->parseMemberNames(array_keys($attributes)), array_values($attributes));
0 ignored issues
show
Coding Style Comprehensibility introduced by
$result was never initialized. Although not strictly required by PHP, it is generally a good practice to add $result = 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...
40
            } elseif ($id = ArrayHelper::getValue($array, 'data.id')) {
41
                $result[$formName] = ['id' => $id, 'type' => $type];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$result was never initialized. Although not strictly required by PHP, it is generally a good practice to add $result = 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...
42
            }
43
            if ($relationships = ArrayHelper::getValue($array, 'data.relationships')) {
44
                foreach ($relationships as $name => $relationship) {
45
                    if (isset($relationship[0])) {
46 View Code Duplication
                        foreach ($relationship as $item) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
47
                            if (isset($item['type']) && isset($item['id'])) {
48
                                $formName = $this->typeToFormName($item['type']);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 19 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
49
                                $result[$name][$formName][] = $item;
0 ignored issues
show
Bug introduced by
The variable $result 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...
50
                            }
51
                        }
52
                    } elseif (isset($relationship['type']) && isset($relationship['id'])) {
53
                        $formName = $this->typeToFormName($relationship['type']);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 17 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
54
                        $result[$name][$formName] = $relationship;
55
                    }
56
                }
57
            }
58
        } else {
59
            $data = ArrayHelper::getValue($array, 'data', []);
60 View Code Duplication
            foreach ($data as $relationLink) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
61
                if (isset($relationLink['type']) && isset($relationLink['id'])) {
62
                    $formName = $this->typeToFormName($relationLink['type']);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 12 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
63
                    $result[$formName][] = $relationLink;
64
                }
65
            }
66
        }
67
        return isset($result) ? $result : $array;
68
    }
69
70
    /**
71
     * @param $type 'type' member of the document
72
     * @return string form name
73
     */
74
    protected function typeToFormName($type)
75
    {
76
        return call_user_func($this->formNameCallback, $type);
77
    }
78
79
    /**
80
     * @param array $memberNames
81
     * @return array variable names
82
     */
83
    protected function parseMemberNames(array $memberNames = [])
84
    {
85
        return array_map($this->memberNameCallback, $memberNames);
86
    }
87
}
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
88