blob: c6555782fdb70e1131308dfbd76bf18cb37de950 [file] [log] [blame]
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +02001<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\Translation;
13
14use Symfony\Component\Translation\Catalogue\AbstractOperation;
15use Symfony\Component\Translation\Catalogue\TargetOperation;
16
17final class TranslatorBag implements TranslatorBagInterface
18{
19 /** @var MessageCatalogue[] */
20 private $catalogues = [];
21
22 public function addCatalogue(MessageCatalogue $catalogue): void
23 {
24 if (null !== $existingCatalogue = $this->getCatalogue($catalogue->getLocale())) {
25 $catalogue->addCatalogue($existingCatalogue);
26 }
27
28 $this->catalogues[$catalogue->getLocale()] = $catalogue;
29 }
30
31 public function addBag(TranslatorBagInterface $bag): void
32 {
33 foreach ($bag->getCatalogues() as $catalogue) {
34 $this->addCatalogue($catalogue);
35 }
36 }
37
38 /**
39 * {@inheritdoc}
40 */
41 public function getCatalogue(string $locale = null)
42 {
43 if (null === $locale || !isset($this->catalogues[$locale])) {
44 $this->catalogues[$locale] = new MessageCatalogue($locale);
45 }
46
47 return $this->catalogues[$locale];
48 }
49
50 /**
51 * {@inheritdoc}
52 */
53 public function getCatalogues(): array
54 {
55 return array_values($this->catalogues);
56 }
57
58 public function diff(TranslatorBagInterface $diffBag): self
59 {
60 $diff = new self();
61
62 foreach ($this->catalogues as $locale => $catalogue) {
63 if (null === $diffCatalogue = $diffBag->getCatalogue($locale)) {
64 $diff->addCatalogue($catalogue);
65
66 continue;
67 }
68
69 $operation = new TargetOperation($diffCatalogue, $catalogue);
70 $operation->moveMessagesToIntlDomainsIfPossible(AbstractOperation::NEW_BATCH);
71 $newCatalogue = new MessageCatalogue($locale);
72
73 foreach ($operation->getDomains() as $domain) {
74 $newCatalogue->add($operation->getNewMessages($domain), $domain);
75 }
76
77 $diff->addCatalogue($newCatalogue);
78 }
79
80 return $diff;
81 }
82
83 public function intersect(TranslatorBagInterface $intersectBag): self
84 {
85 $diff = new self();
86
87 foreach ($this->catalogues as $locale => $catalogue) {
88 if (null === $intersectCatalogue = $intersectBag->getCatalogue($locale)) {
89 continue;
90 }
91
92 $operation = new TargetOperation($catalogue, $intersectCatalogue);
93 $operation->moveMessagesToIntlDomainsIfPossible(AbstractOperation::OBSOLETE_BATCH);
94 $obsoleteCatalogue = new MessageCatalogue($locale);
95
96 foreach ($operation->getDomains() as $domain) {
97 $obsoleteCatalogue->add($operation->getObsoleteMessages($domain), $domain);
98 }
99
100 $diff->addCatalogue($obsoleteCatalogue);
101 }
102
103 return $diff;
104 }
105}