Skip to content

Commit

Permalink
feat(settings): add cache system
Browse files Browse the repository at this point in the history
  • Loading branch information
lanfisis committed Sep 29, 2023
1 parent 6443d41 commit d3d358e
Show file tree
Hide file tree
Showing 12 changed files with 223 additions and 66 deletions.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,19 @@ For a new value you need to specify the type.

⚠️ When specifying the type, be sure to know what you are doing as it should be coherent with the Form Type of the field.

### Use cache

Settings use `cache.adapter.array` adapter by default. If you want to increase performance, you can use
`cache.adapter.apcu`, `cache.adapter.redis` or any adapters instead.


You had to add the following lines to your config file:

```yaml
monsieurbiz_sylius_settings:
cache_adapter: cache.adapter.apcu
```
## Contributing
You can find a way to run the plugin without effort in the file [DEVELOPMENT.md](./DEVELOPMENT.md).
Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
"php": "^8.0",
"ext-mbstring": "*",
"ext-json": "*",
"sylius/sylius": ">=1.10 <1.13"
"sylius/sylius": ">=1.10 <1.13",
"symfony/cache": "^5.4.28 || ^6.0"
},
"require-dev": {
"behat/behat": "^3.6.1",
Expand Down
73 changes: 73 additions & 0 deletions src/CacheWarmer/SettingsCacheWarmer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

/*
* This file is part of Monsieur Biz' Settings plugin for Sylius.
*
* (c) Monsieur Biz <[email protected]>
*
* For the full copyright and license information, please view the LICENSE.txt
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace MonsieurBiz\SyliusSettingsPlugin\CacheWarmer;

use Doctrine\ORM\EntityManagerInterface;
use MonsieurBiz\SyliusSettingsPlugin\Settings\RegistryInterface;
use Sylius\Component\Channel\Repository\ChannelRepositoryInterface;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Locale\Model\LocaleInterface;

final class SettingsCacheWarmer implements SettingsCacheWarmerInterface
{
public function __construct(
private ChannelRepositoryInterface $channelRepository,
private RegistryInterface $registry,
private EntityManagerInterface $entityManager,
) {
}

public function isOptional(): bool
{
return false;
}

/**
* @SuppressWarnings(PHPMD.UnusedFormalParameters)
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function warmUp(string $cacheDir): array
{
if (
false === $this->entityManager->getConnection()->isConnected()
|| false === $this->entityManager->getConnection()->getSchemaManager()->tablesExist('mbiz_settings_setting')
) {
return [];
}

$settings = $this->registry->getAllSettings();
foreach ($settings as $setting) {
$setting->getSettingsByChannelAndLocale();
$setting->getSettingsByChannelAndLocale(null, null, true);

/** @var ChannelInterface $channel */
foreach ($this->channelRepository->findAll() as $channel) {
if (null === $channel->getCode()) {
continue;
}

$setting->getSettingsByChannelAndLocale($channel);
$setting->getSettingsByChannelAndLocale($channel, null, true);

/** @var LocaleInterface $locale */
foreach ($channel->getLocales() as $locale) {
$setting->getSettingsByChannelAndLocale($channel, $locale->getCode());
$setting->getSettingsByChannelAndLocale($channel, $locale->getCode(), true);
}
}
}

return [];
}
}
20 changes: 20 additions & 0 deletions src/CacheWarmer/SettingsCacheWarmerInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

/*
* This file is part of Monsieur Biz' Settings plugin for Sylius.
*
* (c) Monsieur Biz <[email protected]>
*
* For the full copyright and license information, please view the LICENSE.txt
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace MonsieurBiz\SyliusSettingsPlugin\CacheWarmer;

use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;

interface SettingsCacheWarmerInterface extends CacheWarmerInterface
{
}
16 changes: 12 additions & 4 deletions src/Controller/SettingsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace MonsieurBiz\SyliusSettingsPlugin\Controller;

use MonsieurBiz\SyliusSettingsPlugin\CacheWarmer\SettingsCacheWarmerInterface;
use MonsieurBiz\SyliusSettingsPlugin\Factory\Form\MainSettingsFormTypeFactoryInterface;
use MonsieurBiz\SyliusSettingsPlugin\Form\MainSettingsType;
use MonsieurBiz\SyliusSettingsPlugin\Processor\SettingsProcessorInterface;
Expand All @@ -22,15 +23,15 @@
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\Cache\TagAwareCacheInterface;

final class SettingsController extends AbstractController
{
/**
* SettingsController constructor.
*/
public function __construct(
private SettingsProcessorInterface $settingsProcessor,
private MainSettingsFormTypeFactoryInterface $formFactory
private MainSettingsFormTypeFactoryInterface $formFactory,
private TagAwareCacheInterface $monsieurbizSettingsCache,
private SettingsCacheWarmerInterface $cacheWarmer,
) {
}

