xero-8.x-2.x-dev/examples/src/Controller/ExampleController.php
examples/src/Controller/ExampleController.php
<?php
namespace Drupal\xero_example\Controller;
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\examples\Utility\DescriptionTemplateTrait;
use Drupal\xero\XeroQuery;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Example of fetching data from the Xero API.
*
* @ingroup xero_example
*/
class ExampleController implements ContainerInjectionInterface {
use DescriptionTemplateTrait;
/**
* The Xero query.
*
* @var \Drupal\xero\XeroQuery
*/
protected $query;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container->get('xero.query'));
}
/**
* Initialization method.
*
* @param \Drupal\xero\XeroQuery $query
* The xero query to make requests with.
*/
public function __construct(XeroQuery $query) {
$this->query = $query;
}
/**
* {@inheritdoc}
*/
public function getModuleName() {
return 'xero_example';
}
/**
* Shows a list of Xero accounts.
*
* @return array
* A render array.
*
* @throws \Throwable
*/
public function index() {
$render = [
'#type' => 'container',
];
try {
/** @var \Drupal\Core\TypedData\ListInterface|bool $accounts */
$accounts = $this->query
->setType('xero_account')
->setMethod('get')
->execute();
$render['accounts'] = [];
if ($accounts) {
/** @var \Drupal\xero\Plugin\DataType\Account $account */
foreach ($accounts as $account) {
$render['accounts'][] = $account->view();
}
}
else {
$render['error'] = [
'#markup' => 'Something went wrong with this request. Did you configure your Xero private application consumer key and secret and authorize the application?',
];
}
}
catch (PluginException $e) {
$render['error'] = [
'#markup' => $e->getMessage(),
];
}
return $render;
}
}
