Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
/*
4
 * This file is part of the Symfony package.
5
 *
6
 * (c) Fabien Potencier <fabien@symfony.com>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
 
12
namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
13
 
14
use MongoDB\BSON\Binary;
15
use MongoDB\BSON\UTCDateTime;
16
use MongoDB\Client;
17
use MongoDB\Collection;
18
 
19
/**
20
 * Session handler using the mongodb/mongodb package and MongoDB driver extension.
21
 *
22
 * @author Markus Bachmann <markus.bachmann@bachi.biz>
23
 *
24
 * @see https://packagist.org/packages/mongodb/mongodb
25
 * @see https://php.net/mongodb
26
 */
27
class MongoDbSessionHandler extends AbstractSessionHandler
28
{
29
    private Client $mongo;
30
    private Collection $collection;
31
    private array $options;
32
    private int|\Closure|null $ttl;
33
 
34
    /**
35
     * Constructor.
36
     *
37
     * List of available options:
38
     *  * database: The name of the database [required]
39
     *  * collection: The name of the collection [required]
40
     *  * id_field: The field name for storing the session id [default: _id]
41
     *  * data_field: The field name for storing the session data [default: data]
42
     *  * time_field: The field name for storing the timestamp [default: time]
43
     *  * expiry_field: The field name for storing the expiry-timestamp [default: expires_at]
44
     *  * ttl: The time to live in seconds.
45
     *
46
     * It is strongly recommended to put an index on the `expiry_field` for
47
     * garbage-collection. Alternatively it's possible to automatically expire
48
     * the sessions in the database as described below:
49
     *
50
     * A TTL collections can be used on MongoDB 2.2+ to cleanup expired sessions
51
     * automatically. Such an index can for example look like this:
52
     *
53
     *     db.<session-collection>.createIndex(
54
     *         { "<expiry-field>": 1 },
55
     *         { "expireAfterSeconds": 0 }
56
     *     )
57
     *
58
     * More details on: https://docs.mongodb.org/manual/tutorial/expire-data/
59
     *
60
     * If you use such an index, you can drop `gc_probability` to 0 since
61
     * no garbage-collection is required.
62
     *
63
     * @throws \InvalidArgumentException When "database" or "collection" not provided
64
     */
65
    public function __construct(Client $mongo, array $options)
66
    {
67
        if (!isset($options['database']) || !isset($options['collection'])) {
68
            throw new \InvalidArgumentException('You must provide the "database" and "collection" option for MongoDBSessionHandler.');
69
        }
70
 
71
        $this->mongo = $mongo;
72
 
73
        $this->options = array_merge([
74
            'id_field' => '_id',
75
            'data_field' => 'data',
76
            'time_field' => 'time',
77
            'expiry_field' => 'expires_at',
78
        ], $options);
79
        $this->ttl = $this->options['ttl'] ?? null;
80
    }
81
 
82
    public function close(): bool
83
    {
84
        return true;
85
    }
86
 
87
    protected function doDestroy(string $sessionId): bool
88
    {
89
        $this->getCollection()->deleteOne([
90
            $this->options['id_field'] => $sessionId,
91
        ]);
92
 
93
        return true;
94
    }
95
 
96
    public function gc(int $maxlifetime): int|false
97
    {
98
        return $this->getCollection()->deleteMany([
99
            $this->options['expiry_field'] => ['$lt' => new UTCDateTime()],
100
        ])->getDeletedCount();
101
    }
102
 
103
    protected function doWrite(string $sessionId, string $data): bool
104
    {
105
        $ttl = ($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime');
106
        $expiry = new UTCDateTime((time() + (int) $ttl) * 1000);
107
 
108
        $fields = [
109
            $this->options['time_field'] => new UTCDateTime(),
110
            $this->options['expiry_field'] => $expiry,
111
            $this->options['data_field'] => new Binary($data, Binary::TYPE_OLD_BINARY),
112
        ];
113
 
114
        $this->getCollection()->updateOne(
115
            [$this->options['id_field'] => $sessionId],
116
            ['$set' => $fields],
117
            ['upsert' => true]
118
        );
119
 
120
        return true;
121
    }
122
 
123
    public function updateTimestamp(string $sessionId, string $data): bool
124
    {
125
        $ttl = ($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime');
126
        $expiry = new UTCDateTime((time() + (int) $ttl) * 1000);
127
 
128
        $this->getCollection()->updateOne(
129
            [$this->options['id_field'] => $sessionId],
130
            ['$set' => [
131
                $this->options['time_field'] => new UTCDateTime(),
132
                $this->options['expiry_field'] => $expiry,
133
            ]]
134
        );
135
 
136
        return true;
137
    }
138
 
139
    protected function doRead(string $sessionId): string
140
    {
141
        $dbData = $this->getCollection()->findOne([
142
            $this->options['id_field'] => $sessionId,
143
            $this->options['expiry_field'] => ['$gte' => new UTCDateTime()],
144
        ]);
145
 
146
        if (null === $dbData) {
147
            return '';
148
        }
149
 
150
        return $dbData[$this->options['data_field']]->getData();
151
    }
152
 
153
    private function getCollection(): Collection
154
    {
155
        return $this->collection ??= $this->mongo->selectCollection($this->options['database'], $this->options['collection']);
156
    }
157
 
158
    protected function getMongo(): Client
159
    {
160
        return $this->mongo;
161
    }
162
}