Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
},
"require-dev": {
"phpunit/phpunit": "^4.8",
"mockery/mockery": "^0.9.4"
"mockery/mockery": "^0.9.4",
"orchestra/testbench": "^3.3"
},
"autoload": {
"psr-4": {
Expand Down
217 changes: 122 additions & 95 deletions src/Torann/RemoteModel/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,29 @@
use JsonSerializable;
use Jenssegers\Date\Date;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Http\UploadedFile;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;

abstract class Model implements ArrayAccess, Arrayable, Jsonable, JsonSerializable
{
/**
* The url query data
*
* @var array
*/
protected $query = [];

/**
* pagination
*
* @var array
*/
protected $pagination = [];

/**
* The client associated with the model.
*
Expand Down Expand Up @@ -230,6 +246,17 @@ public static function setDateFormat($format)
Date::setToStringFormat($format);
}

/**
* Encode the given value as JSON.
*
* @param mixed $value
* @return string
*/
protected function asJson($value)
{
return json_encode($value);
}

/**
* Get the value of the model's primary key.
*
Expand Down Expand Up @@ -357,37 +384,6 @@ public function newInstance($attributes = [], $exists = false)
return $model;
}

/**
* Create a collection of models from plain arrays.
*
* @param array $items
* @return array
*/
public static function hydrate(array $items, $class = null)
{
$items = array_map(function ($item) use ($class) {
// Single class given
if (gettype($class) === 'string') {
return new $class($item);
}

// Map an array of classes
if (gettype($class) === 'array') {

if (isset($item['type']) && isset($class[$item['type']])) {
return new $class[$item['type']]($item);
}

return null;
}

return new static($item, static::getParentID());

}, $items);

return array_filter($items);
}

/**
* Paginate items.
*
Expand Down Expand Up @@ -421,24 +417,32 @@ public function paginateHydrate($result, $modelClass = null)
'last'
]) : [];

return new LengthAwarePaginator($this->hydrate($items, $modelClass), $total, $perPage, $currentPage,
array_merge($options, [
'path' => LengthAwarePaginator::resolveCurrentPath()
]));
return new LengthAwarePaginator(
$items,
$total,
$perPage,
$currentPage,
array_merge(
$options,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
]
)
);
}

/**
* Execute the query and get the first result.
*
* @param string $id
* @param array $params
* @param array $columns
* @return mixed|static
*/
public static function find($id, array $params = [])
public static function find($id, $columns = ['*'])
{
$instance = new static([], static::getParentID());

return $instance->request($instance->getEndpoint(), 'find', [$id, $params]);
return $instance->where($instance->getKeyName(), $id)->first($columns);
}

/**
Expand All @@ -459,76 +463,78 @@ public static function create(array $attributes = [])
/**
* Make an all paginated request.
*
* @param array $params
* @return \Illuminate\Pagination\LengthAwarePaginator
* @param array $columns
* @return \Illuminate\Support\Collection|static[]
*/
public static function all(array $params = [])
public static function all(array $columns = ['*'])
{
// Remove empty params
$params = array_filter($params);

$instance = new static([], static::getParentID());

// Make request
$result = $instance->makeRequest($instance->getEndpoint(), 'all', [$params]);

// Hydrate object
$result = $instance->paginateHydrate($result);

// Append search params
$result->appends($params);

return $result;
return $instance->get($columns);
}

/**
* Paginate request.
* Get Pagination
*
* @param string $method
* @param array $params
* @return \Illuminate\Pagination\LengthAwarePaginator
* @return array
*/
public static function paginate($method, array $params = [])
public function getPagination()
{
// Set request params
$params = array_filter(array_merge([
'page' => 1
], $params));

$instance = new static([], static::getParentID());;

// Make request
$result = $instance->makeRequest($instance->getEndpoint(), $method, [$params]);

// Hydrate object
$result = $instance->paginateHydrate($result);
return $this->pagination;
}

// Append search params
$result->appends($params);
/**
* Paginate the given query.
*
* @param int $perPage
* @param array $columns
* @param string $pageName
* @param int|null $page
* @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
*
* @throws \InvalidArgumentException
*/
public static function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
{
$instance = new static([], static::getParentID());

return $result;
if ($perPage) {
$instance->take($perPage);
}
$instance->query['_page'] = $page ?: Paginator::resolveCurrentPage($pageName);

$items = $instance->get($columns);
$pagination = $instance->getPagination();

return new LengthAwarePaginator(
$items,
$pagination['total'],
$pagination['per_page'],
$pagination['current_page'],
[
'path' => Paginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
}

/**
* Find a model by its primary key or throw an exception
*
* @param string $id
* @param array $params
* @param array $columns
* @return mixed|static
*
* @throws \Torann\RemoteModel\NotFoundException
*/
public static function findOrFail($id, array $params = [])
public static function findOrFail($id, $columns = ['*'])
{
$instance = new static([], static::getParentID());

// Make request
if (!is_null($result = $instance->request($instance->getEndpoint(), 'find', [$id, $params]))) {
return $result;
$result = static::find($id, $columns);
if (is_null($result)) {
throw new NotFoundException;
}

// Not found
throw new NotFoundException;
return $result;
}

/**
Expand Down Expand Up @@ -893,13 +899,21 @@ public function getClientError()
/**
* Execute the query and get the first result.
*
* @param string $id
* @param array $params
* @return mixed|static
* @param array $columns
* @return \Illuminate\Support\Collection|static[]
*/
public function get($id, array $params = [])
public function get($columns = ['*'])
{
return $this->request($this->getEndpoint(), 'find', [$id, $params]);
$this->query['_columns'] = $columns;
$results = $this->makeRequest($this->getEndpoint(), 'get', [$this->query]);
$items = array_pull($results, 'data');
$this->pagination = $results;

$collection = collect($items)->map(function ($item, $key) {
return $this->newInstance($item, true);
});

return $collection;
}

/**
Expand Down Expand Up @@ -1046,28 +1060,37 @@ public function getRouteKey()
*/
public function where($column, $value = null)
{
$this->setAttribute($column, $value);
$this->query[$column] = $value;
return $this;
}

/**
* Set the "limit" value of the query.
*
* @param int $value
* @return $this
*/
public function take($value)
{
$this->query['_take'] = $value;
return $this;
}

/**
* Execute the query and get the first result.
*
* NOTE: Used for route binding
*
* @return mixed|static
*/
public function first()
public function first($columns = ['*'])
{
$result = $this->get($this->getRouteKey());
$result = $this->take(1)->get($columns);

// After route event
if ($result && method_exists($result, 'afterRoute')) {
$result->afterRoute();
}

return $result;
return count($result) > 0 ? $result->pop() : null;
}

/**
Expand Down Expand Up @@ -1444,6 +1467,10 @@ public function setAttribute($key, $value)
return $this->{'set' . studly_case($key) . 'Attribute'}($value);
}

if ($this->isJsonCastable($key) && ! is_null($value)) {
$value = $this->asJson($value);
}

$this->attributes[$key] = $value;
}

Expand Down Expand Up @@ -1756,7 +1783,7 @@ protected function request($endpoint = null, $method, $params)
*
* @return mixed
*/
protected function makeRequest($endpoint = null, $method, $params)
protected function makeRequest($endpoint, $method, $params)
{
$endpoint = $endpoint ?: $this->getEndpoint();

Expand Down
Loading