icingaweb2-module-director/library/Director/Cli/ObjectsCommand.php

116 lines
3.0 KiB
PHP
Raw Normal View History

2016-10-24 21:44:43 +02:00
<?php
namespace Icinga\Module\Director\Cli;
use Icinga\Module\Director\Objects\IcingaObject;
class ObjectsCommand extends Command
2016-10-24 21:44:43 +02:00
{
protected $type;
private $objects;
/**
* List all objects of this type
*
2018-02-20 21:58:36 +01:00
* Use this command to get a list of all matching objects
2016-10-24 21:44:43 +02:00
*
* USAGE
*
* icingacli director <types> list [options]
*
* OPTIONS
*
* --json Use JSON format
* --no-pretty JSON is pretty-printed per default (for PHP >= 5.4)
* Use this flag to enforce unformatted JSON
*/
public function listAction()
{
$db = $this->db();
$result = array();
foreach ($this->getObjects() as $o) {
$result[] = $o->getObjectName();
}
sort($result);
if ($this->params->shift('json')) {
echo $this->renderJson($result, !$this->params->shift('no-pretty'));
} else {
foreach ($result as $name) {
echo $name . "\n";
}
}
2016-10-24 21:44:43 +02:00
}
/**
2018-02-20 21:58:36 +01:00
* Fetch all objects of this type
2016-10-24 21:44:43 +02:00
*
2018-02-20 21:58:36 +01:00
* Use this command to fetch all matching objects
2016-10-24 21:44:43 +02:00
*
* USAGE
*
* icingacli director <types> fetch [options]
*
* OPTIONS
*
* --resolved Resolve all inherited properties and show a flat
* object
* --json Use JSON format
* --no-pretty JSON is pretty-printed per default (for PHP >= 5.4)
* Use this flag to enforce unformatted JSON
* --no-defaults Per default JSON output ships null or default values
* With this flag you will skip those properties
2016-10-24 21:44:43 +02:00
*/
public function fetchAction()
{
$resolved = $this->params->shift('resolved');
2016-10-24 21:44:43 +02:00
if ($this->params->shift('json')) {
$noDefaults = $this->params->shift('no-defaults', false);
2016-10-24 21:44:43 +02:00
} else {
$this->fail('Currently only json is supported when fetching objects');
}
$db = $this->db();
$res = array();
foreach ($this->getObjects() as $object) {
if ($resolved) {
$object = $object::fromPlainObject($object->toPlainObject(true), $db);
2016-10-24 21:44:43 +02:00
}
$res[$object->getObjectName()] = $object->toPlainObject(false, $noDefaults);
2016-10-24 21:44:43 +02:00
}
echo $this->renderJson($res, !$this->params->shift('no-pretty'));
2016-10-24 21:44:43 +02:00
}
2018-02-25 17:44:46 +01:00
/**
* @return IcingaObject[]
*/
2016-10-24 21:44:43 +02:00
protected function getObjects()
{
if ($this->objects === null) {
$this->objects = IcingaObject::loadAllByType(
$this->getType(),
$this->db()
);
}
return $this->objects;
}
protected function getType()
{
if ($this->type === null) {
// Extract the command class name...
$className = substr(strrchr(get_class($this), '\\'), 1);
// ...and strip the Command extension
$this->type = rtrim(substr($className, 0, -7), 's');
}
return $this->type;
}
}