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: 68: 69: 70: 71: 72: 
<?php

declare(strict_types=1);

namespace Wtf\Auth\Storage;

use Wtf\Root;

class Cookie extends Root implements StorageInterface
{
    /**
     * {@inheritdoc}
     */
    public function setUser(Root $user)
    {
        //@codeCoverageIgnoreStart
        if (!\class_exists(\Dflydev\FigCookies\Cookie::class)) {
            throw new \Exception('wtf/auth cookie storage requires dflydev/fig-cookies package installed');
        }
        //@codeCoverageIgnoreEnd

        return \Dflydev\FigCookies\Cookie::create('user_id', $user->getId());
    }

    /**
     * {@inheritdoc}
     */
    public function getUser(): ?Root
    {
        //@codeCoverageIgnoreStart
        if (!\class_exists(\Dflydev\FigCookies\Cookie::class)) {
            throw new \Exception('wtf/auth cookie storage requires dflydev/fig-cookies package installed');
        }
        //@codeCoverageIgnoreEnd

        if ($id = \Dflydev\FigCookies\FigRequestCookies::get($this->request, 'user_id', null)->getValue()) {
            $entity = $this->entity($this->config('auth.entity'));
            if ($entity->has(['id' => $id])) {
                return $entity->load($id);
            }
        }

        return null;
    }

    /**
     * {@inheritdoc}
     */
    public function isLoggedIn(): bool
    {
        //@codeCoverageIgnoreStart
        if (!\class_exists(\Dflydev\FigCookies\Cookie::class)) {
            throw new \Exception('wtf/auth cookie storage requires dflydev/fig-cookies package installed');
        }
        //@codeCoverageIgnoreEnd

        return (bool) $this->getUser();
    }

    /**
     * {@inheritdoc}
     */
    public function logout(): void
    {
        $request = $this->request;
        unset($this->container['request']);
        $this->container['request'] = \Dflydev\FigCookies\FigRequestCookies::modify($request, 'user_id', function (\Dflydev\FigCookies\Cookie $cookie) {
            return $cookie->withValue(null);
        });
    }
}