ExtractIteratorTest.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Collection\Iterator;
  16. use ArrayObject;
  17. use Cake\Collection\Iterator\ExtractIterator;
  18. use Cake\TestSuite\TestCase;
  19. /**
  20. * ExtractIterator Test
  21. *
  22. */
  23. class ExtractIteratorTest extends TestCase
  24. {
  25. /**
  26. * Tests it is possible to extract a column in the first level of an array
  27. *
  28. * @return void
  29. */
  30. public function testExtractFromArrayShallow()
  31. {
  32. $items = [
  33. ['a' => 1, 'b' => 2],
  34. ['a' => 3, 'b' => 4]
  35. ];
  36. $extractor = new ExtractIterator($items, 'a');
  37. $this->assertEquals([1, 3], iterator_to_array($extractor));
  38. $extractor = new ExtractIterator($items, 'b');
  39. $this->assertEquals([2, 4], iterator_to_array($extractor));
  40. $extractor = new ExtractIterator($items, 'c');
  41. $this->assertEquals([null, null], iterator_to_array($extractor));
  42. }
  43. /**
  44. * Tests it is possible to extract a column in the first level of an object
  45. *
  46. * @return void
  47. */
  48. public function testExtractFromObjectShallow()
  49. {
  50. $items = [
  51. new ArrayObject(['a' => 1, 'b' => 2]),
  52. new ArrayObject(['a' => 3, 'b' => 4])
  53. ];
  54. $extractor = new ExtractIterator($items, 'a');
  55. $this->assertEquals([1, 3], iterator_to_array($extractor));
  56. $extractor = new ExtractIterator($items, 'b');
  57. $this->assertEquals([2, 4], iterator_to_array($extractor));
  58. $extractor = new ExtractIterator($items, 'c');
  59. $this->assertEquals([null, null], iterator_to_array($extractor));
  60. }
  61. /**
  62. * Tests it is possible to extract a column deeply nested in the structure
  63. *
  64. * @return void
  65. */
  66. public function testExtractFromArrayDeep()
  67. {
  68. $items = [
  69. ['a' => ['b' => ['c' => 10]], 'b' => 2],
  70. ['a' => ['b' => ['d' => 15]], 'b' => 4],
  71. ['a' => ['x' => ['z' => 20]], 'b' => 4],
  72. ['a' => ['b' => ['c' => 25]], 'b' => 2],
  73. ];
  74. $extractor = new ExtractIterator($items, 'a.b.c');
  75. $this->assertEquals([10, null, null, 25], iterator_to_array($extractor));
  76. }
  77. }