Skip to content

Commit

Permalink
FileAdapter
Browse files Browse the repository at this point in the history
  • Loading branch information
muhammetsafak committed Dec 15, 2023
1 parent 227e606 commit bd579d4
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 1 deletion.
77 changes: 77 additions & 0 deletions src/Adapters/FileAdapter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php
/**
* FileAdapter.php
*
* This file is part of InitPHP Sessions.
*
* @author Muhammet ŞAFAK <[email protected]>
* @copyright Copyright © 2022 Muhammet ŞAFAK
* @license ./LICENSE MIT
* @version 2.0
* @link https://www.muhammetsafak.com.tr
*/

namespace InitPHP\Sessions\Adapters;

use InitPHP\Sessions\AbstractAdapter;
use InitPHP\Sessions\Interfaces\AdapterInterface;

class FileAdapter extends AbstractAdapter implements AdapterInterface
{

private $path;

private string $prefix = 'sess_';

public function __construct(array $options)
{
$path = $options['path'];
if (!is_dir($path) || !is_writable($path)) {
throw new \InvalidArgumentException("Belirtilen dizin geçerli ve yazılabilir olmalıdır.");
}
$this->path = $path;
isset($options['prefix']) && $this->prefix = $options['prefix'];
}


public function read($id)
{
$id = $this->prefix . $id;

return (string) @file_get_contents("{$this->path}/$id");
}

public function write($id, $data)
{
$id = $this->prefix . $id;

return file_put_contents("{$this->path}/$id", $data) !== false;
}

public function destroy($id)
{
$id = $this->prefix . $id;

$session = "{$this->path}/$id";
if (file_exists($session)) {
unlink($session);
}

return true;
}

public function gc($max_lifetime)
{
$files = glob("{$this->path}/{$this->prefix}*");
$currentTime = time();

foreach ($files as $file) {
if (filemtime($file) + $max_lifetime < $currentTime && file_exists($file)) {
unlink($file);
}
}

return true;
}

}
6 changes: 5 additions & 1 deletion src/Adapters/PDOAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,11 @@ class PDOAdapter extends AbstractAdapter implements AdapterInterface

public function __construct(array $options)
{
$this->pdo = $options['pdo'];
if (isset($options['pdo'])) {
$this->pdo = $options['pdo'];
} else {
$this->pdo = new \PDO($options['dsn'], $options['username'], $options['password']);
}
$this->table = $options['table'];
$this->withIPAddress = $options['withIPAddress'] ?? false;
}
Expand Down

0 comments on commit bd579d4

Please sign in to comment.