Skip to content

Commit

Permalink
feat: translate tags
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolocarpignoli committed May 16, 2024
1 parent 6afc3fa commit 0b6f8ad
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
30 changes: 28 additions & 2 deletions src/Controller/Component/TagsComponent.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

use BEdita\Core\Model\Entity\Tag;
use BEdita\Core\Model\Table\TagsTable;
use BEdita\I18n\Core\I18nTrait;
use Cake\Collection\CollectionInterface;
use Cake\Controller\Component;
use Cake\Database\Expression\QueryExpression;
Expand All @@ -19,6 +20,7 @@
*/
class TagsComponent extends Component
{
use I18nTrait;
use LocatorAwareTrait;

/**
Expand Down Expand Up @@ -50,19 +52,43 @@ public function initialize(array $config): void
*/
public function load(): Query
{
$lang ??= $this->getLang();

return $this->Tags->find()
->where([$this->Tags->aliasField('enabled') => true])
->order([$this->Tags->aliasField('name')])
->formatResults(function (CollectionInterface $results): CollectionInterface {
return $results->map(function (Tag $tag): Tag {
->formatResults(function (CollectionInterface $results) use ($lang): CollectionInterface {
return $results->map(function (Tag $tag) use ($lang): Tag {
$tag->set('slug', Text::slug($tag->name));
$tag = $this->dangerouslyTranslateLabel($tag, $lang);

$tag->clean();

return $tag;
});
});
}

/**
* Dangerous processor to set label to its translation.
*
* **WARNING**: do NOT save entities that have been processed by this processor.
*
* @param \BEdita\Core\Model\Entity\Tag $tag Tag entity to process.
* @param string|null $lang Language code to use.
* @return \BEdita\Core\Model\Entity\Tag
*/
protected function dangerouslyTranslateLabel(Tag $tag, string|null $lang = null): Tag
{
if ($lang === null || !array_key_exists($lang, $tag->get('labels'))) {
return $tag;
}

$tag->label = $tag->get('labels')[$lang];

return $tag;
}

/**
* Build tags subquery for filtering.
*
Expand Down
10 changes: 10 additions & 0 deletions src/Model/ObjectsLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,16 @@ protected function dangerouslyTranslateFields(ObjectEntity $object, string|null
unset($category);
}

if (!empty($object->get('tags'))) {
foreach ($object->get('tags') as &$tag) {
/** @type \BEdita\Core\Model\Entity\Tag $tag */
if (array_key_exists($lang, $tag->get('labels'))) {
$tag->label = $tag->get('labels')[$lang];
}
}
unset($tag);
}

/** @var \BEdita\Core\Model\Entity\Translation|null $requestedTranslation */
$requestedTranslation = collection($object->translations ?? [])
->filter(fn (Translation $tr): bool => $tr->lang === $lang)
Expand Down

0 comments on commit 0b6f8ad

Please sign in to comment.