Skip to content

Commit

Permalink
OP-442: Locales functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
jkindly committed Jul 25, 2024
1 parent ecbdd33 commit 80ddc84
Show file tree
Hide file tree
Showing 12 changed files with 113 additions and 44 deletions.
50 changes: 47 additions & 3 deletions spec/Resolver/BlockResourceResolverSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,25 @@
use BitBag\SyliusCmsPlugin\Repository\BlockRepositoryInterface;
use BitBag\SyliusCmsPlugin\Resolver\BlockResourceResolver;
use BitBag\SyliusCmsPlugin\Resolver\BlockResourceResolverInterface;
use Doctrine\Common\Collections\ArrayCollection;
use PhpSpec\ObjectBehavior;
use Psr\Log\LoggerInterface;
use Sylius\Component\Channel\Context\ChannelContextInterface;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Locale\Context\LocaleContextInterface;
use Sylius\Component\Locale\Model\LocaleInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;

final class BlockResourceResolverSpec extends ObjectBehavior
{
public function let(
BlockRepositoryInterface $blockRepository,
LoggerInterface $logger,
ChannelContextInterface $channelContext
ChannelContextInterface $channelContext,
LocaleContextInterface $localeContext,
RepositoryInterface $localeRepository,
) {
$this->beConstructedWith($blockRepository, $logger, $channelContext);
$this->beConstructedWith($blockRepository, $logger, $channelContext, $localeContext, $localeRepository);
}

public function it_is_initializable(): void
Expand Down Expand Up @@ -60,15 +66,53 @@ public function it_logs_warning_if_block_was_not_found(
$this->findOrLog('homepage_banner');
}

public function it_logs_warning_if_block_was_found_but_it_does_not_have_locale(
BlockRepositoryInterface $blockRepository,
LoggerInterface $logger,
ChannelContextInterface $channelContext,
ChannelInterface $channel,
LocaleContextInterface $localeContext,
LocaleInterface $locale,
RepositoryInterface $localeRepository,
BlockInterface $block
) {
$channel->getCode()->willReturn('WEB');
$channelContext->getChannel()->willReturn($channel);
$blockRepository->findEnabledByCode('homepage_banner', 'WEB')->willReturn($block);
$localeContext->getLocaleCode()->willReturn('en_US');
$locale->getCode()->willReturn('en_US');
$localeRepository->findOneBy(['code' => 'en_US'])->willReturn($locale);
$block->hasLocale($locale)->willReturn(false);
$block->getLocales()->willReturn(new ArrayCollection(['pl_PL']));

$logger
->warning(sprintf(
'Block with "%s" code was found in the database, but it does not have "%s" locale.',
'homepage_banner',
'en_US'
))
->shouldBeCalled()
;

$this->findOrLog('homepage_banner');
}

public function it_returns_block_if_found_in_database(
BlockRepositoryInterface $blockRepository,
BlockInterface $block,
ChannelContextInterface $channelContext,
ChannelInterface $channel
ChannelInterface $channel,
LocaleContextInterface $localeContext,
LocaleInterface $locale,
RepositoryInterface $localeRepository,
) {
$channel->getCode()->willReturn('WEB');
$channelContext->getChannel()->willReturn($channel);
$blockRepository->findEnabledByCode('homepage_banner', 'WEB')->willReturn($block);
$localeContext->getLocaleCode()->willReturn('en_US');
$locale->getCode()->willReturn('en_US');
$localeRepository->findOneBy(['code' => 'en_US'])->willReturn($locale);
$block->hasLocale($locale)->willReturn(true);

$this->findOrLog('homepage_banner')->shouldReturn($block);
}
Expand Down
3 changes: 0 additions & 3 deletions src/Entity/Page.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
use BitBag\SyliusCmsPlugin\Entity\Trait\ChannelsAwareTrait;
use BitBag\SyliusCmsPlugin\Entity\Trait\CollectibleTrait;
use BitBag\SyliusCmsPlugin\Entity\Trait\ContentConfigurationAwareTrait;
use BitBag\SyliusCmsPlugin\Entity\Trait\LocaleAwareTrait;
use Sylius\Component\Resource\Model\TimestampableTrait;
use Sylius\Component\Resource\Model\ToggleableTrait;
use Sylius\Component\Resource\Model\TranslatableTrait;
Expand All @@ -26,7 +25,6 @@ class Page implements PageInterface
use TimestampableTrait;
use ChannelsAwareTrait;
use ContentConfigurationAwareTrait;
use LocaleAwareTrait;
use TranslatableTrait {
__construct as protected initializeTranslationsCollection;
}
Expand All @@ -45,7 +43,6 @@ public function __construct()
$this->initializeChannelsCollection();
$this->initializeTranslationsCollection();
$this->initializeContentElementsCollection();
$this->initializeLocalesCollection();

$this->createdAt = new \DateTime();
}
Expand Down
3 changes: 1 addition & 2 deletions src/Entity/PageInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ interface PageInterface extends
TimestampableInterface,
ChannelsAwareInterface,
SlugAwareInterface,
ContentConfigurationAwareInterface,
LocaleAwareInterface
ContentConfigurationAwareInterface
{
public function getCode(): ?string;

Expand Down
1 change: 0 additions & 1 deletion src/Form/Type/PageType.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ public function buildForm(FormBuilderInterface $builder, array $options): void
'time_widget' => 'single_text',
'required' => false,
])
->add('locales')
->add('contentElements', CollectionType::class, [
'label' => false,
'entry_type' => ContentConfigurationType::class,
Expand Down
30 changes: 30 additions & 0 deletions src/Migrations/Version20240725064430.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

namespace BitBag\SyliusCmsPlugin\Migrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

final class Version20240725064430 extends AbstractMigration
{
public function getDescription(): string
{
return 'This migration remove locales from pages.';
}

public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE bitbag_cms_page_locales DROP FOREIGN KEY FK_EF20FD23C4663E4');
$this->addSql('ALTER TABLE bitbag_cms_page_locales DROP FOREIGN KEY FK_EF20FD23E559DFD1');
$this->addSql('DROP TABLE bitbag_cms_page_locales');
}

public function down(Schema $schema): void
{
$this->addSql('CREATE TABLE bitbag_cms_page_locales (page_id INT NOT NULL, locale_id INT NOT NULL, INDEX IDX_EF20FD23E559DFD1 (locale_id), INDEX IDX_EF20FD23C4663E4 (page_id), PRIMARY KEY(page_id, locale_id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB COMMENT = \'\' ');
$this->addSql('ALTER TABLE bitbag_cms_page_locales ADD CONSTRAINT FK_EF20FD23C4663E4 FOREIGN KEY (page_id) REFERENCES bitbag_cms_page (id) ON DELETE CASCADE');
$this->addSql('ALTER TABLE bitbag_cms_page_locales ADD CONSTRAINT FK_EF20FD23E559DFD1 FOREIGN KEY (locale_id) REFERENCES sylius_locale (id) ON DELETE CASCADE');
}
}
19 changes: 19 additions & 0 deletions src/Resolver/BlockResourceResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
use BitBag\SyliusCmsPlugin\Repository\BlockRepositoryInterface;
use Psr\Log\LoggerInterface;
use Sylius\Component\Channel\Context\ChannelContextInterface;
use Sylius\Component\Locale\Context\LocaleContextInterface;
use Sylius\Component\Locale\Model\LocaleInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Webmozart\Assert\Assert;

final class BlockResourceResolver implements BlockResourceResolverInterface
Expand All @@ -22,6 +25,8 @@ public function __construct(
private BlockRepositoryInterface $blockRepository,
private LoggerInterface $logger,
private ChannelContextInterface $channelContext,
private LocaleContextInterface $localeContext,
private RepositoryInterface $localeRepository,
) {
}

Expand All @@ -40,6 +45,20 @@ public function findOrLog(string $code): ?BlockInterface
return null;
}

