Proyectos de Subversion LeadersLinked - Services

Rev

Rev 1 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

<?php
declare(strict_types = 1);
namespace LeadersLinked\Handler;

use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Log\LoggerInterface;
use LeadersLinked\Mapper\SessionMapper;
use Laminas\Session\SaveHandler\SaveHandlerInterface;
use SessionHandlerInterface;

class SessionHandler implements SaveHandlerInterface
{

    /**
     *
     * @var SessionMapper
     */
    private $sessionMapper;

    /**
     *
     * @var string
     */
    private $session_name;

    /**
     *
     * @var int
     */
    private $session_lifetime;

    /**
     *
     * @param AdapterInterface $adapter
     * @param LoggerInterface $logger
     * @param int $session_lifetime
     */
    public function __construct(AdapterInterface $adapter, LoggerInterface $logger, int $session_lifetime)
    {
        $this->sessionMapper    = SessionMapper::getInstance($adapter, $logger);
        $this->session_lifetime = $session_lifetime;
    }

    /**
     *
     * {@inheritdoc}
     * @see SessionHandlerInterface::close()
     */
    public function close(): bool
    {
        return true;
    }

    /**
     *
     * {@inheritdoc}
     * @see SessionHandlerInterface::destroy()
     */
    public function destroy(string $id): bool
    {
        $this->sessionMapper->delete($id);
        return true;
    }

    /**
     *
     * {@inheritdoc}
     * @see SessionHandlerInterface::gc()
     */
    public function gc(int $max_lifetime): int
    {
        if ($this->sessionMapper->deleteAllExpired($max_lifetime)) {
            return $this->sessionMapper->getAffectedRows();
        } else {
            return 0;
        }
    }

    /**
     *
     * {@inheritdoc}
     * @see SessionHandlerInterface::open()
     */
    public function open(string $path, string $name): bool
    {
        $this->session_name = $name;
        return true;
    }

    /**
     *
     * {@inheritdoc}
     * @see SessionHandlerInterface::read()
     */
    public function read(string $id): string
    {
        $session = $this->sessionMapper->fetchOne($id);
        if ($session && $session->data) {
            return base64_decode($session->data);
        } else {
            return '';
        }
    }

    /**
     *
     * {@inheritdoc}
     * @see SessionHandlerInterface::write()
     */
    public function write(string $id, string $data): bool
    {
        $data = base64_encode($data);

        $session = $this->read($id);
        if ($session) {
            return $this->sessionMapper->update($id, $data);
        } else {
            return $this->sessionMapper->insert($id, $this->session_name, $data, $this->session_lifetime);
        }
    }
}