aboutsummaryrefslogtreecommitdiffhomepage
path: root/application/render/PageCacheManager.php
blob: fe74bf271bb08448f3f4a605f701fb3b8af0ec24 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php

namespace Shaarli\Render;

use DatePeriod;
use Shaarli\Feed\CachedPage;

/**
 * Cache utilities
 */
class PageCacheManager
{
    /** @var string Cache directory */
    protected $pageCacheDir;

    /** @var bool */
    protected $isLoggedIn;

    public function __construct(string $pageCacheDir, bool $isLoggedIn)
    {
        $this->pageCacheDir = $pageCacheDir;
        $this->isLoggedIn = $isLoggedIn;
    }

    /**
     * Purges all cached pages
     *
     * @return string|null an error string if the directory is missing
     */
    public function purgeCachedPages(): ?string
    {
        if (!is_dir($this->pageCacheDir)) {
            $error = sprintf(t('Cannot purge %s: no directory'), $this->pageCacheDir);
            error_log($error);

            return $error;
        }

        array_map('unlink', glob($this->pageCacheDir . '/*.cache'));

        return null;
    }

    /**
     * Invalidates caches when the database is changed or the user logs out.
     */
    public function invalidateCaches(): void
    {
        // Purge page cache shared by sessions.
        $this->purgeCachedPages();
    }

    /**
     * Get CachedPage instance for provided URL.
     *
     * @param string      $pageUrl
     * @param ?DatePeriod $validityPeriod Optionally specify a time limit on requested cache
     *
     * @return CachedPage
     */
    public function getCachePage(string $pageUrl, DatePeriod $validityPeriod = null): CachedPage
    {
        return new CachedPage(
            $this->pageCacheDir,
            $pageUrl,
            false === $this->isLoggedIn,
            $validityPeriod
        );
    }
}