-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathApi4Command.php
192 lines (152 loc) · 6.8 KB
/
Api4Command.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
<?php
namespace Civi\Cv\Command;
use Civi\Cv\Encoder;
use Civi\Cv\Util\Api4ArgParser;
use Civi\Cv\Util\BootTrait;
use Civi\Cv\Util\StructuredOutputTrait;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Api4Command extends BaseCommand {
use BootTrait;
use StructuredOutputTrait;
/**
* @var array
*/
public $defaults;
/**
* @param string|null $name
*/
public function __construct($name = NULL) {
$this->defaults = array('version' => 4, 'checkPermissions' => FALSE);
parent::__construct($name);
}
protected function configure() {
$C = '<comment>';
$_C = '</comment>';
$I = '<info>';
$_I = '</info>';
$this
->setName('api4')
->setDescription('Call APIv4')
->addOption('in', NULL, InputOption::VALUE_REQUIRED, 'Input format (args,json)', 'args')
->configureOutputOptions(['tabular' => TRUE, 'shortcuts' => ['table', 'list']])
->addOption('dry-run', 'N', InputOption::VALUE_NONE, 'Preview the API call. Do not execute.')
->addArgument('Entity.action', InputArgument::REQUIRED)
->addArgument('key=value', InputArgument::IS_ARRAY)
->setHelp("Call an entity/action in APIv4
If your inputs are determined dynamically (e.g. from an external or untrusted
data-source), then it is better to pass parameters via pipe using strict JSON format.
This minimizes the risk that a dynamic value will be incorrectly escaped.
Alas, strict JSON is cumbersome to manually enter on the CLI.
If your inputs are entered manually, then it is easier to use a mix of \"+Options\"
and \"JSON-ish Key-Value\". The \"+Options\" are ideal for common parameters
(like \"select\" or \"where\"), and \"JSON-ish Key-Value\" is a decent fallback
for less common parameters.
Below, we consider a specification for each format and a set of examples.
If you'd like to inspect the behavior more carefully, try using {$I}--dry-run{$_I} ({$I}-N{$_I}).
{$C}Specification: Piped JSON${_C}
{$C}echo{$_C} {$I}JSON{$_I} | {$C}cv api4${_C} {$I}ENTITY{$_I}.{$I}ACTION{$_I} {$C}--in=json${_C}
{$C}Specification: +Options${_C}
{$C}cv api4${_C} {$I}ENTITY{$_I}.{$I}ACTION{$_I} [{$C}+{$_C}{$I}OP{$_I}{$C} {$_C}{$I}EXPR{$_I}]...
Each \"+Option\" allows you to specify a common APIv4 parameter using a
pithy, purpose-built notation. For example:
Option Examples
{$C}+s{$_C}|{$C}+select{$_C} +select id,display_name
+select=id,display_name
+s id,display_name
{$C}+w{$_C}|{$C}+where{$_C} +where 'first_name like \"Adams%\"'
+w 'first_name like \"Adams%\"'
{$C}+o{$_C}|{$C}+orderBy{$_C} +orderBy last_name,first_name
+o last_name,first_name
+o 'last_name DESC,first_name ASC'
{$C}+l{$_C}|{$C}+limit{$_C} +limit 15@60
+l 15
{$C}+v{$_C}|{$C}+value{$_C} +v name=Alice
+v name=Alice
NOTE: The +{$I}OP{$_I} may be written long ({$C}+where{$_C}) or short ({$C}+w{$_C}). It is
valid to separate the +{$I}OP{$_I} and {$I}EXPR{$_I} using a space, colon, or equals sign.
{$C}Specification: JSON-ish Key-Value${_C}
{$C}cv api4${_C} {$I}ENTITY{$_I}.{$I}ACTION{$_I} [{$I}KEY{$_I}={$I}VALUE{$_I}]... [{$I}JSON-OBJECT{$_I}]...
Use ${I}KEY{$_I}={$I}VALUE{$_I} to set an input to a specific value. The value may be a bare string
or it may be JSON (beginning with '[' or '{' or '\"').
Use {$I}JSON-OBJECT{$_I} if you want to pass several fields as one pure JSON string.
A parameter which begins with '{' will be interpreted as a JSON expression.
{$C}Example: Get all contacts{$_C}
cv api4 Contact.get
{$C}Example: Get ten contacts{$_C} (All examples are equivalent.)
cv api4 Contact.get +s id,display_name +l 10
cv api4 Contact.get select='[\"id\",\"display_name\"]' limit=10
cv api4 Contact.get '{\"select\":[\"id\",\"display_name\"],\"limit\":10}'
echo '{\"select\":[\"id\",\"display_name\"],\"limit\":10}' | cv api4 Contact.get --in=json
{$C}Example: Find ten contacts named \"Adam\"{$_C}
cv api4 Contact.get +s display_name +w 'display_name LIKE \"Adam%\"' limit=10
{$C}Example: Find contact names for IDs between 100 and 200, ordered by last name{$_C}
cv api4 Contact.get +s display_name +o last_name +w 'id >= 100' +w 'id <= 200'
{$C}Example: Change do_not_phone for everyone named Adam{$_C}
cv api4 Contact.update +w 'display_name like %Adam%' +v do_not_phone=1
NOTE: To change the default output format, set CV_OUTPUT.
");
$this->configureBootOptions();
}
protected function execute(InputInterface $input, OutputInterface $output) {
$C = '<comment>';
$_C = '</comment>';
$I = '<info>';
$_I = '</info>';
$this->boot($input, $output);
if (!function_exists('civicrm_api4')) {
throw new \RuntimeException("Please enable APIv4 before running APIv4 commands.");
}
[$entity, $action] = explode('.', $input->getArgument('Entity.action'));
$params = $this->parseParams($input);
if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE || $input->getOption('dry-run')) {
$output->writeln("{$I}Entity{$_I}: {$C}$entity{$_C}");
$output->writeln("{$I}Action{$_I}: {$C}$action{$_C}");
$output->writeln("{$I}Params{$_I}: " . json_encode($params, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}
if ($input->getOption('dry-run')) {
return 0;
}
$result = \civicrm_api4($entity, $action, $params);
$out = $input->getOption('out');
if (!in_array($out, Encoder::getFormats()) && in_array($out, Encoder::getTabularFormats())) {
$columns = empty($params['select']) ? array_keys($result->first()) : $params['select'];
$this->sendTable($input, $output, (array) $result, $columns);
}
elseif (!empty($params['select']) && $params['select'] === ['row_count']) {
$this->sendResult($input, $output, $result->count());
}
else {
$this->sendResult($input, $output, $result);
}
return 0;
}
/**
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param $matches
* @return array
*/
protected function parseParams(InputInterface $input) {
$args = $input->getArgument('key=value');
switch ($input->getOption('in')) {
case 'args':
$p = new Api4ArgParser();
$params = $p->parse($args, $this->defaults);
break;
case 'json':
$json = stream_get_contents(STDIN);
if (empty($json)) {
$params = $this->defaults;
}
else {
$params = array_merge($this->defaults, json_decode($json, TRUE));
}
break;
default:
throw new \RuntimeException('Unknown input format');
}
return $params;
}
}