- md5
- 27e2187c0683fb95b8f8b8990cc1e3d7
- sha1
- c879996f1527b07048ee1d94216e548925a96963
- sha256
- bd015c8d59af3a1cc832e537bf421fa5719923c56b5e6be9d10c03729838d3ba
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
<?php
/**
* Joomla! Content Management System
*
* @copyright (C) 2019 Open Source Matters, Inc. <https://www.joomla.org>
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\CMS\MVC\View;
use Joomla\CMS\Document\JsonapiDocument;
use Joomla\CMS\Factory;
use Joomla\CMS\MVC\View\Event\OnGetApiFields;
use Joomla\CMS\Router\Exception\RouteNotFoundException;
use Joomla\CMS\Serializer\JoomlaSerializer;
use Joomla\CMS\Uri\Uri;
use Tobscure\JsonApi\AbstractSerializer;
use Tobscure\JsonApi\Collection;
use Tobscure\JsonApi\Resource;
// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects
/**
* Base class for a Joomla Json List View
*
* Class holding methods for displaying presentation data.
*
* @since 4.0.0
*/
abstract class JsonApiView extends JsonView
{
/**
* The active document object (Redeclared for typehinting)
*
* @var JsonapiDocument
* @since 3.0
*/
public $document;
/**
* The content type
*
* @var string
*/
protected $type;
/**
* Item relationship
*
* @var array
*
* @since 4.0.0
*/
protected $relationship = [];
/**
* Serializer data
*
* @var AbstractSerializer
* @since 4.0.0
*/
protected $serializer;
/**
* The fields to render item in the documents
*
* @var array
* @since 4.0.0
*/
protected $fieldsToRenderItem = [];
/**
* The fields to render items in the documents
*
* @var array
* @since 4.0.0
*/
protected $fieldsToRenderList = [];
/**
* Constructor.
*
* @param array $config A named configuration array for object construction.
* contentType: the name (optional) of the content type to use for the serialization
*
* @since 4.0.0
*/
public function __construct($config = [])
{
if (\array_key_exists('contentType', $config)) {
$this->type = $config['contentType'];
}
if ($this->serializer === null) {
$this->serializer = new JoomlaSerializer($this->type);
}
parent::__construct($config);
}
/**
* Execute and display a template script.
*
* @param ?array $items Array of items
*
* @return string
*
* @since 4.0.0
*/
public function displayList(?array $items = null)
{
/** @var \Joomla\CMS\MVC\Model\ListModel $model */
$model = $this->getModel();
// Get page query
$currentUrl = Uri::getInstance();
$currentPageDefaultInformation = ['offset' => 0, 'limit' => 20];
$currentPageQuery = $currentUrl->getVar('page', $currentPageDefaultInformation);
if ($items === null) {
$items = [];
foreach ($model->getItems() as $item) {
$items[] = $this->prepareItem($item);
}
}
$pagination = $model->getPagination();
// Check for errors.
if (\count($errors = $this->get('Errors'))) {
throw new GenericDataException(implode("\n", $errors), 500);
}
if ($this->type === null) {
throw new \RuntimeException('Content type missing');
}
// Set up links for pagination
$totalItemsCount = ($pagination->pagesTotal * $pagination->limit);
$this->getDocument()->addMeta('total-pages', $pagination->pagesTotal)
->addLink('self', (string) $currentUrl);
// Check for first and previous pages
if ($pagination->limitstart > 0) {
$firstPage = clone $currentUrl;
$firstPageQuery = $currentPageQuery;
$firstPageQuery['offset'] = 0;
$firstPage->setVar('page', $firstPageQuery);
$previousPage = clone $currentUrl;
$previousPageQuery = $currentPageQuery;
$previousOffset = $currentPageQuery['offset'] - $pagination->limit;
$previousPageQuery['offset'] = $previousOffset >= 0 ? $previousOffset : 0;
$previousPage->setVar('page', $previousPageQuery);
$this->getDocument()->addLink('first', $this->queryEncode((string) $firstPage))
->addLink('previous', $this->queryEncode((string) $previousPage));
}
// Check for next and last pages
if ($pagination->limitstart + $pagination->limit < $totalItemsCount) {
$nextPage = clone $currentUrl;
$nextPageQuery = $currentPageQuery;
$nextOffset = $currentPageQuery['offset'] + $pagination->limit;
$nextPageQuery['offset'] = ($nextOffset > ($pagination->pagesTotal * $pagination->limit)) ? $pagination->pagesTotal - $pagination->limit : $nextOffset;
$nextPage->setVar('page', $nextPageQuery);
$lastPage = clone $currentUrl;
$lastPageQuery = $currentPageQuery;
$lastPageQuery['offset'] = ($pagination->pagesTotal - 1) * $pagination->limit;
$lastPage->setVar('page', $lastPageQuery);
$this->getDocument()->addLink('next', $this->queryEncode((string) $nextPage))
->addLink('last', $this->queryEncode((string) $lastPage));
}
$eventData = ['type' => OnGetApiFields::LIST, 'fields' => $this->fieldsToRenderList, 'context' => $this->type];
$event = new OnGetApiFields('onApiGetFields', $eventData);
/** @var OnGetApiFields $eventResult */
$eventResult = Factory::getApplication()->getDispatcher()->dispatch('onApiGetFields', $event);
$collection = (new Collection($items, $this->serializer))
->fields([$this->type => $eventResult->getAllPropertiesToRender()]);
if (!empty($this->relationship)) {
$collection->with($this->relationship);
}
// Set the data into the document and render it
$this->getDocument()->setData($collection);
return $this->getDocument()->render();
}
/**
* Execute and display a template script.
*
* @param object $item Item
*
* @return string
*
* @since 4.0.0
*/
public function displayItem($item = null)
{
if ($item === null) {
/** @var \Joomla\CMS\MVC\Model\AdminModel $model */
$model = $this->getModel();
$item = $this->prepareItem($model->getItem());
}
if ($item->id === null) {
throw new RouteNotFoundException('Item does not exist');
}
// Check for errors.
if (\count($errors = $this->get('Errors'))) {
throw new GenericDataException(implode("\n", $errors), 500);
}
if ($this->type === null) {
throw new \RuntimeException('Content type missing');
}
$eventData = [
'type' => OnGetApiFields::ITEM,
'fields' => $this->fieldsToRenderItem,
'relations' => $this->relationship,
'context' => $this->type,
];
$event = new OnGetApiFields('onApiGetFields', $eventData);
/** @var OnGetApiFields $eventResult */
$eventResult = Factory::getApplication()->getDispatcher()->dispatch('onApiGetFields', $event);
$element = (new Resource($item, $this->serializer))
->fields([$this->type => $eventResult->getAllPropertiesToRender()]);
if (!empty($this->relationship)) {
$element->with($eventResult->getAllRelationsToRender());
}
$this->getDocument()->setData($element);
$this->getDocument()->addLink('self', Uri::current());
return $this->getDocument()->render();
}
/**
* Prepare item before render.
*
* @param object $item The model item
*
* @return object
*
* @since 4.0.0
*/
protected function prepareItem($item)
{
return $item;
}
/**
* Encode square brackets in the URI query, according to JSON API specification.
*
* @param string $query The URI query
*
* @return string
*
* @since 4.0.0
*/
protected function queryEncode($query)
{
return str_replace(['[', ']'], ['%5B', '%5D'], $query);
}
}
The same content is in 23 releases, Joomla 5.2.0-beta1 to 5.3.0-beta3. See them all, or every version of this file.