Skip to content

EspoCRM – Open Source CRM Application

Data cache access

Yurii70a9c4b2631d
diff --git a/application/Espo/Core/Acl/GlobalRestriction.php b/application/Espo/Core/Acl/GlobalRestriction.php
index 4a6cc54244..473951a8d9 100644
--- a/application/Espo/Core/Acl/GlobalRestriction.php
+++ b/application/Espo/Core/Acl/GlobalRestriction.php
@@ -29,8 +29,7 @@
namespace Espo\Core\Acl;
-use Espo\Core\Utils\Config\SystemConfig;
-use Espo\Core\Utils\DataCache;
+use Espo\Core\Utils\Cache\DataCacheAccess;
use Espo\Core\Utils\FieldUtil;
use Espo\Core\Utils\Metadata;
@@ -83,45 +82,21 @@ class GlobalRestriction
self::TYPE_READ_ONLY,
];
- private ?stdClass $data = null;
-
private string $cacheKey = 'entityAcl';
public function __construct(
private Metadata $metadata,
- private DataCache $dataCache,
private FieldUtil $fieldUtil,
- SystemConfig $systemConfig,
+ private DataCacheAccess $dataCacheAccess,
) {
- $useCache = $systemConfig->useCache();
-
- if ($useCache && $this->dataCache->has($this->cacheKey)) {
- /** @var stdClass $cachedData */
- $cachedData = $this->dataCache->get($this->cacheKey);
-
- $this->data = $cachedData;
-
- return;
- }
-
- if (!$this->data) {
- $this->buildData();
- }
-
- if ($useCache) {
- $this->storeCacheFile();
- }
- }
-
- private function storeCacheFile(): void
- {
- assert($this->data !== null);
-
- $this->dataCache->store($this->cacheKey, $this->data);
+ $this->dataCacheAccess->init(
+ key: $this->cacheKey,
+ loader: fn () => $this->buildData(),
+ );
}
- private function buildData(): void
+ private function buildData(): stdClass
{
/** @var string[] $scopeList */
$scopeList = array_keys($this->metadata->get(['entityDefs']) ?? []);
@@ -211,7 +186,7 @@ class GlobalRestriction
}
}
- $this->data = $data;
+ return $data;
}
/**
@@ -220,21 +195,9 @@ class GlobalRestriction
*/
public function getScopeRestrictedFieldList(string $scope, string $type): array
{
- assert($this->data !== null);
-
- if (!property_exists($this->data, $scope)) {
- return [];
- }
+ $data = $this->dataCacheAccess->get();
- if (!property_exists($this->data->$scope, 'fields')) {
- return [];
- }
-
- if (!property_exists($this->data->$scope->fields, $type)) {
- return [];
- }
-
- return $this->data->$scope->fields->$type;
+ return $data->$scope->fields->$type ?? [];
}
/**
@@ -243,21 +206,9 @@ class GlobalRestriction
*/
public function getScopeRestrictedAttributeList(string $scope, string $type): array
{
- assert($this->data !== null);
-
- if (!property_exists($this->data, $scope)) {
- return [];
- }
-
- if (!property_exists($this->data->$scope, 'attributes')) {
- return [];
- }
+ $data = $this->dataCacheAccess->get();
- if (!property_exists($this->data->$scope->attributes, $type)) {
- return [];
- }
-
- return $this->data->$scope->attributes->$type;
+ return $data->$scope->attributes->$type ?? [];
}
/**
@@ -266,20 +217,8 @@ class GlobalRestriction
*/
public function getScopeRestrictedLinkList(string $scope, string $type): array
{
- assert($this->data !== null);
-
- if (!property_exists($this->data, $scope)) {
- return [];
- }
-
- if (!property_exists($this->data->$scope, 'links')) {
- return [];
- }
-
- if (!property_exists($this->data->$scope->links, $type)) {
- return [];
- }
+ $data = $this->dataCacheAccess->get();
- return $this->data->$scope->links->$type;
+ return $data->$scope->links->$type ?? [];
}
}
diff --git a/application/Espo/Core/Acl/Map/Map.php b/application/Espo/Core/Acl/Map/Map.php
index 55f5103926..49f2ab823b 100644
--- a/application/Espo/Core/Acl/Map/Map.php
+++ b/application/Espo/Core/Acl/Map/Map.php
@@ -30,10 +30,8 @@
namespace Espo\Core\Acl\Map;
use Espo\Core\Acl\Table;
-use Espo\Core\Utils\Config;
-use Espo\Core\Utils\DataCache;
+use Espo\Core\Utils\Cache\DataCacheAccess;
use Espo\Core\Utils\ObjectUtil;
-
use stdClass;
use RuntimeException;
@@ -42,8 +40,6 @@ use RuntimeException;
*/
class Map
{
- private stdClass $data;
- private string $cacheKey;
/** @var array<string, string[]> */
private $forbiddenFieldsCache = [];
/** @var array<string, string[]> */
@@ -54,28 +50,20 @@ class Map
Table::LEVEL_NO,
];
+ /**
+ * @param DataCacheAccess<stdClass> $dataCacheAccess
+ */
public function __construct(
Table $table,
private DataBuilder $dataBuilder,
- private DataCache $dataCache,
CacheKeyProvider $cacheKeyProvider,
- Config\SystemConfig $systemConfig,
+ private DataCacheAccess $dataCacheAccess,
) {
- $this->cacheKey = $cacheKeyProvider->get();
-
- if ($systemConfig->useCache() && $this->dataCache->has($this->cacheKey)) {
- /** @var stdClass $cachedData */
- $cachedData = $this->dataCache->get($this->cacheKey);
-
- $this->data = $cachedData;
- } else {
- $this->data = $this->dataBuilder->build($table);
-
- if ($systemConfig->useCache()) {
- $this->dataCache->store($this->cacheKey, $this->data);
- }
- }
+ $this->dataCacheAccess->init(
+ key: $cacheKeyProvider->get(),
+ loader: fn () => $this->dataBuilder->build($table),
+ );
}
/**
@@ -83,7 +71,7 @@ class Map
*/
public function getData(): stdClass
{
- return ObjectUtil::clone($this->data);
+ return ObjectUtil::clone($this->dataCacheAccess->get());
}
/**
@@ -114,7 +102,9 @@ class Map
return $this->forbiddenAttributesCache[$key];
}
- $fieldTableQuickAccess = $this->data->fieldTableQuickAccess;
+ $data = $this->dataCacheAccess->get();
+
+ $fieldTableQuickAccess = $data->fieldTableQuickAccess;
if (
!isset($fieldTableQuickAccess->$scope) ||
@@ -186,7 +176,9 @@ class Map
return $this->forbiddenFieldsCache[$key];
}
- $fieldTableQuickAccess = $this->data->fieldTableQuickAccess;
+ $data = $this->dataCacheAccess->get();
+
+ $fieldTableQuickAccess = $data->fieldTableQuickAccess;
if (
!isset($fieldTableQuickAccess->$scope) ||
diff --git a/application/Espo/Core/Currency/InternalRatesProvider.php b/application/Espo/Core/Currency/InternalRatesProvider.php
index e52a2cd39e..efaa58ee66 100644
--- a/application/Espo/Core/Currency/InternalRatesProvider.php
+++ b/application/Espo/Core/Currency/InternalRatesProvider.php
@@ -30,10 +30,10 @@
namespace Espo\Core\Currency;
use Espo\Core\Field\Date;
-use Espo\Core\Utils\Config\SystemConfig;
-use Espo\Core\Utils\DataCache;
+use Espo\Core\Utils\Cache\DataCacheAccess;
use Espo\Core\Utils\DateTime;
use LogicException;
+use RuntimeException;
use stdClass;
/**
@@ -43,74 +43,55 @@ class InternalRatesProvider
{
private string $cacheKey = 'currencyRates';
- /** @var (stdClass&object{date: string, rates: stdClass})|null */
- private ?stdClass $data = null;
+ private ?Date $today = null;
+ private ?string $base = null;
+ /**
+ * @param DataCacheAccess<stdClass> $dataCacheAccess
+ */
public function __construct(
- private DataCache $dataCache,
- private SystemConfig $systemConfig,
private DateTime $dateTime,
private InternalRateEntryProvider $rateEntryProvider,
- ) {}
+ private DataCacheAccess $dataCacheAccess,
+ ) {
+ $this->dataCacheAccess->init(
+ key: $this->cacheKey,
+ loader: function () {
+ if (!$this->today || $this->base === null) {
+ throw new LogicException();
+ }
+
+ return $this->buildData($this->today, $this->base);
+ },
+ validityChecker: function (stdClass $data): bool {
+ if (!$this->today) {
+ throw new LogicException();
+ }
+
+ $date = $data->date ?? null;
+
+ return $date === $this->today->toString();
+ },
+ );
+ }
/**
* @return array<string, float>
*/
public function get(string $base): array
{
- $this->data ??= $this->getCachedData();
-
$today = $this->dateTime->getToday();
- if (!$this->data || $this->data->date !== $today->toString()) {
- $this->data = $this->buildData($today, $base);
+ $this->today = $today;
+ $this->base = $base;
- $this->storeData();
- }
-
- if ($this->data === null) {
- throw new LogicException();
- }
-
- return get_object_vars($this->data->rates);
- }
-
- /**
- * @return (stdClass&object{date: string, rates: stdClass})|null
- */
- private function getCachedData(): ?stdClass
- {
- if (!$this->systemConfig->useCache()) {
- return null;
- }
-
- $cached = $this->dataCache->tryGet($this->cacheKey);
-
- if (!$cached instanceof stdClass) {
- return null;
- }
-
- if (!isset($cached->date) || !isset($cached->rates)) {
- $this->dataCache->clear($this->cacheKey);
-
- return null;
- }
-
- /** @var stdClass&object{date: string, rates: stdClass} */
- return $cached;
- }
-
- private function storeData(): void
- {
- if (!$this->systemConfig->useCache()) {
- return;
- }
+ $data = $this->dataCacheAccess->get();
- if (!$this->data instanceof stdClass) {
- throw new LogicException();
+ if (!property_exists($data, 'rates')) {
+ throw new RuntimeException("Corrupted cache data in '$this->cacheKey'.");
}
- $this->dataCache->store($this->cacheKey, $this->data);
+ return get_object_vars($data->rates);
}
/**
diff --git a/application/Espo/Core/DataManager.php b/application/Espo/Core/DataManager.php
index 802cc02ed4..2361ead3ff 100644
--- a/application/Espo/Core/DataManager.php
+++ b/application/Espo/Core/DataManager.php
@@ -169,7 +169,7 @@ class DataManager
*/
public function rebuildMetadata(): void
{
- $this->metadata->init(true);
+ $this->metadata->init();
$this->ormMetadataData->reload();
$this->entityManager->getMetadata()->updateData();
diff --git a/application/Espo/Core/Loaders/Metadata.php b/application/Espo/Core/Loaders/Metadata.php
index bbc8653f0a..0cf435b513 100644
--- a/application/Espo/Core/Loaders/Metadata.php
+++ b/application/Espo/Core/Loaders/Metadata.php
@@ -31,18 +31,15 @@ namespace Espo\Core\Loaders;
use Espo\Core\Container\Loader;
use Espo\Core\InjectableFactory;
-use Espo\Core\Utils\Config;
use Espo\Core\Utils\Metadata as MetadataService;
class Metadata implements Loader
{
- public function __construct(private InjectableFactory $injectableFactory, private Config $config)
+ public function __construct(private InjectableFactory $injectableFactory)
{}
public function load(): MetadataService
{
- return $this->injectableFactory->createWith(MetadataService::class, [
- 'useCache' => $this->config->get('useCache') ?? false,
- ]);
+ return $this->injectableFactory->create(MetadataService::class);
}
}
diff --git a/application/Espo/Core/Utils/Cache/DataCacheAccess.php b/application/Espo/Core/Utils/Cache/DataCacheAccess.php
new file mode 100644
index 0000000000..ac5588743c
--- /dev/null
+++ b/application/Espo/Core/Utils/Cache/DataCacheAccess.php
@@ -0,0 +1,165 @@
+<?php
+/************************************************************************
+ * This file is part of EspoCRM.
+ *
+ * EspoCRM – Open Source CRM application.
+ * Copyright (C) 2014-2026 EspoCRM, Inc.
+ * Website: https://www.espocrm.com
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program 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 Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ * The interactive user interfaces in modified source and object code versions
+ * of this program must display Appropriate Legal Notices, as required under
+ * Section 5 of the GNU Affero General Public License version 3.
+ *
+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
+ ************************************************************************/
+
+namespace Espo\Core\Utils\Cache;
+
+use Closure;
+use Espo\Core\Utils\Config\SystemConfig;
+use Espo\Core\Utils\DataCache;
+use Espo\Core\Utils\Log;
+use LogicException;
+use stdClass;
+
+/**
+ * @internal
+ * @since 10.1.0
+ * @template T of array<int|string, mixed> | stdClass = array<int|string, mixed> | stdClass
+ */
+class DataCacheAccess
+{
+ /** @var T|null */
+ private mixed $data = null;
+
+ private ?string $key = null;
+
+ /** @var (Closure(): T)|null */
+ private ?Closure $loader = null;
+
+ /** @var (Closure(T): bool)|null */
+ private ?Closure $validityChecker = null;
+
+ public function __construct(
+ private DataCache $dataCache,
+ private SystemConfig $systemConfig,
+ private Log $log,
+ ) {}
+
+ /**
+ * @todo Event clearing loaded data.
+ *
+ * @param Closure(): T $loader
+ * @param (Closure(T): bool)|null $validityChecker
+ */
+ public function init(string $key, Closure $loader, ?Closure $validityChecker = null): void
+ {
+ $this->key = $key;
+ $this->loader = $loader;
+ $this->validityChecker = $validityChecker;
+
+ $this->data = null;
+ }
+
+ public function reset(): void
+ {
+ $this->data = null;
+ }
+
+ /**
+ * @param T $data
+ */
+ public function set(mixed $data): void
+ {
+ $this->data = $data;
+ }
+
+ public function store(): void
+ {
+ if (!$this->key) {
+ throw new LogicException("Not initialized.");
+ }
+
+ if ($this->data === null) {
+ throw new LogicException("Data not set.");
+ }
+
+ if ($this->systemConfig->useCache()) {
+ $this->dataCache->store($this->key, $this->data);
+ }
+ }
+
+ /**
+ * @return T
+ */
+ public function get(): mixed
+ {
+ if ($this->data && $this->validityChecker && !($this->validityChecker)($this->data)) {
+ $this->data = null;
+ }
+
+ if ($this->data !== null) {
+ return $this->data;
+ }
+
+ $key = $this->key;
+ $loader = $this->loader;
+
+ if (!$key || !$loader) {
+ throw new LogicException("Not initialized.");
+ }
+
+ if ($this->systemConfig->useCache() && $this->dataCache->has($key)) {
+ $this->loadFromCache();
+ }
+
+ if ($this->data === null) {
+ $this->data = $loader();
+
+ if ($this->systemConfig->useCache()) {
+ $this->dataCache->store($key, $this->data);
+ }
+ }
+
+ return $this->data;
+ }
+
+ private function loadFromCache(): void
+ {
+ $key = $this->key ?? throw new LogicException();
+
+ $data = $this->dataCache->tryGet($key);
+
+ if (is_array($data) || $data instanceof stdClass) {
+ /** @var T $data */
+
+ if ($this->validityChecker && !($this->validityChecker)($data)) {
+ $this->data = null;
+
+ return;
+ }
+
+ $this->data = $data;
+
+ return;
+ }
+
+ $this->log->warning("Corrupted cache data in '$key'.");
+
+ $this->dataCache->clear($key);
+ }
+}
diff --git a/application/Espo/Core/Utils/Metadata.php b/application/Espo/Core/Utils/Metadata.php
index a906ca1a6f..96191c963f 100644
--- a/application/Espo/Core/Utils/Metadata.php
+++ b/application/Espo/Core/Utils/Metadata.php
@@ -29,10 +29,10 @@
namespace Espo\Core\Utils;
+use Espo\Core\Utils\Cache\DataCacheAccess;
use Espo\Core\Utils\File\Manager as FileManager;
use Espo\Core\Utils\Metadata\Builder;
use Espo\Core\Utils\Metadata\BuilderHelper;
-
use stdClass;
use LogicException;
use RuntimeException;
@@ -42,55 +42,49 @@ use RuntimeException;
*/
class Metadata
{
- /** @var ?array<string, mixed> */
- private ?array $data = null;
- private ?stdClass $objData = null;
-
private string $cacheKey = 'metadata';
private string $objCacheKey = 'objMetadata';
private string $customPath = 'custom/Espo/Custom/Resources/metadata';
/** @var array<string, array<string, mixed>> */
private $deletedData = [];
+
/** @var array<string, array<string, mixed>> */
private $changedData = [];
+ /**
+ * @param DataCacheAccess<array<string, mixed>> $data
+ * @param DataCacheAccess<stdClass> $objectData
+ */
public function __construct(
private FileManager $fileManager,
- private DataCache $dataCache,
private Module $module,
private Builder $builder,
private BuilderHelper $builderHelper,
- private bool $useCache = false
- ) {}
+ private DataCacheAccess $data,
+ private DataCacheAccess $objectData,
+ ) {
+
+ $this->objectData->init(
+ key: $this->objCacheKey,
+ loader: fn () => $this->builder->build(),
+ );
+
+ $this->data->init(
+ key: $this->cacheKey,
+ loader: fn () => $this->getObjectConvertedToAssoc(),
+ );
+ }
/**
* Init metadata.
+ *
+ * @internal
*/
- public function init(bool $reload = false): void
+ public function init(): void
{
- if (!$this->useCache) {
- $reload = true;
- }
-
- if ($this->dataCache->has($this->cacheKey) && !$reload) {
- /** @var array<string, mixed> $data */
- $data = $this->dataCache->get($this->cacheKey);
-
- $this->data = $data;
-
- return;
- }
-
- $this->clearVars();
-
- $objData = $this->getObjData($reload);
-
- $this->data = Util::objectToArray($objData);
-
- if ($this->useCache) {
- $this->dataCache->store($this->cacheKey, $this->data);
- }
+ $this->reloadObject();
+ $this->reload();
}
/**
@@ -100,13 +94,7 @@ class Metadata
*/
private function getData(): array
{
- if (empty($this->data) || !is_array($this->data)) {
- $this->init();
- }
-
- assert($this->data !== null);
-
- return $this->data;
+ return $this->data->get();
}
/**
@@ -118,40 +106,9 @@ class Metadata
*/
public function get($key = null, $default = null)
{
- return Util::getValueByKey($this->getData(), $key, $default);
- }
-
- private function objInit(bool $reload = false): void
- {
- if (!$this->useCache) {
- $reload = true;
- }
-
- if ($this->dataCache->has($this->objCacheKey) && !$reload) {
- /** @var stdClass $data */
- $data = $this->dataCache->get($this->objCacheKey);
-
- $this->objData = $data;
-
- return;
- }
-
- $this->objData = $this->builder->build();
-
- if ($this->useCache) {
- $this->dataCache->store($this->objCacheKey, $this->objData);
- }
- }
-
- private function getObjData(bool $reload = false): stdClass
- {
- if (!isset($this->objData) || $reload) {
- $this->objInit($reload);
- }
+ $data = $this->data->get();
- assert($this->objData !== null);
-
- return $this->objData;
+ return Util::getValueByKey($data, $key, $default);
}
/**
@@ -163,18 +120,17 @@ class Metadata
*/
public function getObjects($key = null, $default = null)
{
- $objData = $this->getObjData();
-
- return Util::getValueByKey($objData, $key, $default);
+ return Util::getValueByKey($this->getAll(), $key, $default);
}
+ /**
+ * Important. Do not modify without cloning.
+ */
public function getAll(): stdClass
{
- return $this->getObjData();
+ return $this->objectData->get();
}
-
-
/**
* Get metadata definition in custom directory.
*
@@ -183,7 +139,7 @@ class Metadata
*/
public function getCustom(string $key1, string $key2, $default = null)
{
- $filePath = $this->customPath . "/$key1/$key2.json";
+ $filePath = "$this->customPath/$key1/$key2.json";
if (!$this->fileManager->isFile($filePath)) {
return $default;
@@ -213,13 +169,13 @@ class Metadata
}
}
- $filePath = $this->customPath . "/$key1/$key2.json";
+ $filePath = "$this->customPath/$key1/$key2.json";
$changedData = Json::encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$this->fileManager->putContents($filePath, $changedData);
- $this->init(true);
+ $this->init();
}
/**
@@ -264,11 +220,13 @@ class Metadata
/** @var array<string, array<string, mixed>> $mergedChangedData */
$mergedChangedData = Util::merge($this->changedData, $newData);
+
/** @var array<string, mixed> $mergedData */
$mergedData = Util::merge($this->getData(), $newData);
$this->changedData = $mergedChangedData;
- $this->data = $mergedData;
+
+ $this->data->set($mergedData);
if (is_array($data)) {
$this->undelete($key1, $key2, $data);
@@ -294,24 +252,27 @@ class Metadata
$unsetList = $unsets;
foreach ($unsetList as $unsetItem) {
- if (preg_match('/fields\.([^.]+)/', $unsetItem, $matches)) {
- $field = $matches[1];
- $fieldPath = [$key1, $key2, 'fields', $field];
-
- // @todo Revise the need. Additional fields are supposed to exist only in the build?
- $additionalFields = $this->builderHelper->getAdditionalFields(
- field: $field,
- params: $this->get($fieldPath, []),
- defs: $defs,
- );
+ if (!preg_match('/fields\.([^.]+)/', $unsetItem, $matches)) {
+ continue;
+ }
+
+ $field = $matches[1];
+ $fieldPath = [$key1, $key2, 'fields', $field];
- if (is_array($additionalFields)) {
- foreach ($additionalFields as $additionalFieldName => $additionalFieldParams) {
- $unsets[] = 'fields.' . $additionalFieldName;
- }
+ // @todo Revise the need. Additional fields are supposed to exist only in the build?
+ $additionalFields = $this->builderHelper->getAdditionalFields(
+ field: $field,
+ params: $this->get($fieldPath, []),
+ defs: $defs,
+ );
+
+ if (is_array($additionalFields)) {
+ foreach ($additionalFields as $additionalFieldName => $additionalFieldParams) {
+ $unsets[] = 'fields.' . $additionalFieldName;
}
}
}
+
break;
}
@@ -343,7 +304,8 @@ class Metadata
/** @var array<string, mixed> $data */
$data = Util::unsetInArray($this->getData(), $metadataUnsetData, true);
- $this->data = $data;
+
+ $this->data->set($data);
}
/**
@@ -351,13 +313,15 @@ class Metadata
*/
private function undelete(string $key1, string $key2, $data): void
{
- if (isset($this->deletedData[$key1][$key2])) {
- foreach ($this->deletedData[$key1][$key2] as $unsetIndex => $unsetItem) {
- $value = Util::getValueByKey($data, $unsetItem);
+ if (!isset($this->deletedData[$key1][$key2])) {
+ return;
+ }
- if (isset($value)) {
- unset($this->deletedData[$key1][$key2][$unsetIndex]);
- }
+ foreach ($this->deletedData[$key1][$key2] as $unsetIndex => $unsetItem) {
+ $value = Util::getValueByKey($data, $unsetItem);
+
+ if (isset($value)) {
+ unset($this->deletedData[$key1][$key2][$unsetIndex]);
}
}
}
@@ -370,7 +334,7 @@ class Metadata
$this->changedData = [];
$this->deletedData = [];
- $this->init(true);
+ $this->init();
}
/**
@@ -389,7 +353,7 @@ class Metadata
continue;
}
- $filePath = $path . "/$key1/$key2.json";
+ $filePath = "$path/$key1/$key2.json";
$result &= $this->fileManager->mergeJsonContents($filePath, $data);
}
@@ -403,7 +367,7 @@ class Metadata
continue;
}
- $filePath = $path . "/$key1/$key2.json";
+ $filePath = "$path/$key1/$key2.json";
$rowResult = $this->fileManager->unsetJsonContents($filePath, $unsetData);
@@ -443,8 +407,29 @@ class Metadata
return $this->get(['scopes', $scopeName, 'module']);
}
- private function clearVars(): void
+ private function reloadObject(): void
+ {
+ $data = $this->builder->build();
+
+ $this->objectData->set($data);
+ $this->objectData->store();
+ }
+
+ private function reload(): void
{
- $this->data = null;
+ $data = $this->getObjectConvertedToAssoc();
+
+ $this->data->set($data);
+ $this->data->store();
+ }
+
+ /**
+ * @return array<string, mixed>
+ */
+ private function getObjectConvertedToAssoc(): array
+ {
+ $data = $this->objectData->get();
+
+ return Util::objectToArray($data);
}
}
diff --git a/application/Espo/Core/Webhook/Manager.php b/application/Espo/Core/Webhook/Manager.php
index cbe0167133..d78e32ea99 100644
--- a/application/Espo/Core/Webhook/Manager.php
+++ b/application/Espo/Core/Webhook/Manager.php
@@ -32,16 +32,13 @@ namespace Espo\Core\Webhook;
use Espo\Core\Name\Field;
use Espo\Core\ORM\Entity;
use Espo\Core\ORM\EntityManager;
+use Espo\Core\Utils\Cache\DataCacheAccess;
use Espo\Core\Utils\Config;
-use Espo\Core\Utils\Config\SystemConfig;
-use Espo\Core\Utils\DataCache;
use Espo\Core\Utils\FieldUtil;
use Espo\Core\Utils\Log;
use Espo\Entities\Webhook;
use Espo\Entities\WebhookEventQueueItem;
-
use Espo\ORM\Name\Attribute;
-use RuntimeException;
use stdClass;
/**
@@ -63,45 +60,21 @@ class Manager
Field::VERSION_NUMBER,
];
- /** @var ?array<string, bool> */
- private $data = null;
-
+ /**
+ * @param DataCacheAccess<array<string, bool>> $dataCacheAccess
+ */
public function __construct(
private Config $config,
- private DataCache $dataCache,
private EntityManager $entityManager,
private FieldUtil $fieldUtil,
private Log $log,
- private SystemConfig $systemConfig,
+ private DataCacheAccess $dataCacheAccess,
) {
- $this->loadData();
- }
-
- private function loadData(): void
- {
- if ($this->systemConfig->useCache() && $this->dataCache->has($this->cacheKey)) {
- /** @var array<string, bool> $data */
- $data = $this->dataCache->get($this->cacheKey);
-
- $this->data = $data;
- }
-
- if (is_null($this->data)) {
- $this->data = $this->buildData();
-
- if ($this->systemConfig->useCache()) {
- $this->storeDataToCache();
- }
- }
- }
-
- private function storeDataToCache(): void
- {
- if ($this->data === null) {
- throw new RuntimeException("No data to store.");
- }
- $this->dataCache->store($this->cacheKey, $this->data);
+ $this->dataCacheAccess->init(
+ key: $this->cacheKey,
+ loader: fn () => $this->buildData(),
+ );
}
/**
@@ -135,11 +108,12 @@ class Manager
*/
public function addEvent(string $event): void
{
- $this->data[$event] = true;
+ $data = $this->dataCacheAccess->get();
- if ($this->systemConfig->useCache()) {
- $this->storeDataToCache();
- }
+ $data[$event] = true;
+
+ $this->dataCacheAccess->set($data);
+ $this->dataCacheAccess->store();
}
/**
@@ -160,16 +134,19 @@ class Manager
return;
}
- unset($this->data[$event]);
+ $data = $this->dataCacheAccess->get();
- if ($this->systemConfig->useCache()) {
- $this->storeDataToCache();
- }
+ unset($data[$event]);
+
+ $this->dataCacheAccess->set($data);
+ $this->dataCacheAccess->store();
}
private function eventExists(string $event): bool
{
- return isset($this->data[$event]);
+ $data = $this->dataCacheAccess->get();
+
+ return isset($data[$event]);
}
private function logDebugEvent(string $event, Entity $entity): void
diff --git a/tests/unit/Espo/Core/Acl/Map/MapTest.php b/tests/unit/Espo/Core/Acl/Map/MapTest.php
index 694df5d25b..40d35c3c4c 100644
--- a/tests/unit/Espo/Core/Acl/Map/MapTest.php
+++ b/tests/unit/Espo/Core/Acl/Map/MapTest.php
@@ -36,35 +36,29 @@ use Espo\Core\Acl\Map\Map;
use Espo\Core\Acl\Map\MetadataProvider;
use Espo\Core\Acl\ScopeData;
use Espo\Core\Acl\Table;
-use Espo\Core\Utils\Config;
+use Espo\Core\Utils\Cache\DataCacheAccess;
+use Espo\Core\Utils\Config\SystemConfig;
use Espo\Core\Utils\DataCache;
use Espo\Core\Utils\FieldUtil;
+use Espo\Core\Utils\Log;
use PHPUnit\Framework\TestCase;
use stdClass;
class MapTest extends TestCase
{
private $fieldUtil;
- private $systemConfig;
private $table;
private $metadataProvider;
private $cacheKeyProvider;
- private $dataCache;
protected function setUp(): void
{
- $this->systemConfig = $this->createMock(Config\SystemConfig::class);
$this->fieldUtil = $this->createMock(FieldUtil::class);
$this->table = $this->createMock(Table::class);
- $this->dataCache = $this->createMock(DataCache::class);
$this->metadataProvider = $this->createMock(MetadataProvider::class);
$this->cacheKeyProvider = $this->createMock(CacheKeyProvider::class);
- $this->systemConfig
- ->expects($this->any())
- ->method('useCache')
- ->willReturn(false);
}
private function mockTableData(array $scopeData, array $fieldData, array $permissionData): void
@@ -201,12 +195,20 @@ class MapTest extends TestCase
$expectedData = $this->getExpectedRawData();
+ $this->cacheKeyProvider->method('get')
+ ->willReturn('key');
+
+ $dataCacheAccess = new DataCacheAccess(
+ dataCache: $this->createMock(DataCache::class),
+ systemConfig: $this->createMock(SystemConfig::class),
+ log: $this->createMock(Log::class),
+ );
+
$map = new Map(
- $this->table,
- $dataBuilder,
- $this->dataCache,
- $this->cacheKeyProvider,
- $this->systemConfig,
+ table: $this->table,
+ dataBuilder: $dataBuilder,
+ cacheKeyProvider: $this->cacheKeyProvider,
+ dataCacheAccess: $dataCacheAccess,
);
$this->assertEquals($expectedData, $map->getData());
diff --git a/tests/unit/Espo/Core/Utils/MetadataTest.php b/tests/unit/Espo/Core/Utils/MetadataTest.php
index 6bd532f16c..75265ebcab 100644
--- a/tests/unit/Espo/Core/Utils/MetadataTest.php
+++ b/tests/unit/Espo/Core/Utils/MetadataTest.php
@@ -29,13 +29,15 @@
namespace tests\unit\Espo\Core\Utils;
+use Espo\Core\Utils\Cache\DataCacheAccess;
+use Espo\Core\Utils\Config\SystemConfig;
+use Espo\Core\Utils\DataCache;
+use Espo\Core\Utils\Json;
use PHPUnit\Framework\TestCase;
use tests\unit\ReflectionHelper;
-
use Espo\Core\Utils\Metadata;
use Espo\Core\Utils\File\Manager as FileManager;
use Espo\Core\Utils\Log;
-use Espo\Core\Utils\DataCache;
use Espo\Core\Utils\File\UnifierObj;
use Espo\Core\Utils\File\Unifier;
use Espo\Core\Utils\Module;
@@ -45,21 +47,16 @@ use Espo\Core\Utils\Resource\PathProvider;
class MetadataTest extends TestCase
{
- private $object;
+ private ?Metadata $metadata = null;
private $reflection;
- private $fileManager;
+ private ?FileManager $fileManager = null;
+
private $customPath;
protected function setUp(): void
{
$this->fileManager = new FileManager();
- $dataCache = $this->getMockBuilder(DataCache::class)->disableOriginalConstructor()->getMock();
-
- $log = $this->getMockBuilder(Log::class)->disableOriginalConstructor()->getMock();
-
- $GLOBALS['log'] = $log;
-
$module = new Module($this->fileManager);
$pathProvider = new PathProvider(new ModulePathProvider($module));
@@ -73,16 +70,28 @@ class MetadataTest extends TestCase
$builder = new Metadata\Builder($reader);
- $this->object = new Metadata(
- $this->fileManager,
- $dataCache,
- $module,
- $builder,
- $builderHelper,
- true
+ $dataCacheAccess = new DataCacheAccess(
+ dataCache: $this->createMock(DataCache::class),
+ systemConfig: $this->createMock(SystemConfig::class),
+ log: $this->createMock(Log::class),
);
- $this->reflection = new ReflectionHelper($this->object);
+ $objectDataCacheAccess = new DataCacheAccess(
+ dataCache: $this->createMock(DataCache::class),
+ systemConfig: $this->createMock(SystemConfig::class),
+ log: $this->createMock(Log::class),
+ );
+
+ $this->metadata = new Metadata(
+ fileManager: $this->fileManager,
+ module: $module,
+ builder: $builder,
+ builderHelper: $builderHelper,
+ data: $dataCacheAccess,
+ objectData: $objectDataCacheAccess,
+ );
+
+ $this->reflection = new ReflectionHelper($this->metadata);
$this->customPath = 'tests/unit/testData/cache/metadata/custom';
@@ -91,180 +100,170 @@ class MetadataTest extends TestCase
protected function tearDown() : void
{
- $this->object->clearChanges();
- $this->object = NULL;
+ $this->metadata->clearChanges();
+ $this->metadata = null;
}
- public function testGet()
+ public function testGet(): void
{
- $this->assertEquals('System', $this->object->get('app.adminPanel.system.label'));
+ $this->assertEquals('System', $this->metadata->get('app.adminPanel.system.label'));
- $this->assertArrayHasKey('fields', $this->object->get('entityDefs.User'));
+ $this->assertArrayHasKey('fields', $this->metadata->get('entityDefs.User'));
}
- public function testSet()
+ public function testSet(): void
{
- $data = array (
+ $data = [
'fields' =>
- array (
+ [
'name' =>
- array (
+ [
'required' => false,
'maxLength' => 150,
'view' => 'Views.Test.Custom',
- ),
- ),
- );
+ ],
+ ],
+ ];
- $this->object->set('entityDefs', 'Attachment', $data);
+ $this->metadata->set('entityDefs', 'Attachment', $data);
- $this->assertEquals('Views.Test.Custom', $this->object->get('entityDefs.Attachment.fields.name.view'));
- $this->assertEquals(150, $this->object->get('entityDefs.Attachment.fields.name.maxLength'));
+ $this->assertEquals('Views.Test.Custom', $this->metadata->get('entityDefs.Attachment.fields.name.view'));
+ $this->assertEquals(150, $this->metadata->get('entityDefs.Attachment.fields.name.maxLength'));
- $result = array(
- 'entityDefs' => array(
+ $result = [
+ 'entityDefs' => [
'Attachment' => $data
- ),
- );
+ ],
+ ];
$this->assertEquals($result, $this->reflection->getProperty('changedData'));
- $data = array (
+ $data = [
'fields' =>
- array (
+ [
'name' =>
- array (
+ [
'maxLength' => 200,
- ),
- ),
- );
+ ],
+ ],
+ ];
- $this->object->set('entityDefs', 'Attachment', $data);
- $this->assertEquals(200, $this->object->get('entityDefs.Attachment.fields.name.maxLength'));
- $this->assertEquals('Views.Test.Custom', $this->object->get('entityDefs.Attachment.fields.name.view'));
+ $this->metadata->set('entityDefs', 'Attachment', $data);
+ $this->assertEquals(200, $this->metadata->get('entityDefs.Attachment.fields.name.maxLength'));
+ $this->assertEquals('Views.Test.Custom', $this->metadata->get('entityDefs.Attachment.fields.name.view'));
- $result = array(
- 'entityDefs' => array(
- 'Attachment' => array (
+ $result = [
+ 'entityDefs' => [
+ 'Attachment' => [
'fields' =>
- array (
+ [
'name' =>
- array (
+ [
'required' => false,
'maxLength' => 200,
'view' => 'Views.Test.Custom',
- ),
- ),
- ),
- ),
- );
+ ],
+ ],
+ ],
+ ],
+ ];
$this->assertEquals($result, $this->reflection->getProperty('changedData'));
- $this->object->clearChanges();
+ $this->metadata->clearChanges();
- $this->assertEquals(array(), $this->reflection->getProperty('changedData'));
- $this->assertEquals(255, $this->object->get('entityDefs.Attachment.fields.name.maxLength'));
+ $this->assertEquals([], $this->reflection->getProperty('changedData'));
+ $this->assertEquals(255, $this->metadata->get('entityDefs.Attachment.fields.name.maxLength'));
}
- public function testDelete()
+ public function testDelete(): void
{
- $data = array (
+ $this->metadata->delete('entityDefs', 'Attachment', [
'fields.name.type',
- );
- $this->object->delete('entityDefs', 'Attachment', $data);
- $this->assertNull($this->object->get('entityDefs.Attachment.fields.name.type'));
+ ]);
- $result = array(
- 'entityDefs' => array(
- 'Attachment' => array(
- 'fields.name.type',
- ),
- ),
- );
+ $this->assertNull($this->metadata->get('entityDefs.Attachment.fields.name.type'));
- $this->assertEquals($result, $this->reflection->getProperty('deletedData'));
+ $this->assertEquals([
+ 'entityDefs' => [
+ 'Attachment' => [
+ 'fields.name.type',
+ ],
+ ],
+ ], $this->reflection->getProperty('deletedData'));
- $data = array (
+ $this->metadata->delete('entityDefs', 'Attachment', [
'fields.name.required',
- );
- $this->object->delete('entityDefs', 'Attachment', $data);
- $this->assertNull($this->object->get('entityDefs.Attachment.fields.name.required'));
+ ]);
+
+ $this->assertNull($this->metadata->get('entityDefs.Attachment.fields.name.required'));
- $result = array(
- 'entityDefs' => array(
- 'Attachment' => array(
+ $this->assertEquals([
+ 'entityDefs' => [
+ 'Attachment' => [
'fields.name.type',
'fields.name.required',
- ),
- ),
- );
- $this->assertEquals($result, $this->reflection->getProperty('deletedData'));
+ ],
+ ],
+ ], $this->reflection->getProperty('deletedData'));
- $this->object->init(false);
+ $this->metadata->init();
- $this->assertNotNull($this->object->get('entityDefs.Attachment.fields.name.type'));
- $this->assertNotNull($this->object->get('entityDefs.Attachment.fields.name.required'));
+ $this->assertNotNull($this->metadata->get('entityDefs.Attachment.fields.name.type'));
+ $this->assertNotNull($this->metadata->get('entityDefs.Attachment.fields.name.required'));
- $this->object->clearChanges();
+ $this->metadata->clearChanges();
$this->assertEquals([], $this->reflection->getProperty('deletedData'));
}
- public function testUndelete()
+ public function testUndelete(): void
{
- $data = [
+ $this->metadata->delete('entityDefs', 'Attachment', [
'fields.name.type',
'fields.name.required',
- ];
+ ]);
- $this->object->delete('entityDefs', 'Attachment', $data);
- $this->assertNull($this->object->get('entityDefs.Attachment.fields.name.type'));
+ $this->assertNull($this->metadata->get('entityDefs.Attachment.fields.name.type'));
- $data = array (
- 'fields' =>
- array (
- 'name' =>
- array (
- 'type' => 'enum',
- ),
- ),
- );
- $this->object->set('entityDefs', 'Attachment', $data);
- $this->assertEquals('enum', $this->object->get('entityDefs.Attachment.fields.name.type'));
- $result = array(
- 'entityDefs' => array(
- 'Attachment' => array(
+ $this->metadata->set('entityDefs', 'Attachment', [
+ 'fields' => [
+ 'name' => [
+ 'type' => 'enum',
+ ],
+ ],
+ ]);
+
+ $this->assertEquals('enum', $this->metadata->get('entityDefs.Attachment.fields.name.type'));
+
+ $this->assertEquals([
+ 'entityDefs' => [
+ 'Attachment' => [
1 => 'fields.name.required',
- ),
- ),
- );
- $this->assertEquals($result, $this->reflection->getProperty('deletedData'));
+ ],
+ ],
+ ], $this->reflection->getProperty('deletedData'));
- $data = array (
- 'fields' =>
- array (
- 'name' =>
- array (
- 'required' => true,
- ),
- ),
- );
- $this->object->set('entityDefs', 'Attachment', $data);
- $this->assertEquals(true, $this->object->get('entityDefs.Attachment.fields.name.required'));
-
- $result = array(
- 'entityDefs' => array(
- 'Attachment' => array(
- ),
- ),
- );
- $this->assertEquals($result, $this->reflection->getProperty('deletedData'));
+ $this->metadata->set('entityDefs', 'Attachment', [
+ 'fields' => [
+ 'name' => [
+ 'required' => true,
+ ],
+ ],
+ ]);
+
+ $this->assertEquals(true, $this->metadata->get('entityDefs.Attachment.fields.name.required'));
+
+ $this->assertEquals([
+ 'entityDefs' => [
+ 'Attachment' => [],
+ ],
+ ], $this->reflection->getProperty('deletedData'));
}
- public function testGetCustom()
+ public function testGetCustom(): void
{
- $this->assertNull($this->object->getCustom('entityDefs', 'Lead'));
+ $this->assertNull($this->metadata->getCustom('entityDefs', 'Lead'));
- $customData = $this->object->getCustom('entityDefs', 'Lead', (object) []);
+ $customData = $this->metadata->getCustom('entityDefs', 'Lead', (object) []);
$this->assertTrue(is_object($customData));
@@ -277,14 +276,14 @@ class MetadataTest extends TestCase
],
];
- $this->object->saveCustom('entityDefs', 'Lead', $data);
+ $this->metadata->saveCustom('entityDefs', 'Lead', $data);
- $this->assertEquals($data, $this->object->getCustom('entityDefs', 'Lead'));
+ $this->assertEquals($data, $this->metadata->getCustom('entityDefs', 'Lead'));
unlink($this->customPath . '/entityDefs/Lead.json');
}
- public function testSaveCustom1()
+ public function testSaveCustom1(): void
{
$data = (object) [
'fields' => (object) [
@@ -295,19 +294,19 @@ class MetadataTest extends TestCase
],
];
- $this->object->saveCustom('entityDefs', 'Lead', $data);
+ $this->metadata->saveCustom('entityDefs', 'Lead', $data);
$savedFile = $this->customPath . '/entityDefs/Lead.json';
$fileContent = $this->fileManager->getContents($savedFile);
- $savedData = \Espo\Core\Utils\Json::decode($fileContent);
+ $savedData = Json::decode($fileContent);
$this->assertEquals($data, $savedData);
unlink($savedFile);
}
- public function testSaveCustom2()
+ public function testSaveCustom2(): void
{
$initData = (object) [
'fields' => (object) [
@@ -318,19 +317,19 @@ class MetadataTest extends TestCase
],
];
- $this->object->saveCustom('entityDefs', 'Lead', $initData);
+ $this->metadata->saveCustom('entityDefs', 'Lead', $initData);
- $customData = $this->object->getCustom('entityDefs', 'Lead');
+ $customData = $this->metadata->getCustom('entityDefs', 'Lead');
unset($customData->fields->status->type);
$customData->fields->status->options = ["__APPEND__", "Test1"];
- $this->object->saveCustom('entityDefs', 'Lead', $customData);
+ $this->metadata->saveCustom('entityDefs', 'Lead', $customData);
$savedFile = $this->customPath . '/entityDefs/Lead.json';
$fileContent = $this->fileManager->getContents($savedFile);
- $savedData = \Espo\Core\Utils\Json::decode($fileContent);
+ $savedData = Json::decode($fileContent);
$expectedData = (object) [
'fields' => (object) [
@@ -345,10 +344,10 @@ class MetadataTest extends TestCase
unlink($savedFile);
}
- public function testGetObjects()
+ public function testGetObjects(): void
{
- $this->assertEquals('System', $this->object->getObjects('app.adminPanel.system.label'));
- $this->assertObjectHasProperty('fields', $this->object->getObjects('entityDefs.User'));
- $this->assertObjectHasProperty('type', $this->object->getObjects('entityDefs.User.fields.name'));
+ $this->assertEquals('System', $this->metadata->getObjects('app.adminPanel.system.label'));
+ $this->assertObjectHasProperty('fields', $this->metadata->getObjects('entityDefs.User'));
+ $this->assertObjectHasProperty('type', $this->metadata->getObjects('entityDefs.User.fields.name'));
}
}