Skip to content

♻️ 💥 Integrate translation behavior #3561

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions UPGRADING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# From Bolt 5.2

## Drop knplabs/doctrine-behaviors dependency

The `knplabs/doctrine-behaviors` package has been removed from the Bolt core.

The translation behavior has been integrated.

Namespace changes:

| Old class | New class |
|----------------------------------------------------------------------|------------------------------------------------------|
| Knp\DoctrineBehaviors\Contract\Entity\TranslatableInterface | Bolt\Entity\TranslatableInterface |
| Knp\DoctrineBehaviors\Contract\Entity\TranslationInterface | Bolt\Entity\TranslationInterface |
| Knp\DoctrineBehaviors\Model\Translatable\TranslatableTrait | Use two trait below |
| Knp\DoctrineBehaviors\Model\Translatable\TranslatableMethodsTrait | Bolt\Entity\Translatable\TranslatableMethodsTrait |
| Knp\DoctrineBehaviors\Model\Translatable\TranslatablePropertiesTrait | Bolt\Entity\Translatable\TranslatablePropertiesTrait |
| Knp\DoctrineBehaviors\Model\Translatable\TranslationTrait | Use two trait below |
| Knp\DoctrineBehaviors\Model\Translatable\TranslationMethodsTrait | Bolt\Entity\Translatable\TranslationMethodsTrait |
| Knp\DoctrineBehaviors\Model\Translatable\TranslationPropertiesTrait | Bolt\Entity\Translatable\TranslationPropertiesTrait |
| Knp\DoctrineBehaviors\EventSubscriber\TranslatableEventSubscriber | Bolt\Event\Listener\TranslatableListener |
| Knp\DoctrineBehaviors\Exception\TranslatableException | Bolt\Exception\TranslatableException |
| Knp\DoctrineBehaviors\Provider\LocaleProvider | Bolt\Locale\LocaleProvider |
| Knp\DoctrineBehaviors\Contract\Provider\LocaleProviderInterface | Bolt\Locale\LocaleProviderInterface |
1 change: 0 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
"erusev/parsedown-extra": "^0.8.1",
"fakerphp/faker": "^1.16",
"jasny/twig-extensions": "^1.3",
"knplabs/doctrine-behaviors": "^2.1",
"knplabs/knp-menu-bundle": "^3.1",
"league/glide-symfony": "^1.0.4",
"miljar/php-exif": "^0.6.4",
Expand Down
1 change: 0 additions & 1 deletion config/bundles.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle::class => ['all' => true],
Http\HttplugBundle\HttplugBundle::class => ['dev' => true, 'local' => true],
Knp\Bundle\MenuBundle\KnpMenuBundle::class => ['all' => true],
Knp\DoctrineBehaviors\DoctrineBehaviorsBundle::class => ['all' => true],
Nelmio\CorsBundle\NelmioCorsBundle::class => ['all' => true],
Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle::class => ['all' => true],
Symfony\Bundle\DebugBundle\DebugBundle::class => ['all' => true],
Expand Down
10 changes: 10 additions & 0 deletions config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ parameters:
# foo_manager: foo_
bolt.backend_url: /bolt
bolt.remember_lifetime: 2592000 # 30 days in seconds
bolt.doctrine_behaviors_translatable_fetch_mode: LAZY
bolt.doctrine_behaviors_translation_fetch_mode: LAZY

services:
# default configuration for services in *this* file
Expand All @@ -31,6 +33,8 @@ services:
$tablePrefix: '%bolt.table_prefix%'
$backendUrl: '%bolt.backend_url%'
$rememberLifetime: '%bolt.remember_lifetime%'
$translatableFetchMode: '%bolt.doctrine_behaviors_translatable_fetch_mode%'
$translationFetchMode: '%bolt.doctrine_behaviors_translation_fetch_mode%'

_instanceof:
Bolt\Menu\ExtensionBackendMenuInterface:
Expand Down Expand Up @@ -78,6 +82,12 @@ services:
Bolt\Event\Listener\UserAvatarLoadListener:
tags:
- { name: doctrine.event_listener, event: postLoad }

Bolt\Event\Listener\TranslatableListener:
tags:
- { name: doctrine.event_listener, event: loadClassMetadata }
- { name: doctrine.event_listener, event: postLoad }
- { name: doctrine.event_listener, event: prePersist }

