Skip to content

Commit b02b7d4

Browse files
authored
Merge pull request #36 from sherlockode/fix/locale-issue-default-value
Fix resource label if default locale is not set
2 parents ae752ef + 8ae2589 commit b02b7d4

1 file changed

Lines changed: 49 additions & 3 deletions

File tree

src/Twig/TreeRuntime.php

Lines changed: 49 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
namespace Sherlockode\SyliusFAQPlugin\Twig;
44

55
use Sherlockode\SyliusFAQPlugin\Entity\Category;
6+
use Sherlockode\SyliusFAQPlugin\Entity\CategoryTranslation;
7+
use Sherlockode\SyliusFAQPlugin\Entity\Question;
8+
use Sherlockode\SyliusFAQPlugin\Entity\QuestionTranslation;
69
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
710
use Twig\Environment;
811
use Twig\Extension\RuntimeExtensionInterface;
@@ -42,7 +45,7 @@ public function generateTree(iterable $categories): string
4245
foreach ($categories as $category) {
4346
$tree[$id] = [
4447
'id' => 'category_' . $category->getId(),
45-
'title' => $category->getName(),
48+
'title' => $this->getDefaultLabel($category),
4649
'parent_id' => 0,
4750
'level' => 1,
4851
'min_level' => 1,
@@ -61,7 +64,7 @@ public function generateTree(iterable $categories): string
6164

6265
$tree[$id] = [
6366
'id' => 'question_' . $question->getId(),
64-
'title' => $question->getQuestion(),
67+
'title' => $this->getDefaultLabel($category),
6568
'parent_id' => 'category_' . $category->getId(),
6669
'level' => 2,
6770
'min_level' => 2,
@@ -86,13 +89,56 @@ public function generateTree(iterable $categories): string
8689
*
8790
* @return array
8891
*/
89-
private function getLocaleCodes(iterable $translations) {
92+
private function getLocaleCodes(iterable $translations): array
93+
{
9094
$codes = [];
9195

9296
foreach ($translations as $translation) {
97+
if ($translation instanceof CategoryTranslation && null === $translation->getName()) {
98+
continue;
99+
}
100+
101+
if ($translation instanceof QuestionTranslation && null === $translation->getQuestion()) {
102+
continue;
103+
}
104+
93105
$codes[] = strtolower(substr(strrchr($translation->getLocale(), '_'), 1));
94106
}
95107

96108
return $codes;
97109
}
110+
111+
/**
112+
* @param $resource
113+
*
114+
* @return string|null
115+
*/
116+
private function getDefaultLabel($resource): ?string
117+
{
118+
$label = null;
119+
120+
if ($resource instanceof Category) {
121+
$label = $resource->getName();
122+
123+
if (null === $label) {
124+
$translation = $resource->getTranslations()->first();
125+
if (false !== $translation) {
126+
$label = $translation->getName();
127+
}
128+
}
129+
}
130+
131+
if ($resource instanceof Question) {
132+
$label = $resource->getQuestion();
133+
134+
if (null === $label) {
135+
$translation = $resource->getTranslations()->first();
136+
if (false !== $translation) {
137+
$label = $translation->getQuestion();
138+
}
139+
}
140+
}
141+
142+
return $label;
143+
}
98144
}

0 commit comments

Comments
 (0)