DatabaseEloquentBelongsToManyWithCastedAttributesTest.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace Illuminate\Tests\Database;
  3. use Illuminate\Database\Eloquent\Builder;
  4. use Illuminate\Database\Eloquent\Collection;
  5. use Illuminate\Database\Eloquent\Model;
  6. use Illuminate\Database\Eloquent\Relations\BelongsToMany;
  7. use Mockery as m;
  8. use PHPUnit\Framework\TestCase;
  9. class DatabaseEloquentBelongsToManyWithCastedAttributesTest extends TestCase
  10. {
  11. protected function tearDown(): void
  12. {
  13. m::close();
  14. }
  15. public function testModelsAreProperlyMatchedToParents()
  16. {
  17. $relation = $this->getRelation();
  18. $model1 = m::mock(Model::class);
  19. $model1->shouldReceive('getAttribute')->with('parent_key')->andReturn(1);
  20. $model1->shouldReceive('getAttribute')->with('foo')->passthru();
  21. $model1->shouldReceive('hasGetMutator')->andReturn(false);
  22. $model1->shouldReceive('hasAttributeMutator')->andReturn(false);
  23. $model1->shouldReceive('getCasts')->andReturn([]);
  24. $model1->shouldReceive('getRelationValue', 'relationLoaded', 'setRelation', 'isRelation')->passthru();
  25. $model2 = m::mock(Model::class);
  26. $model2->shouldReceive('getAttribute')->with('parent_key')->andReturn(2);
  27. $model2->shouldReceive('getAttribute')->with('foo')->passthru();
  28. $model2->shouldReceive('hasGetMutator')->andReturn(false);
  29. $model2->shouldReceive('hasAttributeMutator')->andReturn(false);
  30. $model2->shouldReceive('getCasts')->andReturn([]);
  31. $model2->shouldReceive('getRelationValue', 'relationLoaded', 'setRelation', 'isRelation')->passthru();
  32. $result1 = (object) [
  33. 'pivot' => (object) [
  34. 'foreign_key' => new class
  35. {
  36. public function __toString()
  37. {
  38. return '1';
  39. }
  40. },
  41. ],
  42. ];
  43. $models = $relation->match([$model1, $model2], Collection::wrap($result1), 'foo');
  44. self::assertNull($models[1]->foo);
  45. self::assertEquals(1, $models[0]->foo->count());
  46. self::assertContains($result1, $models[0]->foo);
  47. }
  48. protected function getRelation()
  49. {
  50. $builder = m::mock(Builder::class);
  51. $related = m::mock(Model::class);
  52. $related->shouldReceive('newCollection')->passthru();
  53. $builder->shouldReceive('getModel')->andReturn($related);
  54. $related->shouldReceive('qualifyColumn');
  55. $builder->shouldReceive('join', 'where');
  56. return new BelongsToMany(
  57. $builder,
  58. new EloquentBelongsToManyModelStub,
  59. 'relation',
  60. 'foreign_key',
  61. 'id',
  62. 'parent_key',
  63. 'related_key'
  64. );
  65. }
  66. }
  67. class EloquentBelongsToManyModelStub extends Model
  68. {
  69. public $foreign_key = 'foreign.value';
  70. }