Bolt\Extension\RoutesLoader:
tags: [routing.loader]
Expand Down
5 changes: 0 additions & 5 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,6 @@ parameters:
message: '#Unreachable statement - code above always terminates#'
path: %currentWorkingDirectory%/src/*

# false positive: `TranslationInterface does not know about FieldTranslation::getValue().` Skip this error.
-
message: '#Call to an undefined method Knp\\DoctrineBehaviors\\Contract\\Entity\\TranslationInterface#'
path: %currentWorkingDirectory%/src/*

# false positive: Parameters in Storage\Directive\OrderDirective::orderByNumericField() aren't seen as integers
-
message: '#of method Doctrine\\ORM\\Query\\Expr::substring\(\) expects int#'
Expand Down
80 changes: 49 additions & 31 deletions src/DataFixtures/ContentFixtures.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Bolt\Entity\Content;
use Bolt\Entity\Field;
use Bolt\Entity\Field\SelectField;
use Bolt\Entity\FieldTranslation;
use Bolt\Enum\Statuses;
use Bolt\Repository\FieldRepository;
use Bolt\Twig\ContentExtension;
Expand Down Expand Up @@ -49,12 +50,17 @@ class ContentFixtures extends BaseFixture implements DependentFixtureInterface,
/** @var ContentExtension */
private $contentExtension;

