ExtractIteratorTest.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. * Tests it is possible to extract a column in the first level of an array
  26. *
  27. * @return void
  28. */
  29. public function testExtractFromArrayShallow() {
  30. $items = [
  31. ['a' => 1, 'b' => 2],
  32. ['a' => 3, 'b' => 4]
  33. ];
  34. $extractor = new ExtractIterator($items, 'a');
  35. $this->assertEquals([1, 3], iterator_to_array($extractor));
  36. $extractor = new ExtractIterator($items, 'b');
  37. $this->assertEquals([2, 4], iterator_to_array($extractor));
  38. $extractor = new ExtractIterator($items, 'c');
  39. $this->assertEquals([null, null], iterator_to_array($extractor));
  40. }
  41. /**
  42. * Tests it is possible to extract a column in the first level of an object
  43. *
  44. * @return void
  45. */
  46. public function testExtractFromObjectShallow() {
  47. $items = [
  48. new ArrayObject(['a' => 1, 'b' => 2]),
  49. new ArrayObject(['a' => 3, 'b' => 4])
  50. ];
  51. $extractor = new ExtractIterator($items, 'a');
  52. $this->assertEquals([1, 3], iterator_to_array($extractor));
  53. $extractor = new ExtractIterator($items, 'b');
  54. $this->assertEquals([2, 4], iterator_to_array($extractor));
  55. $extractor = new ExtractIterator($items, 'c');
  56. $this->assertEquals([null, null], iterator_to_array($extractor));
  57. }
  58. /**
  59. * Tests it is possible to extract a column deeply nested in the structure
  60. *
  61. * @return void
  62. */
  63. public function testExtractFromArrayDeep() {
  64. $items = [
  65. ['a' => ['b' => ['c' => 10]], 'b' => 2],
  66. ['a' => ['b' => ['d' => 15]], 'b' => 4],
  67. ['a' => ['x' => ['z' => 20]], 'b' => 4],
  68. ['a' => ['b' => ['c' => 25]], 'b' => 2],
  69. ];
  70. $extractor = new ExtractIterator($items, 'a.b.c');
  71. $this->assertEquals([10, null, null, 25], iterator_to_array($extractor));
  72. }
  73. }