KarmaService.php 9.96 KB
Newer Older
1
2
3
4
5
<?php

namespace T3o\Karma\Service;

use T3o\Karma\Domain\Model\FrontendUser;
6
use T3o\Karma\Domain\Model\LedgerEntry;
7
8
use T3o\Karma\Domain\Repository\FrontendUserRepository;
use T3o\Karma\Domain\Repository\LedgerEntryRepository;
9
use TYPO3\CMS\Core\Utility\GeneralUtility;
10
use TYPO3\CMS\Extbase\Domain\Model\FrontendUser as ExtbaseFrontendUser;
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

/***************************************************************
 *  Copyright notice
 *
 *  (c) 2018
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/

class KarmaService implements \TYPO3\CMS\Core\SingletonInterface
{
    /**
     * @var LedgerEntryRepository
     */
    protected $ledgerEntryRepository;

    /**
     * @var FrontendUserRepository
     */
    protected $frontendUserRepository;

47
48
49
50
51
52
53
54
55
56
57
58
59
    /**
     * @var array
     */
    protected $settings;

    /**
     * UserProfileChangeKarmaIssuerUtility constructor.
     */
    public function __construct()
    {
        $objectManager = GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Object\ObjectManager::class);
        /** @var \TYPO3\CMS\Extbase\Configuration\ConfigurationManager $configurationManager */
        $configurationManager = $objectManager->get(\TYPO3\CMS\Extbase\Configuration\ConfigurationManager::class);
60
+        $this->settings = $configurationManager->getConfiguration(
61
62
63
64
65
            \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_SETTINGS,
            'karma'
        );
    }

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
    /**
     * @param LedgerEntryRepository $ledgerEntryRepository
     */
    public function injectLedgerEntryRepository(LedgerEntryRepository $ledgerEntryRepository)
    {
        $this->ledgerEntryRepository = $ledgerEntryRepository;
    }

    /**
     * @param FrontendUserRepository $frontendUserRepository
     */
    public function injectFrontendUserRepository(FrontendUserRepository $frontendUserRepository)
    {
        $this->frontendUserRepository = $frontendUserRepository;
    }

    /**
     * Get the imimmutable karma total from the user
     *
85
     * @param ExtbaseFrontendUser $frontendUser
86
87
88
89
     * @param bool $ignoreCache Fetch value directly from ledger
     * @param bool $updateCacheEntry Update the user's cache entry if we're ignoring cache. Will also update immutable cache.
     * @return int Immutable Karma Total
     */
90
    public function getImmutableKarmaForUser(ExtbaseFrontendUser $frontendUser, $ignoreCache = false, $updateCacheEntry = true)
91
92
93
94
    {
        $frontendUser = $this->ensureCorrectFrontendUserSubclass($frontendUser);

        if (!$ignoreCache) {
95
            return $frontendUser->getKarmaImmutableValueCache();
96
97
98
99
        }

        $immutableKarma = $this->ledgerEntryRepository->calculateImmutableKarmaTotalForUser($frontendUser);

mabolek's avatar
mabolek committed
100
        if ($updateCacheEntry) {
101
            $mutableKarma = $this->getMutableKarmaForUser($frontendUser, true, false);
102

103
            $frontendUser->setKarmaImmutableValueCache($immutableKarma);
104
            $frontendUser->setKarmaMutableValueCache($mutableKarma);
105
            $frontendUser->setKarmaCacheTimestamp(time());
106
            $frontendUser->setKarmaSourceTotalCacheDecoded([]);
107
108
109
110
111
112
113
114
115
116

            $this->frontendUserRepository->update($frontendUser);
        }

        return $immutableKarma;
    }

    /**
     * Get the mutable karma total from the user
     *
117
     * @param ExtbaseFrontendUser $frontendUser
118
119
120
121
     * @param bool $ignoreCache Fetch value directly from ledger
     * @param bool $updateCacheEntry Update the user's cache entry if we're ignoring cache. Will also update mutable cache.
     * @return int Mutable Karma Total
     */
122
    public function getMutableKarmaForUser(ExtbaseFrontendUser $frontendUser, $ignoreCache = false, $updateCacheEntry = true)
123
124
125
126
    {
        $frontendUser = $this->ensureCorrectFrontendUserSubclass($frontendUser);

        if (!$ignoreCache) {
127
            return $frontendUser->getKarmaMutableValueCache();
128
129
130
131
        }

        $mutableKarma = $this->ledgerEntryRepository->calculateMutableKarmaTotalForUser($frontendUser);

mabolek's avatar
mabolek committed
132
        if ($updateCacheEntry) {
133
            $immutableKarma = $this->getImmutableKarmaForUser($frontendUser, true, false);
134

135
            $frontendUser->setKarmaMutableValueCache($mutableKarma);
136
            $frontendUser->setKarmaImmutableValueCache($immutableKarma);
137
            $frontendUser->setKarmaCacheTimestamp(time());
138
            $frontendUser->setKarmaSourceTotalCacheDecoded([]);
139
140
141
142
143
144
145

            $this->frontendUserRepository->update($frontendUser);
        }

        return $mutableKarma;
    }

