Skip to content

Commit

Permalink
Map only those method names returning eloquent operations
Browse files Browse the repository at this point in the history
  • Loading branch information
nilportugues committed Oct 16, 2015
1 parent d7e1468 commit 47126a0
Showing 1 changed file with 25 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

namespace NilPortugues\Laravel5\JsonApiSerializer\Mapper;

use ErrorException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;
use ReflectionClass;
Expand Down Expand Up @@ -40,7 +41,7 @@ protected static function getClassProperties($className)
if (is_subclass_of($value, Model::class, true)) {
$attributes = array_merge(
Schema::getColumnListing($value->getTable()),
self::getRelationshipMethodsAsPropertyName($className, $reflection)
self::getRelationshipMethodsAsPropertyName($value, $className, $reflection)
);

self::$eloquentClasses[$className] = $attributes;
Expand All @@ -53,18 +54,39 @@ protected static function getClassProperties($className)
return parent::getClassProperties($className);
}


/**
* @param $value
* @param string $className
* @param ReflectionClass $reflection
*
* @return array
*/
protected static function getRelationshipMethodsAsPropertyName($className, ReflectionClass $reflection)
protected static function getRelationshipMethodsAsPropertyName($value, $className, ReflectionClass $reflection)
{
$methods = [];
foreach ($reflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
if (ltrim($method->class, "\\") === ltrim($className, "\\")) {
$methods[] = $method->name;

$name = $method->name;
$reflectionMethod = $reflection->getMethod($name);

// Eloquent relations do not include parameters, so we'll be filtering based on this criteria.
if (0 == $reflectionMethod->getNumberOfParameters()) {
try {
$returned = $reflectionMethod->invoke($value);
//All operations (eg: boolean operations) are now filtered out.
if (is_object($returned)) {

// Only keep those methods as properties if these are returning Eloquent relations.
// But do not run the operation as it is an expensive operation.
if (false !== strpos(get_class($returned), 'Illuminate\Database\Eloquent\Relations')) {
$methods[] = $method->name;
}

}
} catch(ErrorException $e) {}
}
}
}

Expand Down

0 comments on commit 47126a0

Please sign in to comment.