SupportMacroableTest.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace Tightenco\Collect\Tests\Support;
  3. use PHPUnit\Framework\TestCase;
  4. use Tightenco\Collect\Support\Traits\Macroable;
  5. class SupportMacroableTest extends TestCase
  6. {
  7. private $macroable;
  8. public function setUp()
  9. {
  10. $this->macroable = $this->createObjectForTrait();
  11. }
  12. private function createObjectForTrait()
  13. {
  14. return new EmptyMacroable;
  15. }
  16. public function testRegisterMacro()
  17. {
  18. $macroable = $this->macroable;
  19. $macroable::macro(__CLASS__, function () {
  20. return 'Taylor';
  21. });
  22. $this->assertEquals('Taylor', $macroable::{__CLASS__}());
  23. }
  24. public function testRegisterMacroAndCallWithoutStatic()
  25. {
  26. $macroable = $this->macroable;
  27. $macroable::macro(__CLASS__, function () {
  28. return 'Taylor';
  29. });
  30. $this->assertEquals('Taylor', $macroable->{__CLASS__}());
  31. }
  32. public function testWhenCallingMacroClosureIsBoundToObject()
  33. {
  34. TestMacroable::macro('tryInstance', function () {
  35. return $this->protectedVariable;
  36. });
  37. TestMacroable::macro('tryStatic', function () {
  38. return static::getProtectedStatic();
  39. });
  40. $instance = new TestMacroable;
  41. $result = $instance->tryInstance();
  42. $this->assertEquals('instance', $result);
  43. $result = TestMacroable::tryStatic();
  44. $this->assertEquals('static', $result);
  45. }
  46. public function testClassBasedMacros()
  47. {
  48. TestMacroable::mixin(new TestMixin);
  49. $instance = new TestMacroable;
  50. $this->assertEquals('instance-Adam', $instance->methodOne('Adam'));
  51. }
  52. }
  53. class EmptyMacroable
  54. {
  55. use Macroable;
  56. }
  57. class TestMacroable
  58. {
  59. use Macroable;
  60. protected $protectedVariable = 'instance';
  61. protected static function getProtectedStatic()
  62. {
  63. return 'static';
  64. }
  65. }
  66. class TestMixin
  67. {
  68. public function methodOne()
  69. {
  70. return function ($value) {
  71. return $this->methodTwo($value);
  72. };
  73. }
  74. protected function methodTwo()
  75. {
  76. return function ($value) {
  77. return $this->protectedVariable.'-'.$value;
  78. };
  79. }
  80. }