/** @var LocaleInterface $locale */
$locale = $this->localeRepository->findOneBy(['code' => $this->localeContext->getLocaleCode()]);
Assert::notNull($locale);

if (false === $block->hasLocale($locale) && 0 !== $block->getLocales()->count()) {
$this->logger->warning(sprintf(
'Block with "%s" code was found in the database, but it does not have "%s" locale.',
$code,
$this->localeContext->getLocaleCode(),
));

return null;
}

return $block;
}
}
30 changes: 14 additions & 16 deletions src/Resources/assets/admin/js/bitbag/bitbag-page-slug.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@ export class HandleSlugUpdate {
wrappersIndicator: 'data-bb-cms-wrapper',
lockFieldIndicator: 'data-bb-cms-toggle-slug',
bbTarget: 'bitbag_sylius_cms_plugin_page',
nameField: 'bitbag_sylius_cms_plugin_page_name',
}
) {
this.wrappers = document.querySelectorAll(`[${config.wrappersIndicator}]`);
this.lockFieldIndicator = `[${config.lockFieldIndicator}]`;
this.bbTarget = config.bbTarget;
this.config = config;
this.nameField = document.getElementById(`${config.nameField}`);
}

init() {
Expand All @@ -29,44 +31,40 @@ export class HandleSlugUpdate {
throw new Error('Bitbag CMS Plugin - HandleSlugUpdate class config key values are not valid strings');
}

if (!this.nameField ) {
throw new Error('Bitbag CMS Plugin - HandleSlugUpdate name field not found');
}

this._handleFields();
}

