Completed
Push — master ( 5b9fc6...a77c60 )
by Igor
02:01
created

TDataInit::initFromPost()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
/**
3
 * @license MIT
4
 * @author Igor Sorokin <[email protected]>
5
 */
6
namespace Dspbee\Bundle\Data;
7
8
/**
9
 * Initialize class properties from array.
10
 *
11
 * Class TDataFilter
12
 * @package Dspbee\Core
13
 */
14
trait TDataInit
15
{
16
    /**
17
     * Init class members.
18
     *
19
     * @param array $data
20
     */
21
    public function initFromArray(array $data)
22
    {
23
        foreach ($data as $name => $value) {
24
            $method = 'set' . ucfirst($name);
25
            if (method_exists($this, $method)) {
26
                call_user_func_array([$this, $method], [$value]);
27
            } else {
28
                if (property_exists(get_called_class(), $name)) {
29
                    $this->$name = $value;
30
                }
31
            }
32
        }
33
    }
34
35
    /**
36
     * Init class members from $_POST array.
37
     *
38
     * @param null $callback
39
     */
40
    public function initFromPost($callback = null)
0 ignored issues
show
Coding Style introduced by
initFromPost uses the super-global variable $_POST 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...
41
    {
42
        $input = $_POST;
43
        if (null !== $callback) {
44
            $input = array_map($callback, $input);
45
        }
46
        $this->initFromArray($input);
47
    }
48
}