public function __construct(Config $config, FileLocations $fileLocations, TagAwareCacheInterface $cache, string $defaultLocale, ContentExtension $contentExtension)
{
public function __construct(
Config $config,
FileLocations $fileLocations,
TagAwareCacheInterface $cache,
string $defaultLocale,
ContentExtension $contentExtension
) {
$this->config = $config;
$this->faker = Factory::create();
$seed = $this->config->get('general/fixtures_seed');
if (! empty($seed)) {
if (!empty($seed)) {
$this->faker->seed($seed);
}

Expand Down Expand Up @@ -103,7 +109,7 @@ private function loadContent(ObjectManager $manager): void
continue;
}

$amount = $contentType['singleton'] ? 1 : (int) ($contentType['listing_records'] * 3);
$amount = $contentType['singleton'] ? 1 : (int)($contentType['listing_records'] * 3);

for ($i = 1; $i <= $amount; $i++) {
if ($i === 1) {
Expand All @@ -124,7 +130,7 @@ private function loadContent(ObjectManager $manager): void

$preset = $this->getPreset($contentType['slug']);

if ($i === 1 || ! empty($preset)) {
if ($i === 1 || !empty($preset)) {
$content->setStatus($preset['status'] ?? Statuses::PUBLISHED);
} else {
$content->setStatus($this->getRandomStatus());
Expand Down Expand Up @@ -180,8 +186,13 @@ private function loadContent(ObjectManager $manager): void
}
}

private function loadCollectionField(Content $content, Field $field, $fieldType, ContentType $contentType, array $preset): Field
{
private function loadCollectionField(
Content $content,
Field $field,
$fieldType,
ContentType $contentType,
array $preset
): Field {
$collectionItems = $field->getDefinition()->get('fields');

$i = 0;
Expand Down Expand Up @@ -211,8 +222,14 @@ private function loadSetField(Content $content, Field $set, ContentType $content
return $set;
}

private function loadField(Content $content, string $name, $fieldType, ContentType $contentType, array $preset, bool $addToContent = true): Field
{
private function loadField(
Content $content,
string $name,
$fieldType,
ContentType $contentType,
array $preset,
bool $addToContent = true
): Field {
$sortorder = 1;

$field = FieldRepository::factory($fieldType, $name);
Expand Down Expand Up @@ -242,7 +259,8 @@ private function loadField(Content $content, string $name, $fieldType, ContentTy
$locales = $contentType['locales']->toArray();
foreach ($locales as $locale) {
if ($locale !== $this->defaultLocale && array_search($locale, $locales, true) !== count($locales) - 1) {
$value = $preset[$name] ?? $this->getValuesforFieldType($fieldType, $contentType['singleton'], $content);
$value = $preset[$name] ?? $this->getValuesforFieldType($fieldType, $contentType['singleton'],
$content);
$field->translate($locale, false)->setValue($value);
}
}
Expand Down Expand Up @@ -273,19 +291,19 @@ private function getFixtureFormatValues(string $format): array
{
return [
preg_replace_callback(
'/{([\w]+)}/i',
function ($match) {
$match = $match[1];
'/{([\w]+)}/i',
function ($match) {
$match = $match[1];

try {
return $this->faker->{$match};
} finally {
}
try {
return $this->faker->{$match};
} finally {
}

return '(unknown)';
},
$format
),
return '(unknown)';
},
$format
),
];
}

Expand Down Expand Up @@ -361,7 +379,7 @@ private function getFieldTypeValue(DeepCollection $field, bool $singleton, Conte

break;
case 'number':
$data = [(string) $this->faker->numberBetween(-100, 1000)];
$data = [(string)$this->faker->numberBetween(-100, 1000)];

break;
case 'checkbox':
Expand Down Expand Up @@ -411,7 +429,7 @@ private function getFieldTypeValue(DeepCollection $field, bool $singleton, Conte
$data = ['selected' => 'latlong', 'zoom' => '7', 'search' => ''];
$coordinates = $this->faker->localCoordinates();
$data['lat'] = $coordinates['latitude'];
$data['long'] =$coordinates['longitude'];
$data['long'] = $coordinates['longitude'];
$data = [json_encode($data)];


Expand Down Expand Up @@ -534,7 +552,7 @@ private function getPresetRecords(): array

private function getPreset(string $slug): array
{
if (isset($this->presetRecords[$slug]) && ! empty($this->presetRecords[$slug]) && ! $this->getOption('--append')) {
if (isset($this->presetRecords[$slug]) && !empty($this->presetRecords[$slug]) && !$this->getOption('--append')) {
$preset = array_shift($this->presetRecords[$slug]);
} else {
$preset = [];
Expand All @@ -552,14 +570,14 @@ private function setSelectFieldsMappedWithContent(ObjectManager $manager): void
$contentDefaultLocale = $content->getDefaultLocale();
$contentLocales = $content->getLocales();
foreach ($content->getFields() as $field) {
if (! $this->isSelectFieldAndMappedWithContent($field)) {
if (!$this->isSelectFieldAndMappedWithContent($field)) {
continue;
}

/** @var SelectField $field */
$contentType = $field->getContentType();

if (! \is_string($contentType)) {
if (!\is_string($contentType)) {
continue;
}

Expand Down Expand Up @@ -590,14 +608,14 @@ private function setSelectFieldsMappedWithContent(ObjectManager $manager): void

private function isSelectFieldAndMappedWithContent(Field $field): bool
{
if (! $field instanceof SelectField) {
return FALSE;
if (!$field instanceof SelectField) {
return false;
}

if (! $field->isContentSelect()) {
return FALSE;
if (!$field->isContentSelect()) {
return false;
}

return TRUE;
return true;
}
}
9 changes: 6 additions & 3 deletions src/Entity/Field.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter;
use Bolt\Common\Arr;
use Bolt\Configuration\Content\FieldType;
use Bolt\Entity\Translatable\TranslatableMethodsTrait;
use Bolt\Entity\Translatable\TranslatablePropertiesTrait;
use Bolt\Event\Listener\FieldFillListener;
use Bolt\Utils\Sanitiser;
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Contract\Entity\TranslatableInterface;
use Knp\DoctrineBehaviors\Model\Translatable\TranslatableTrait;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Serializer\Annotation\SerializedName;
use Tightenco\Collect\Support\Collection;
Expand Down Expand Up @@ -53,10 +53,13 @@
* @ORM\InheritanceType("SINGLE_TABLE")
* @ORM\DiscriminatorColumn(name="type", type="string", length=191)
* @ORM\DiscriminatorMap({"generic" = "Field"})
*
* @method FieldTranslation translate(?string $locale = null, bool $fallbackToDefault = true)
*/
class Field implements FieldInterface, TranslatableInterface
{
use TranslatableTrait;
use TranslatablePropertiesTrait;
use TranslatableMethodsTrait;

public const TYPE = 'generic';

Expand Down
8 changes: 5 additions & 3 deletions src/Entity/FieldTranslation.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,17 @@

namespace Bolt\Entity;

use Bolt\Entity\Translatable\TranslationMethodsTrait;
use Bolt\Entity\Translatable\TranslationPropertiesTrait;
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model\Translatable\TranslationTrait;

/**
* @ORM\Entity
*/
class FieldTranslation implements TranslationInterface
{
use TranslationTrait;
use TranslationPropertiesTrait;
use TranslationMethodsTrait;

/**
* @ORM\Id()
Expand Down Expand Up @@ -59,6 +61,6 @@ public function set(string $key, $value): self
*/
public static function getTranslatableEntityClass(): string
{
return 'Field';
return Field::class;
}
}
Loading