Failed Conditions
Push — master ( c04808...f5c6c8 )
by Arnold
04:54
created

Session::getRequest()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
ccs 0
cts 0
cp 0
c 0
b 0
f 0
nc 1
1
<?php
2
3
namespace Jasny\Controller;
4
5
use Jasny\Controller\Session\Flash;
6
7
/**
8
 * Use session in the controller
9
 */
10
trait Session
11
{
12
    /**
13
     * Session
14
     * @var array|\ArrayObject
15
     */
16
    protected $session;
17
18
    /**
19
     * Flash message
20
     * @var Flash
21
     */
22
    protected $flash;
23
    
24
    
25
    /**
26
     * Get request, set for controller
27
     *
28
     * @return ServerRequestInterface
29
     */
30
    abstract public function getRequest();
31
    
32
    
33
    /**
34
     * Link the session to the session property in the controller
35
     */
36 2
    public function useSession()
1 ignored issue
show
Coding Style introduced by
useSession uses the super-global variable $_SESSION 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...
37
    {
38 2
        $this->session = $this->getRequest()->getAttribute('session');
39
        
40 2
        if (!isset($this->session)) {
41 1
            $this->session =& $_SESSION;
42 1
        }
43 2
    }
44
    
45
    
46
    /**
47
     * Get an/or set the flash message.
48
     * 
49
     * @param mixed $type     flash type, eg. 'error', 'notice' or 'success'
50
     * @param mixed $message  flash message
51
     * @return Flash
52
     */
53 2
    public function flash($type = null, $message = null)
54
    {
55 2
        if (!isset($this->flash)) {
56 1
            $this->flash = new Flash($this->session);
57 1
        }
58
        
59 2
        if ($type) {
60 1
            $this->flash->set($type, $message);
61 1
        }
62
        
63 2
        return $this->flash;
64
    }
65
}
66