146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
    /**
     * Get the immutable karma total for a specific karma source code from the user
     *
     * @param string $karmaSourceCode The source code to fetch the total for
     * @param ExtbaseFrontendUser $frontendUser
     * @param bool $ignoreCache Fetch value directly from ledger
     * @param bool $updateCacheEntry Update the user's cache entry if we're ignoring cache. Will also update mutable cache.
     * @return int Mutable Karma Total
     */
    public function getImmutableKarmaSourceTotalForUser($karmaSourceCode, ExtbaseFrontendUser $frontendUser, $ignoreCache = false, $updateCacheEntry = true)
    {
        $frontendUser = $this->ensureCorrectFrontendUserSubclass($frontendUser);

        $totals = $frontendUser->getKarmaSourceTotalCacheDecoded();
        if (!$ignoreCache) {
            if (isset($totals[$karmaSourceCode])) {
                return $totals[$karmaSourceCode];
            }
        }

        $sourceTotal = $this->ledgerEntryRepository->calculateImmutableKarmaSourceTotalForUser($karmaSourceCode, $frontendUser);

        if ($updateCacheEntry) {
            $totals[$karmaSourceCode] = $sourceTotal;
            $frontendUser->setKarmaSourceTotalCacheDecoded($totals);

            $this->frontendUserRepository->update($frontendUser);
        }

        return $sourceTotal;
    }

178
179
180
181
182
    /**
     * Add karma to a user
     *
     * @param int $karmaValue to add to the user
     * @param ExtbaseFrontendUser $frontendUser to add the value to
183
     * @param string $karmaSource for the karma value
184
185
     * @param string $karmaIssuer code
     * @param string $karmaIssuerAction code
186
     */
187
    public function addKarmaToUser(int $karmaValue, ExtbaseFrontendUser $frontendUser, string $karmaSource, string $karmaIssuer, string $karmaIssuerAction)
188
189
190
191
192
193
194
195
196
    {
        $frontendUser = $this->ensureCorrectFrontendUserSubclass($frontendUser);

        $ledgerEntry = new LedgerEntry();

        $ledgerEntry->setImmutableValue($karmaValue);
        $ledgerEntry->setMutableValue($karmaValue);
        $ledgerEntry->setUser($frontendUser);
        $ledgerEntry->setKarmaSource($karmaSource);
197
198
        $ledgerEntry->setIssuer($karmaIssuer);
        $ledgerEntry->setIssuerAction($karmaIssuerAction);
199
200
201
202
203
204
205
206
207

        $this->ledgerEntryRepository->add($ledgerEntry);

        $frontendUser->setKarmaImmutableValueCache($frontendUser->getKarmaImmutableValueCache() + $karmaValue);
        $frontendUser->setKarmaMutableValueCache($frontendUser->getKarmaMutableValueCache() + $karmaValue);
        $frontendUser->setKarmaCacheTimestamp(time());
        $this->frontendUserRepository->update($frontendUser);
    }

208
209
210
    /**
     * Trigger a karma-earning action for a user
     *
211
212
     * @param string $issuerCode The issuer code for the karma
     * @param string $issuerActionCode The issuer action code for the karma
213
214
215
216
217
     * @param ExtbaseFrontendUser $frontendUser The frontend user earning the karma
     * @throws \Exception If the $issuerCode, $issuerActionCode, or karma source code is not defined in TypoScript.
     */
    public function triggerKarmaIssuerActionForUser($issuerCode, $issuerActionCode, ExtbaseFrontendUser $frontendUser)
    {
mabolek's avatar
mabolek committed
218
        if (!array_key_exists($issuerCode, $this->settings['issuers'])) {
219
220
221
            throw new \Exception('Issuer code "' . $issuerCode . '" does not exist.', 1549968187);
        }

mabolek's avatar
mabolek committed
222
        if (!array_key_exists($issuerActionCode, $this->settings['issuers'][$issuerCode])) {
223
224
225
226
227
228
229
230
231
232
            throw new \Exception('Issuer action code "' . $issuerActionCode . '" does not exist.', 1549968249);
        }

        $issuerActionSettings = $this->settings['issuers'][$issuerCode][$issuerActionCode];
        $karmaSourceCode = $issuerActionSettings['sourceCode'];

        if ($karmaSourceCode === '') {
            throw new \Exception('Empty karma source code supplied. Please configure it in TypoScript.', 1541508560);
        }

mabolek's avatar
mabolek committed
233
        if (!array_key_exists($karmaSourceCode, $this->settings['sourceCodes'])) {
234
235
236
237
238
239
240
241
242
243
244
245
            throw new \Exception('Karma source code "' . $karmaSourceCode . '" does not exist.', 1549968362);
        }

        $this->addKarmaToUser(
            $issuerActionSettings['valueEarned'],
            $frontendUser,
            $karmaSourceCode,
            $issuerCode,
            $issuerActionCode
        );
    }

246
247
248
    /**
     * Will take any FrontendUser object and return a karma extension FrontendUser subclass with the data we need
     *
249
     * @param ExtbaseFrontendUser $frontendUser
250
251
252
     * @return FrontendUser
     * @internal
     */
253
    public function ensureCorrectFrontendUserSubclass(ExtbaseFrontendUser $frontendUser)
mabolek's avatar
mabolek committed
254
    {
255
256
257
258
259
260
261
262
        //If user is not an instance of our own frontend user class we have to fetch it again
        if (!($frontendUser instanceof FrontendUser)) {
            $frontendUser = $this->frontendUserRepository->findByUid($frontendUser->getUid());
        }

        return $frontendUser;
    }
}