Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
66.67% covered (warning)
66.67%
10 / 15
25.00% covered (danger)
25.00%
1 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
SubmittedTextCache
66.67% covered (warning)
66.67%
10 / 15
25.00% covered (danger)
25.00%
1 / 4
7.33
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 stashText
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 fetchText
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 makeCacheKey
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2
3namespace TwoColConflict\ProvideSubmittedText;
4
5use BagOStuff;
6use MediaWiki\Session\SessionId;
7use MediaWiki\User\UserIdentity;
8use UnexpectedValueException;
9use Wikimedia\LightweightObjectStore\ExpirationAwareness;
10
11/**
12 * @license GPL-2.0-or-later
13 * @author Christoph Jauera <christoph.jauera@wikimedia.de>
14 */
15class SubmittedTextCache {
16
17    private const CACHE_KEY = 'twoColConflict_yourText';
18
19    private BagOStuff $cache;
20
21    public function __construct( BagOStuff $cache ) {
22        $this->cache = $cache;
23    }
24
25    /**
26     * @param string $titleDbKey
27     * @param UserIdentity $user
28     * @param SessionId|null $sessionId
29     * @param string $text
30     *
31     * @return bool If caching was successful or not.
32     */
33    public function stashText( string $titleDbKey, UserIdentity $user, ?SessionId $sessionId, string $text ): bool {
34        $key = $this->makeCacheKey( $titleDbKey, $user, $sessionId );
35        return $this->cache->set( $key, $text, ExpirationAwareness::TTL_DAY );
36    }
37
38    /**
39     * @param string $titleDbKey
40     * @param UserIdentity $user
41     * @param SessionId|null $sessionId
42     *
43     * @return string|false Returns false when the cache expired
44     */
45    public function fetchText( string $titleDbKey, UserIdentity $user, ?SessionId $sessionId ) {
46        $key = $this->makeCacheKey( $titleDbKey, $user, $sessionId );
47        return $this->cache->get( $key );
48    }
49
50    private function makeCacheKey( string $titleDbKey, UserIdentity $user, ?SessionId $sessionId ): string {
51        $components = [
52            self::CACHE_KEY,
53            $titleDbKey,
54            $user->getId(),
55        ];
56        // The user ID is specific enough for registered users
57        if ( !$user->isRegistered() ) {
58            if ( !$sessionId ) {
59                throw new UnexpectedValueException( 'Must provide a session for anonymous users' );
60            }
61            // Warning, the session ID should not use the same spot as the user ID
62            $components[] = $sessionId->getId();
63        }
64        return $this->cache->makeKey( ...$components );
65    }
66
67}