Skip to content

Instantly share code, notes, and snippets.

@disasterdrop
Last active December 5, 2016 16:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save disasterdrop/ee9d3c702c63d5c609b55821d59f2a3f to your computer and use it in GitHub Desktop.
Save disasterdrop/ee9d3c702c63d5c609b55821d59f2a3f to your computer and use it in GitHub Desktop.
Propel Adapters for Apigility Collections
<?php
namespace Musterhaus\Propel\Paginator\Adapter;
use Zend\Paginator\Adapter\AdapterInterface;
use PropelCollection;
/**
* Class CollectionAdapter
*
* @package Musterhaus\Propel\Paginator\Adapter
* @author Sebastian Okolowski <okolowski@musterhaus.net>
*/
class CollectionAdapter implements AdapterInterface {
/**
*
* @var PropelCollection
*/
protected $collection;
/**
* @var int
*/
protected $count = 0;
/**
* CollectionAdapter constructor.
*
* @param PropelCollection $collection
*/
public function __construct(PropelCollection $collection) {
$this->collection = $collection;
}
/**
* @param int $offset
* @param int $itemCountPerPage
* @return array
*/
public function getItems($offset, $itemCountPerPage) {
$items = array();
foreach($this->collection as $item) {
$items[] = $item;
}
return array_slice($items, $offset, $itemCountPerPage);
}
/**
* @param string $mode
* @return int
*/
public function count() {
return $this->collection->count();
}
}
<?php
namespace Musterhaus\Propel\Paginator\Adapter;
use Zend\Paginator\Adapter\AdapterInterface;
/**
* Class PaginatorAdapter
*
* @package Musterhaus\Propel\Paginator\Adapter
* @author Sebastian Okolowski <okolowski@muterhaus.net>
*/
class PaginatorAdapter implements AdapterInterface {
/**
* @var \ModelCriteria
*/
protected $query;
/**
* @var int
*/
protected $count = 0;
/**
* PaginatorAdapter constructor.
*
* @param $query
*/
public function __construct(\ModelCriteria $query) {
$this->query = $query;
$this->count = $this->query->count();
}
/**
* @param int $offset
* @param int $itemCountPerPage
* @return \PropelModelPager
*/
public function getItems($offset, $itemCountPerPage) {
$page = round($offset / $itemCountPerPage) + 1;
return $this->query->paginate($page, $itemCountPerPage);
}
/**
* @return int
*/
public function count() {
return $this->count;
}
}
<?php
use Musterhaus\Propel\Paginator\Adapter\PaginatorAdapter;
class SomeApigilityResource extends AbstractResourceListener {
/**
* Fetch all or a subset of resources
*
* @param array $params
* @return ApiProblem|mixed
*/
public function fetchAll($params = array()) {
$query = \SomePropelQuery::create();
$adapter = new PaginatorAdapter($query);
return new \SomeApigilityRestCollection($adapter);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment