|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * @author @jayS-de <[email protected]> |
| 4 | + */ |
| 5 | + |
| 6 | +namespace Commercetools\Core\Model\Product; |
| 7 | + |
| 8 | +use Commercetools\Core\Error\InvalidArgumentException; |
| 9 | +use Commercetools\Core\Error\Message; |
| 10 | +use Commercetools\Core\Model\Common\Collection; |
| 11 | +use Commercetools\Core\Model\Common\Context; |
| 12 | + |
| 13 | +/** |
| 14 | + * @package Commercetools\Core\Model\Product |
| 15 | + * @link https://dev.commercetools.com/http-api-projects-products-search.html#representations |
| 16 | + * @method SuggestionCollection current() |
| 17 | + * @method LocalizedSuggestionCollection add(SuggestionCollection $element) |
| 18 | + * @method SuggestionCollection getAt($offset) |
| 19 | + */ |
| 20 | +class LocalizedSuggestionCollection extends Collection |
| 21 | +{ |
| 22 | + protected $type = '\Commercetools\Core\Model\Product\SuggestionCollection'; |
| 23 | + |
| 24 | + /** |
| 25 | + * @param $locale |
| 26 | + * @return SuggestionCollection |
| 27 | + */ |
| 28 | + public function __get($locale) |
| 29 | + { |
| 30 | + $context = new Context(); |
| 31 | + $context->setGraceful($this->getContext()->isGraceful()) |
| 32 | + ->setLanguages([$locale]); |
| 33 | + return $this->get($context); |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * @param Context $context |
| 38 | + * @return string |
| 39 | + */ |
| 40 | + protected function getLanguage(Context $context) |
| 41 | + { |
| 42 | + $locale = null; |
| 43 | + foreach ($context->getLanguages() as $language) { |
| 44 | + if (isset($this[$language])) { |
| 45 | + $locale = $language; |
| 46 | + break; |
| 47 | + } |
| 48 | + } |
| 49 | + return $locale; |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * @param Context $context |
| 54 | + * @return SuggestionCollection |
| 55 | + */ |
| 56 | + public function get(Context $context = null) |
| 57 | + { |
| 58 | + if (is_null($context)) { |
| 59 | + $context = $this->getContext(); |
| 60 | + } |
| 61 | + $locale = $this->getLanguage($context); |
| 62 | + if (!isset($this[$locale])) { |
| 63 | + if (!$context->isGraceful()) { |
| 64 | + throw new InvalidArgumentException(Message::NO_VALUE_FOR_LOCALE); |
| 65 | + } |
| 66 | + return new SuggestionCollection(); |
| 67 | + } |
| 68 | + return $this->getAt($locale); |
| 69 | + } |
| 70 | +} |
0 commit comments