summaryrefslogtreecommitdiff
path: root/src/Http/SessionServiceProvider.php
blob: 55e3f48b8fd256c23d3dd958e73adb6a39ea7ead (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php

namespace Engelsystem\Http;

use Engelsystem\Container\ServiceProvider;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
use Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface;

class SessionServiceProvider extends ServiceProvider
{
    public function register()
    {
        $sessionStorage = $this->getSessionStorage();
        $this->app->instance('session.storage', $sessionStorage);
        $this->app->bind(SessionStorageInterface::class, 'session.storage');

        $session = $this->app->make(Session::class);
        $this->app->instance('session', $session);

        /** @var Request $request */
        $request = $this->app->get('request');
        $request->setSession($session);

        $session->start();
    }

    /**
     * Returns the session storage
     *
     * @return SessionStorageInterface
     */
    protected function getSessionStorage()
    {
        if ($this->isCli()) {
            return $this->app->make(MockArraySessionStorage::class);
        }

        return $this->app->make(NativeSessionStorage::class, ['options' => ['cookie_httponly' => true]]);
    }

    /**
     * Test if is called from cli
     *
     * @return bool
     */
    protected function isCli()
    {
        return PHP_SAPI == 'cli';
    }
}