Expand All @@ -54,6 +55,8 @@ public function formAction(Request $request, RegistryInterface $registry, string
$data = (array) $form->getData();
$this->settingsProcessor->processData($settings, $data);
$this->addFlash('success', 'monsieurbiz.settings.settings_successfully_saved');
$this->cleanCache($settings);
$this->cacheWarmer->warmUp('');

return $this->redirectToRoute('monsieurbiz_sylius_settings_admin_edit', [
'alias' => $settings->getAlias(),
Expand Down Expand Up @@ -83,4 +86,9 @@ private function getForm(SettingsInterface $settings): FormInterface
],
);
}

private function cleanCache(SettingsInterface $settings): void
{
$this->monsieurbizSettingsCache->invalidateTags([$settings->getAlias()]);
}
}
1 change: 1 addition & 0 deletions src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ private function addPlugins(ArrayNodeDefinition $rootNode): void
/** @phpstan-ignore-next-line */
$rootNode
->children()
->scalarNode('cache_adapter')->defaultValue('cache.adapter.array')->end()
->arrayNode('plugins')
->useAttributeAsKey('name', false)
->defaultValue([])
Expand Down
1 change: 1 addition & 0 deletions src/DependencyInjection/InstantiateSettingsPass.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public function process(ContainerBuilder $container): void
$container->setDefinition($id, new Definition($class, [
$this->getMetadataDefinition($metadata),
$container->findDefinition('monsieurbiz_settings.repository.setting'),
$container->findDefinition('monsieurbiz_settings.cache'),
]));

$aliases = [
Expand Down
28 changes: 28 additions & 0 deletions src/DependencyInjection/MonsieurBizSyliusSettingsExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,5 +59,33 @@ public function prepend(ContainerBuilder $container): void
'MonsieurBiz\SyliusSettingsPlugin\Migrations' => '@MonsieurBizSyliusSettingsPlugin/Migrations',
]),
]);

$this->addCachePool($container);
}

private function addCachePool(ContainerBuilder $container): void
{
$settingConfigs = $container->getExtensionConfig($this->getAlias());
$configuration = $this->getConfiguration([], $container);
if (null === $configuration) {
return;
}

$cacheAdapter = $this->processConfiguration($configuration, $settingConfigs)['cache_adapter'] ?: null;
if (null === $cacheAdapter) {
return;
}

$container->prependExtensionConfig('framework', [
'cache' => [
'pools' => [
'monsieurbiz_settings.cache' => [
'adapter' => $cacheAdapter,
'public' => false,
'tags' => true,
],
],
],
]);
}
}
8 changes: 4 additions & 4 deletions src/Factory/Form/MainSettingsFormTypeFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,13 @@ public function createNew(SettingsInterface $settings, string $type, array $opti
private function getInitialFormData(SettingsInterface $settings): array
{
$data = [
Settings::DEFAULT_KEY . '-' . Settings::DEFAULT_KEY => $settings->getSettingsValuesByChannelAndLocale() + $settings->getDefaultValues(),
Settings::DEFAULT_KEY . '-' . Settings::DEFAULT_KEY => $settings->getSettingsValuesByChannelAndLocale(useCache: false) + $settings->getDefaultValues(),
];

if ($settings->showLocalesInForm()) {
/** @var LocaleInterface $locale */
foreach ($this->localeRepository->findAll() as $locale) {
$data[Settings::DEFAULT_KEY . '-' . $locale->getCode()] = $settings->getSettingsValuesByChannelAndLocale(null, $locale->getCode());
$data[Settings::DEFAULT_KEY . '-' . $locale->getCode()] = $settings->getSettingsValuesByChannelAndLocale(null, $locale->getCode(), false);
}
}

Expand All @@ -64,11 +64,11 @@ private function getChannelInitialFormData(SettingsInterface $settings): array
$data = [];
/** @var ChannelInterface $channel */
foreach ($this->channelRepository->findAll() as $channel) {
$data['channel-' . $channel->getId() . '-' . Settings::DEFAULT_KEY] = $settings->getSettingsValuesByChannelAndLocale($channel);
$data['channel-' . $channel->getId() . '-' . Settings::DEFAULT_KEY] = $settings->getSettingsValuesByChannelAndLocale($channel, useCache: false);

if ($settings->showLocalesInForm()) {
foreach ($channel->getLocales() as $locale) {
$data['channel-' . $channel->getId() . '-' . $locale->getCode()] = $settings->getSettingsValuesByChannelAndLocale($channel, $locale->getCode());
$data['channel-' . $channel->getId() . '-' . $locale->getCode()] = $settings->getSettingsValuesByChannelAndLocale($channel, $locale->getCode(), false);
}
}
}
Expand Down
4 changes: 3 additions & 1 deletion src/Processor/SettingsProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,9 @@ private function saveSettings(SettingsInterface $settings, ?int $channelId, ?str

$actualSettings = $settings->getSettingsByChannelAndLocale(
$channel,
$localeCode
$localeCode,
false,
false
);

$this->removeUnusedSettings($data, $actualSettings);
Expand Down
Loading

0 comments on commit d3d358e

Please sign in to comment.