<?php

declare(strict_types=1);

/*
 * Copyright (c) 2017-2022 François Kooman <fkooman@tuxed.net>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

namespace fkooman\SeCookie\Tests;

use fkooman\SeCookie\Exception\SessionException;
use fkooman\SeCookie\FileSessionStorage;
use fkooman\SeCookie\SessionStorageInterface;

class TestFileSessionStorage extends FileSessionStorage
{
    private string $tmpDir;

    /**
     * @param array<string,null|array<string,string>> $sessionList
     */
    public function __construct(array $sessionList)
    {
        $this->tmpDir = sprintf('%s/php-secookie-test-%s', sys_get_temp_dir(), bin2hex(random_bytes(32)));
        mkdir($this->tmpDir);
        parent::__construct($this->tmpDir);

        // write the sessionData to the sessionDir
        foreach ($sessionList as $sessionId => $sessionData) {
            $sessionFile = sprintf('%s/%s%s', $this->tmpDir, SessionStorageInterface::ID_PREFIX, $sessionId);
            $fileData = null === $sessionData ? '' : serialize($sessionData);
            file_put_contents($sessionFile, $fileData);
        }
    }

    /**
     * @return array<string,array<string,string>>
     */
    public function getAll(): array
    {
        $sessionList = [];
        foreach (glob(sprintf('%s/%s*', $this->tmpDir, SessionStorageInterface::ID_PREFIX)) as $sessionFile) {
            $sessionId = substr(basename($sessionFile), \strlen(SessionStorageInterface::ID_PREFIX));
            if (false === $sessionDataString = file_get_contents($sessionFile)) {
                throw new SessionException('unable to read session file');
            }

            /** @var mixed */
            $sessionData = '' === $sessionDataString ? null : unserialize($sessionDataString);
            $sessionList[$sessionId] = $sessionData;
        }

        return $sessionList;
    }
}
