ConvertArrayTest.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Convert\Test\Unit;
  7. use \Magento\Framework\Convert\ConvertArray;
  8. class ConvertArrayTest extends \PHPUnit\Framework\TestCase
  9. {
  10. /**
  11. * @var ConvertArray
  12. */
  13. protected $_model;
  14. protected function setUp()
  15. {
  16. $this->_model = new ConvertArray();
  17. }
  18. public function testAssocToXml()
  19. {
  20. $data = ['one' => 1, 'two' => ['three' => 3, 'four' => '4']];
  21. $result = $this->_model->assocToXml($data);
  22. $expectedResult = <<<XML
  23. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  24. <_><one>1</one><two><three>3</three><four>4</four></two></_>
  25. XML;
  26. $this->assertInstanceOf('SimpleXMLElement', $result);
  27. $this->assertEquals($expectedResult, $result->asXML());
  28. }
  29. /**
  30. * @expectedException \Exception
  31. * @expectedExceptionMessage Associative and numeric keys can't be mixed at one level. Verify and try again.
  32. */
  33. public function testAssocToXmlExceptionByKey()
  34. {
  35. $data = [
  36. 'one' => [
  37. 100,
  38. 'two' => 'three',
  39. ],
  40. ];
  41. $this->_model->assocToXml($data);
  42. }
  43. /**
  44. * @param array $array
  45. * @param string $rootName
  46. * @expectedException \Magento\Framework\Exception\LocalizedException
  47. * @dataProvider assocToXmlExceptionDataProvider
  48. */
  49. public function testAssocToXmlException($array, $rootName = '_')
  50. {
  51. $this->_model->assocToXml($array, $rootName);
  52. }
  53. public function testToFlatArray()
  54. {
  55. $input = [
  56. 'key1' => 'value1',
  57. 'key2' => ['key21' => 'value21', 'key22' => 'value22', 'key23' => ['key231' => 'value231']],
  58. 'key3' => ['key31' => 'value31', 'key3' => 'value3'],
  59. 'key4' => ['key4' => 'value4'],
  60. ];
  61. $expectedOutput = [
  62. 'key1' => 'value1',
  63. 'key21' => 'value21',
  64. 'key22' => 'value22',
  65. 'key231' => 'value231',
  66. 'key31' => 'value31',
  67. 'key3' => 'value3',
  68. 'key4' => 'value4',
  69. ];
  70. $output = ConvertArray::toFlatArray($input);
  71. $this->assertEquals($expectedOutput, $output, 'Array is converted to flat structure incorrectly.');
  72. }
  73. /**
  74. * @return array
  75. */
  76. public function assocToXmlExceptionDataProvider()
  77. {
  78. return [[[], ''], [[], 0], [[1, 2, 3]], [['root' => 1], 'root']];
  79. }
  80. }