Completed
Pull Request — master (#2)
by Beñat
02:58
created

YamlStorage::properties()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 4
rs 10
cc 2
eloc 2
nc 2
nop 0
1
<?php
2
3
/*
4
 * This file is part of the WPSymfonyForm plugin.
5
 *
6
 * Copyright (c) 2015-2016 LIN3S <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace LIN3S\WPSymfonyForm\Admin\Storage;
13
14
use Symfony\Component\Yaml\Yaml;
15
16
/**
17
 * YAML strategy of storage.
18
 *
19
 * @author Beñat Espiña <[email protected]>
20
 */
21
class YamlStorage implements Storage
22
{
23
    /**
24
     * The data collection.
25
     *
26
     * @var array
27
     */
28
    private $data;
29
30
    /**
31
     * Constructor.
32
     *
33
     * @param string|null $formType The form type
34
     * @param string|null $yamlFile The dir path of YAML file
35
     */
36
    public function __construct($formType = null, $yamlFile = null)
37
    {
38
        if (null === $yamlFile) {
39
            $yamlFile = __DIR__ . '/../../../../../../../../wp_symfony_form_email_log.yml';
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $yamlFile. This often makes code more readable.
Loading history...
40
        }
41
        $data = Yaml::parse(file_get_contents($yamlFile));
42
        if (null === $formType) {
43
            $this->data = $data;
0 ignored issues
show
Documentation Bug introduced by
It seems like $data can also be of type string or object<stdClass>. However, the property $data is declared as type array. 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...
44
        } else {
45
            foreach ($data as $item) {
0 ignored issues
show
Bug introduced by
The expression $data of type array|string|object<stdClass> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
46
                if ($item['formType'] === $formType) {
47
                    $this->data[] = $item;
48
                }
49
            }
50
        }
51
52
        if (null === $this->data) {
53
            $this->data = [];
54
        }
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60 View Code Duplication
    public function findAll($limit, $offset)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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
    {
62
        $data = $this->data;
63
        foreach ($data as $key => $item) {
64
            if (array_key_exists('ID', $item)) {
65
                continue;
66
            }
67
            $data[$key]['ID'] = $key;
68
        }
69
        usort($data, [$this, 'sort']);
70
71
        return $this->paginate($data, $limit, $offset);
72
    }
73
74
    /**
75
     * {@inheritdoc}
76
     */
77 View Code Duplication
    public function query(array $criteria, $limit, $offset)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
78
    {
79
        $data = [];
80
        foreach ($this->data as $key => $item) {
81
            foreach ($criteria as $name => $singleCriteria) {
82
                if ($item[$name] === $singleCriteria) {
83
                    $data[$key] = $item;
84
                }
85
            }
86
            if (array_key_exists('ID', $item)) {
87
                continue;
88
            }
89
            $data[$key]['ID'] = $key;
90
        }
91
        usort($data, [$this, 'sort']);
92
93
        return $this->paginate($data, $limit, $offset);
94
    }
95
96
    /**
97
     * {@inheritdoc}
98
     */
99
    public function properties()
100
    {
101
        return isset($this->data[0]) ? array_keys($this->data[0]) : null;
102
    }
103
104
    /**
105
     * {@inheritdoc}
106
     */
107
    public function size()
108
    {
109
        return count($this->data);
110
    }
111
112
    /**
113
     * Paginates the given collection of data.
114
     *
115
     * @param array $data   The collection data
116
     * @param int   $limit  Logs per page
117
     * @param int   $offset The number of the page
118
     *
119
     * @return array
120
     */
121
    private function paginate($data, $limit, $offset)
122
    {
123
        return array_slice($data, (($offset - 1) * $limit), $limit);
124
    }
125
126
    /**
127
     * Compares the given two items.
128
     *
129
     * @param mixed $item1 The first item
130
     * @param mixed $item2 The second item
131
     *
132
     * @return int
133
     */
134 View Code Duplication
    private function sort($item1, $item2)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
Coding Style introduced by
sort uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
135
    {
136
        $orderBy = 'name';
137
        $order = 'asc';
138
139
        if (!empty($_GET['orderby'])) {
140
            $orderBy = $_GET['orderby'];
141
        }
142
        if (!empty($_GET['order'])) {
143
            $order = $_GET['order'];
144
        }
145
        $result = strcmp($item1[$orderBy], $item2[$orderBy]);
146
        if ('asc' === $order) {
147
            return $result;
148
        }
149
150
        return -$result;
151
    }
152
}
153