_handleFields() {
this.wrappers.forEach((item) => {
const locale = item.dataset.locale;

let textField = item.querySelector(`#${this.bbTarget}_translations_${locale}_name`);
if (!textField) {
textField = item.querySelector(`#${this.bbTarget}_name`);
}

let slugField = item.querySelector(`#${this.bbTarget}_translations_${locale}_slug`);
if (!slugField) {
slugField = item.querySelector(`#${this.bbTarget}_slug`);
}

const lockField = item.querySelector(this.lockFieldIndicator);

if (!textField || !slugField) {
if (!slugField) {
return;
}

let timeout;

textField.addEventListener('input', (e) => {
this.nameField.addEventListener('input', (e) => {
e.preventDefault();

if (slugField.readOnly) {
return;
if (!slugField.readOnly) {
clearTimeout(timeout);
timeout = setTimeout(() => {
this._updateSlug(slugField, this.nameField.value);
}, 1000);
}

clearTimeout(timeout);
timeout = setTimeout(() => {
this._updateSlug(slugField, textField.value);
}, 1000);
});

const lockField = item.querySelector(this.lockFieldIndicator);
if (!lockField) {
return;
}
Expand Down
11 changes: 0 additions & 11 deletions src/Resources/config/doctrine/Page.orm.xml
Original file line number Diff line number Diff line change
Expand Up @@ -58,16 +58,5 @@
</order-by>
</one-to-many>

<many-to-many field="locales" target-entity="Sylius\Component\Locale\Model\LocaleInterface">
<join-table name="bitbag_cms_page_locales">
<join-columns>
<join-column name="page_id" referenced-column-name="id" nullable="false" on-delete="CASCADE" />
</join-columns>
<inverse-join-columns>
<join-column name="locale_id" referenced-column-name="id" nullable="false" on-delete="CASCADE" />
</inverse-join-columns>
</join-table>
</many-to-many>

</mapped-superclass>
</doctrine-mapping>
2 changes: 2 additions & 0 deletions src/Resources/config/services/resolver.xml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
<argument type="service" id="bitbag_sylius_cms_plugin.repository.block" />
<argument type="service" id="logger" />
<argument type="service" id="sylius.context.channel" />
<argument type="service" id="sylius.context.locale" />
<argument type="service" id="sylius.repository.locale" />
</service>

<service id="bitbag_sylius_cms_plugin.resolver.collection_resource" class="BitBag\SyliusCmsPlugin\Resolver\CollectionResourceResolver" public="true">
Expand Down
6 changes: 0 additions & 6 deletions src/Resources/config/validation/PageTranslation.xml
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,6 @@
</constraint>

<property name="slug">
<constraint name="NotBlank">
<option name="message">bitbag_sylius_cms_plugin.page.slug.not_blank</option>
<option name="groups">
<value>bitbag</value>
</option>
</constraint>
<constraint name="Length">
<option name="min">2</option>
<option name="max">250</option>
Expand Down
1 change: 0 additions & 1 deletion src/Resources/views/Page/Crud/_form.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
{{ form_row(form.code) }}
{{ form_row(form.enabled) }}
{{ form_row(form.channels) }}
{{ form_row(form.locales) }}
{{ form_row(form.collections) }}
{{ form_row(form.publishAt) }}
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@

<div class="ui large stackable menu">
{{ render(url('sylius_shop_partial_taxon_index_by_code', {'code': 'category', 'template': '@SyliusShop/Taxon/_horizontalMenu.html.twig'})) }}
{{ render(path('bitbag_sylius_cms_plugin_shop_page_show_link_by_code', {'code' : 'about', 'template' : '@BitBagSyliusCmsPlugin/Shop/Page/Show/_link.html.twig'})) }}
<a href="{{ path('bitbag_sylius_cms_plugin_shop_page_index_by_collection_code', {'collectionCode' : 'blog'}) }}"
class="item">
Blog
Expand Down

0 comments on commit 80ddc84

Please sign in to comment.