Skip to content

Commit

Permalink
βœ…πŸ› Add tests and fix bugs for RelationsInModelFinder
Browse files Browse the repository at this point in the history
  • Loading branch information
mathieutu committed Aug 2, 2017
1 parent 73fff7d commit 7540199
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 9 deletions.
14 changes: 6 additions & 8 deletions src/Helpers/RelationsInModelFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,6 @@
class RelationsInModelFinder
{
private $model;
/**
* @var
*/
private $relationsType;

public function __construct(Model $model, array $relationsType)
Expand All @@ -19,22 +16,23 @@ public function __construct(Model $model, array $relationsType)
$this->relationsType = $relationsType;
}

public static function children(Model $model)
public static function hasOneOrMany(Model $model)
{
return (new static($model, ['hasMany', 'hasManyThrough', 'hasOne']))->find();
return (new static($model, ['hasMany', 'hasOne']))->find();
}

protected function find()
{
return collect(get_class_methods($this->model))->sort()
->reject(function ($method) {
$this->isAnEloquentMethod($method);
return $this->isAnEloquentMethod($method);
})->filter(function ($method) {
$code = $this->getMethodCode($method);
collect($this->relationsType)->contains(function ($relation) use ($code) {

return collect($this->relationsType)->contains(function ($relation) use ($code) {
return Str::contains($code, '$this->' . $relation . '(');
});
});
})->toArray();
}

protected function isAnEloquentMethod($method): bool
Expand Down
2 changes: 1 addition & 1 deletion src/Traits/JsonExporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public function exportRelations(): Collection

public function getJsonExportableRelations(): array
{
return $this->jsonExportableRelations ?? RelationsInModelFinder::children($this);
return $this->jsonExportableRelations ?? RelationsInModelFinder::hasOneOrMany($this);
}


Expand Down
42 changes: 42 additions & 0 deletions tests/Helpers/RelationsInModelFinderTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

namespace MathieuTu\JsonImport\Tests\Helpers;

use MathieuTu\JsonImport\Helpers\RelationsInModelFinder;

class RelationsInModelFinderTest extends \PHPUnit\Framework\TestCase
{
public function testhasOneOrMany()
{
$this->assertEquals(['foos', 'bar'], RelationsInModelFinder::hasOneOrMany(new MyModel()));
}
}

class MyModel extends \Illuminate\Database\Eloquent\Model
{
public function foos()
{
return $this->hasMany('foo');
}

public function bar()
{
return $this->hasOne('bar');
}

public function baz()
{
return $this->hasManyThrough('baz', 'bar');
}

public function notARelation()
{
return 'this is not a relation!';
}

public function parent()
{
return $this->belongsTo('parent');
}

}

0 comments on commit 7540199

Please sign in to comment.