Charsets.php
3 years ago
Hosts.php
2 months ago
Pages.php
9 months ago
SettingsChangeHandler.php
2 weeks ago
SettingsController.php
4 days ago
SettingsRepository.php
1 year ago
TrackingConfig.php
5 months ago
UserFlagsController.php
1 year ago
UserFlagsRepository.php
3 years ago
index.php
3 years ago
SettingsRepository.php
55 lines
| 1 | <?php // phpcs:ignore SlevomatCodingStandard.TypeHints.DeclareStrictTypes.DeclareStrictTypesMissing |
| 2 | |
| 3 | namespace MailPoet\Settings; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use MailPoet\Doctrine\Repository; |
| 9 | use MailPoet\Entities\SettingEntity; |
| 10 | use MailPoetVendor\Carbon\Carbon; |
| 11 | use MailPoetVendor\Doctrine\ORM\Query; |
| 12 | |
| 13 | /** |
| 14 | * @extends Repository<SettingEntity> |
| 15 | */ |
| 16 | class SettingsRepository extends Repository { |
| 17 | public function findOneByName(string $name): ?SettingEntity { |
| 18 | // Always fetch fresh entity data (= don't use "findOneBy()"). See also further below. |
| 19 | $result = (array)$this->doctrineRepository->createQueryBuilder('s') |
| 20 | ->where('s.name = :name') |
| 21 | ->setParameter('name', $name) |
| 22 | ->getQuery() |
| 23 | ->setHint(Query::HINT_REFRESH, true) |
| 24 | ->getResult(); |
| 25 | |
| 26 | return isset($result[0]) && $result[0] instanceof SettingEntity ? $result[0] : null; |
| 27 | } |
| 28 | |
| 29 | public function createOrUpdateByName($name, $value) { |
| 30 | // Temporarily use low-level INSERT ... ON DUPLICATE KEY UPDATE query to avoid race conditions |
| 31 | // between entity fetch and creation with multiple concurrent requests. This will be replaced |
| 32 | // by a code solving atomicity of create-or-update on entity (ORM) level in a follow-up ticket. |
| 33 | $now = Carbon::now()->millisecond(0); |
| 34 | $tableName = $this->entityManager->getClassMetadata(SettingEntity::class)->getTableName(); |
| 35 | $this->entityManager->getConnection()->executeStatement(" |
| 36 | INSERT INTO $tableName (name, value, created_at, updated_at) |
| 37 | VALUES (:name, :value, :now, :now) |
| 38 | ON DUPLICATE KEY UPDATE value = :value, updated_at = :now |
| 39 | ", [ |
| 40 | 'name' => $name, |
| 41 | 'value' => is_array($value) ? serialize($value) : $value, |
| 42 | 'now' => $now, |
| 43 | ]); |
| 44 | |
| 45 | // Ensure entity data is up-to-date in memory. |
| 46 | // - We can't use "refresh()"; we don't have the entity instance, and it can be a new record. |
| 47 | // - We can't use "findOneBy()"; it could return a cached entity instance. |
| 48 | $this->findOneByName($name); |
| 49 | } |
| 50 | |
| 51 | protected function getEntityClassName() { |
| 52 | return SettingEntity::class; |
| 53 | } |
| 54 | } |
| 55 |