ServiceSerializer.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /**
  3. * Refer to LICENSE.txt distributed with the Temando Shipping module for notice of license
  4. */
  5. namespace Temando\Shipping\Model\Checkout\Address;
  6. use Magento\Framework\Api\AttributeInterface;
  7. use Magento\Framework\Api\AttributeInterfaceFactory;
  8. use Magento\Framework\Serialize\SerializerInterface;
  9. /**
  10. * Temando Checkout Address Service Selection Serializer
  11. *
  12. * @package Temando\Shipping\Model
  13. * @author Christoph Aßmann <christoph.assmann@netresearch.de>
  14. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  15. * @link http://www.temando.com/
  16. */
  17. class ServiceSerializer implements SerializerInterface
  18. {
  19. /**
  20. * @var SerializerInterface
  21. */
  22. private $serializer;
  23. /**
  24. * @var AttributeInterfaceFactory
  25. */
  26. private $attributeFactory;
  27. /**
  28. * ServiceSerializer constructor.
  29. * @param SerializerInterface $serializer
  30. * @param AttributeInterfaceFactory $attributeFactory
  31. */
  32. public function __construct(
  33. SerializerInterface $serializer,
  34. AttributeInterfaceFactory $attributeFactory
  35. ) {
  36. $this->serializer = $serializer;
  37. $this->attributeFactory = $attributeFactory;
  38. }
  39. /**
  40. * @param AttributeInterface[] $services
  41. * @return bool|string
  42. */
  43. public function serialize($services)
  44. {
  45. $data = [];
  46. if (is_array($services)) {
  47. foreach ($services as $service) {
  48. $data[$service->getAttributeCode()] = $service->getValue();
  49. }
  50. }
  51. return $this->serializer->serialize($data);
  52. }
  53. /**
  54. * @param string $string
  55. * @return AttributeInterface[]
  56. */
  57. public function unserialize($string)
  58. {
  59. /** @var string[] $data */
  60. $data = $this->serializer->unserialize($string);
  61. if (empty($data) || !is_array($data)) {
  62. return [];
  63. }
  64. array_walk($data, function (&$value, $key) {
  65. /** @var AttributeInterface $attribute */
  66. $attribute = $this->attributeFactory->create();
  67. $attribute->setAttributeCode($key);
  68. $attribute->setValue($value);
  69. // replace plain service value by AttributeInterface
  70. $value = $attribute;
  71. });
  72. /** @var AttributeInterface[] $services */
  73. $services = $data;
  74. return $services;
  75. }
  76. }