/** * Returns the output of a wp-cli command as an array. * * This method should be used in conjuction with wp-cli commands that will return lists. * E.g. * * $inactiveThemes = $I->cliToArray('theme list --status=inactive --field=name'); * * The above command could return an array like * * ['twentyfourteen', 'twentyfifteen'] * * No check will be made on the command the user inserted for coherency with a split-able * output. * * @param string $userCommand * * @return array An array containing the output of wp-cli split into single elements. */ public function cliToArray($userCommand = 'post list --format=ids', callable $splitCallback = null) { $this->initPaths(); $command = $this->buildCommand($userCommand); $this->debugSection('command', $command); $output = $this->executor->execAndOutput($command, $status); $this->debugSection('output', $output); $this->evaluateStatus($output, $status); if (empty($output)) { return []; } $hasSplitCallback = !is_null($splitCallback); $originalOutput = $output; if (!is_array($output) || is_array($output) && $hasSplitCallback) { if (is_array($output)) { $output = implode(PHP_EOL, $output); } if (!$hasSplitCallback) { if (!preg_match('/[\\n]+/', $output)) { $output = preg_split('/\\s+/', $output); } else { $output = preg_split('/\\s*\\n+\\s*/', $output); } } else { $output = $splitCallback($output, $userCommand, $this); } } if (!is_array($output) && $hasSplitCallback) { throw new ModuleException(__CLASS__, "Split callback must return an array, it returned: \n" . print_r($output, true) . "\nfor original output:\n" . print_r($originalOutput, true)); } return empty($output) ? [] : array_map('trim', $output); }
/** * @test * it should call the split callback even if the output is an array */ public function it_should_call_the_split_callback_even_if_the_output_is_an_array() { $output = ['123foo', 'foo123', '123foo', 'bar']; $this->executor->execAndOutput(Argument::type('string'), Argument::any())->willReturn($output); $sut = $this->make_instance(); $callback = function ($output) { return preg_split('/123\\n/', $output); }; $expected = preg_split('/123\\n/', implode(PHP_EOL, $output)); $this->assertEquals($expected, $sut->cliToArray('post list --format=ids', $callback)); }