Skip to content

Commit

Permalink
Merge pull request #36 from sherlockode/fix/locale-issue-default-value
Browse files Browse the repository at this point in the history
Fix resource label if default locale is not set
  • Loading branch information
Vowow authored Mar 8, 2023
2 parents ae752ef + 8ae2589 commit b02b7d4
Showing 1 changed file with 49 additions and 3 deletions.
52 changes: 49 additions & 3 deletions src/Twig/TreeRuntime.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
namespace Sherlockode\SyliusFAQPlugin\Twig;

use Sherlockode\SyliusFAQPlugin\Entity\Category;
use Sherlockode\SyliusFAQPlugin\Entity\CategoryTranslation;
use Sherlockode\SyliusFAQPlugin\Entity\Question;
use Sherlockode\SyliusFAQPlugin\Entity\QuestionTranslation;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig\Environment;
use Twig\Extension\RuntimeExtensionInterface;
Expand Down Expand Up @@ -42,7 +45,7 @@ public function generateTree(iterable $categories): string
foreach ($categories as $category) {
$tree[$id] = [
'id' => 'category_' . $category->getId(),
'title' => $category->getName(),
'title' => $this->getDefaultLabel($category),
'parent_id' => 0,
'level' => 1,
'min_level' => 1,
Expand All @@ -61,7 +64,7 @@ public function generateTree(iterable $categories): string

$tree[$id] = [
'id' => 'question_' . $question->getId(),
'title' => $question->getQuestion(),
'title' => $this->getDefaultLabel($category),
'parent_id' => 'category_' . $category->getId(),
'level' => 2,
'min_level' => 2,
Expand All @@ -86,13 +89,56 @@ public function generateTree(iterable $categories): string
*
* @return array
*/
private function getLocaleCodes(iterable $translations) {
private function getLocaleCodes(iterable $translations): array
{
$codes = [];

foreach ($translations as $translation) {
if ($translation instanceof CategoryTranslation && null === $translation->getName()) {
continue;
}

if ($translation instanceof QuestionTranslation && null === $translation->getQuestion()) {
continue;
}

$codes[] = strtolower(substr(strrchr($translation->getLocale(), '_'), 1));
}

return $codes;
}

/**
* @param $resource
*
* @return string|null
*/
private function getDefaultLabel($resource): ?string
{
$label = null;

if ($resource instanceof Category) {
$label = $resource->getName();

if (null === $label) {
$translation = $resource->getTranslations()->first();
if (false !== $translation) {
$label = $translation->getName();
}
}
}

if ($resource instanceof Question) {
$label = $resource->getQuestion();

if (null === $label) {
$translation = $resource->getTranslations()->first();
if (false !== $translation) {
$label = $translation->getQuestion();
}
}
}

return $label;
}
}

0 comments on commit b02b7d4

Please sign in to comment.