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: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 
<?php

declare(strict_types=1);

namespace Wtf\Auth\Storage;

use Wtf\Root;

class Session extends Root implements StorageInterface
{
    /**
     * {@inheritdoc}
     */
    public function setUser(Root $user)
    {
        if (PHP_SESSION_ACTIVE !== \session_status()) {
            throw new \Exception('Session not started');
        }

        $_SESSION['user'] = $user->getData();
        if (isset($_SESSION['user']['password'])) {
            unset($_SESSION['user']['password']);
        }

        return $user;
    }

    /**
     * {@inheritdoc}
     */
    public function getUser(): ?Root
    {
        if (PHP_SESSION_ACTIVE !== \session_status()) {
            return null;
        }

        if ($_SESSION['user'] ?? null) {
            return $this->entity($this->config('auth.entity'))->setData($_SESSION['user']);
        }

        return null;
    }

    /**
     * {@inheritdoc}
     */
    public function isLoggedIn(): bool
    {
        if (PHP_SESSION_ACTIVE !== \session_status()) {
            return false;
        }

        return (bool) ($_SESSION['user'] ?? null);
    }

    /**
     * {@inheritdoc}
     */
    public function logout(): void
    {
        $_SESSION = [];
        if (PHP_SESSION_ACTIVE === \session_status()) {
            \session_destroy();
        }
    }
}