Skip to content

Commit bd579d4

Browse files
committed
FileAdapter
1 parent 227e606 commit bd579d4

File tree

2 files changed

+82
-1
lines changed

2 files changed

+82
-1
lines changed

src/Adapters/FileAdapter.php

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
<?php
2+
/**
3+
* FileAdapter.php
4+
*
5+
* This file is part of InitPHP Sessions.
6+
*
7+
* @author Muhammet ŞAFAK <info@muhammetsafak.com.tr>
8+
* @copyright Copyright © 2022 Muhammet ŞAFAK
9+
* @license ./LICENSE MIT
10+
* @version 2.0
11+
* @link https://www.muhammetsafak.com.tr
12+
*/
13+
14+
namespace InitPHP\Sessions\Adapters;
15+
16+
use InitPHP\Sessions\AbstractAdapter;
17+
use InitPHP\Sessions\Interfaces\AdapterInterface;
18+
19+
class FileAdapter extends AbstractAdapter implements AdapterInterface
20+
{
21+
22+
private $path;
23+
24+
private string $prefix = 'sess_';
25+
26+
public function __construct(array $options)
27+
{
28+
$path = $options['path'];
29+
if (!is_dir($path) || !is_writable($path)) {
30+
throw new \InvalidArgumentException("Belirtilen dizin geçerli ve yazılabilir olmalıdır.");
31+
}
32+
$this->path = $path;
33+
isset($options['prefix']) && $this->prefix = $options['prefix'];
34+
}
35+
36+
37+
public function read($id)
38+
{
39+
$id = $this->prefix . $id;
40+
41+
return (string) @file_get_contents("{$this->path}/$id");
42+
}
43+
44+
public function write($id, $data)
45+
{
46+
$id = $this->prefix . $id;
47+
48+
return file_put_contents("{$this->path}/$id", $data) !== false;
49+
}
50+
51+
public function destroy($id)
52+
{
53+
$id = $this->prefix . $id;
54+
55+
$session = "{$this->path}/$id";
56+
if (file_exists($session)) {
57+
unlink($session);
58+
}
59+
60+
return true;
61+
}
62+
63+
public function gc($max_lifetime)
64+
{
65+
$files = glob("{$this->path}/{$this->prefix}*");
66+
$currentTime = time();
67+
68+
foreach ($files as $file) {
69+
if (filemtime($file) + $max_lifetime < $currentTime && file_exists($file)) {
70+
unlink($file);
71+
}
72+
}
73+
74+
return true;
75+
}
76+
77+
}

src/Adapters/PDOAdapter.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,11 @@ class PDOAdapter extends AbstractAdapter implements AdapterInterface
3939

4040
public function __construct(array $options)
4141
{
42-
$this->pdo = $options['pdo'];
42+
if (isset($options['pdo'])) {
43+
$this->pdo = $options['pdo'];
44+
} else {
45+
$this->pdo = new \PDO($options['dsn'], $options['username'], $options['password']);
46+
}
4347
$this->table = $options['table'];
4448
$this->withIPAddress = $options['withIPAddress'] ?? false;
4549
}

0 commit comments

Comments
 (0)