diff --git a/.php_cs b/.php_cs new file mode 100644 index 0000000..ab4e8ca --- /dev/null +++ b/.php_cs @@ -0,0 +1,53 @@ +setUsingCache(true) + ->fixers(array( + 'newline_after_open_tag', + 'no_useless_else', + 'no_useless_return', + 'ordered_use', + 'php_unit_construct', + '-phpdoc_annotation_without_dot', + '-phpdoc_params', + '-phpdoc_to_comment', + '-psr0', + 'unalign_double_arrow', + 'unalign_equals', + )) + ->finder( + Symfony\CS\Finder\DefaultFinder::create() + ->in(__DIR__) + ->exclude(array('vendor', 'build/templates')) + ) +; diff --git a/.php_cs.dist b/.php_cs.dist new file mode 100644 index 0000000..dfd9d98 --- /dev/null +++ b/.php_cs.dist @@ -0,0 +1,108 @@ +setUsingCache(true) + ->setRiskyAllowed(true) + ->setRules(array( + '@PSR2' => true, + '@Symfony' => true, + '@Symfony:risky' => true, + 'align_multiline_comment' => true, + 'array_indentation' => true, + 'array_syntax' => array('syntax' => 'long'), + 'blank_line_before_statement' => true, + 'combine_consecutive_issets' => true, + 'combine_consecutive_unsets' => true, + 'declare_strict_types' => false, + 'dir_constant' => true, + 'ereg_to_preg' => true, + 'explicit_string_variable' => true, + 'global_namespace_import' => array('import_classes' => false), + 'header_comment' => array('header' => $header), + 'heredoc_to_nowdoc' => true, + 'linebreak_after_opening_tag' => true, + 'logical_operators' => true, + 'method_argument_space' => true, + 'multiline_whitespace_before_semicolons' => true, + 'native_function_invocation' => false, + 'no_alternative_syntax' => true, + 'no_empty_comment' => true, + 'no_extra_consecutive_blank_lines' => array( + 'break', + 'continue', + 'extra', + 'return', + 'throw', + 'use', + 'parenthesis_brace_block', + 'square_brace_block', + 'curly_brace_block', + ), + 'no_homoglyph_names' => true, + 'no_null_property_initialization' => true, + 'no_short_echo_tag' => true, + 'no_spaces_inside_parenthesis' => true, + 'no_superfluous_elseif' => true, + 'no_superfluous_phpdoc_tags' => array('allow_mixed' => true), + 'no_unneeded_curly_braces' => true, + 'no_unneeded_final_method' => true, + 'no_unreachable_default_argument_value' => true, + 'no_unset_on_property' => true, + 'no_useless_else' => true, + 'no_useless_return' => true, + 'no_whitespace_in_blank_line' => true, + 'ordered_class_elements' => true, + 'ordered_imports' => true, + 'phpdoc_add_missing_param_annotation' => true, + 'phpdoc_align' => false, + 'phpdoc_order' => true, + 'phpdoc_summary' => false, + 'phpdoc_to_comment' => false, + 'phpdoc_trim_consecutive_blank_line_separation' => true, + 'phpdoc_types_order' => array( + 'null_adjustment' => 'always_last', + 'sort_algorithm' => 'none', + ), + 'phpdoc_var_annotation_correct_order' => true, + 'php_unit_construct' => true, + 'php_unit_set_up_tear_down_visibility' => true, + 'php_unit_strict' => true, + 'pow_to_exponentiation' => true, + 'psr4' => true, + 'return_assignment' => true, + 'single_line_comment_style' => true, + 'void_return' => false, + 'yoda_style' => true, + )) + ->setFinder( + PhpCsFixer\Finder::create() + ->in(__DIR__) + ->exclude(array('vendor', 'build/templates')) + ) +; diff --git a/.travis.yml b/.travis.yml index 9ede92a..77369b1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -120,3 +120,4 @@ install: script: - ./vendor/bin/phpunit + - ./vendor/bin/php-cs-fixer fix -v diff --git a/build/build.php b/build/build.php old mode 100644 new mode 100755 index 58863e0..8aa1aa1 --- a/build/build.php +++ b/build/build.php @@ -1,27 +1,29 @@ +#!/usr/bin/env php . + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. * - * @copyright GNU General Public License - * @author confirm IT solutions GmbH, Rathausstrase 14, CH-6340 Baar + * @copyright The MIT License (MIT) + * @author confirm IT solutions GmbH, Rathausstrase 14, CH-6340 Baar */ if (!in_array(PHP_SAPI, array('cli', 'phpdbg', 'embed'), true)) { @@ -30,15 +32,11 @@ set_time_limit(0); -/* - * Load required files. - */ +// Load required files. require __DIR__.'/config.inc.php'; require __DIR__.'/replacePlaceholders.func.php'; -/* - * Define some pathes and do some sanity checks for existence of the pathes. - */ +// Define some pathes and do some sanity checks for existence of the pathes. if (!is_dir(PATH_ZABBIX)) { throw new RuntimeException('ERROR: Zabbix path "'.PATH_ZABBIX.'" is not a directory! Please check the PATH_ZABBIX configuration constant.'); @@ -48,7 +46,7 @@ require PATH_ZABBIX.'/include/defines.inc.php'; /** - * @brief Path to the API.php class file of the Zabbix PHP front-end. + * Path to the API.php class file of the Zabbix PHP front-end. * * This class file will be used, to determine all available API classes. */ @@ -59,7 +57,7 @@ } /** - * @brief Path to the api/classes/ directory of the Zabbix PHP front-end. + * Path to the api/classes/ directory of the Zabbix PHP front-end. * * This directory and the contained class files will be used, to determine all * available methods for each API class. @@ -74,9 +72,7 @@ throw new RuntimeException('ERROR: API class directory "'.PATH_ZABBIX_API_CLASSES_DIRECTORY.'" not found!'); } -/* - * Initialize. - */ +// Initialize. // set template placeholders $templatePlaceholders = array( @@ -117,8 +113,7 @@ class ZabbixApiClassMap extends CApiServiceFactory { public function getClassMap() { - $classMap = $this->objects; - return $classMap; + return $this->objects; } } } else { @@ -175,15 +170,13 @@ function __autoload($className) // loop through defined methods foreach ($reflection->getMethods(ReflectionMethod::IS_PUBLIC & ~ReflectionMethod::IS_STATIC) as $method) { // add action to API array - if ($method->class != 'CZBXAPI' && !($resource == 'user' && $method->name == 'login') && !($resource == 'user' && $method->name == 'logout') && !$method->isConstructor() && !$method->isDestructor() && !$method->isAbstract()) { + if ('CZBXAPI' !== $method->class && !('user' === $resource && 'login' === $method->name) && !('user' === $resource && 'logout' === $method->name) && !$method->isConstructor() && !$method->isDestructor() && !$method->isAbstract()) { $apiArray[$resource][] = $method->name; } } } -/* - * Build abstract template. - */ +// Build abstract template. // get template if (!$template = file_get_contents(PATH_TEMPLATES.'/abstract.tpl.php')) { @@ -194,7 +187,7 @@ function __autoload($className) preg_match('/(.*)(.*)(.*)/s', $template, $matches); // sanity check -if (count($matches) != 4) { +if (4 !== count($matches)) { throw new RuntimeException('Template "'.PATH_TEMPLATES.'"/abstract.tpl.php parsing failed!'); } @@ -206,7 +199,7 @@ function __autoload($className) foreach ($actions as $action) { $methodPlaceholders = array( 'API_METHOD' => $resource.'.'.$action, - 'PHP_METHOD' => $resource.ucfirst($action) + 'PHP_METHOD' => $resource.ucfirst($action), ); $apiMethods .= replacePlaceholders($matches[2], $methodPlaceholders); } @@ -222,9 +215,7 @@ function __autoload($className) echo 'BUILT: abstract class file "'.PATH_BUILD.'/'.FILENAME_ABSTRACT.'"'."\n"; -/* - * Build concrete template. - */ +// Build concrete template. if (!file_exists(PATH_BUILD.'/'.FILENAME_CONCRETE)) { // get template @@ -245,9 +236,7 @@ function __autoload($className) echo 'SKIPPED: concrete class file "'.PATH_BUILD.'/'.FILENAME_CONCRETE.'"'."\n"; } -/* - * Build exception template. - */ +// Build exception template. if (!file_exists(PATH_BUILD.'/'.FILENAME_EXCEPTION)) { // get template diff --git a/build/config.inc.php b/build/config.inc.php index 26e60d5..cbc2000 100644 --- a/build/config.inc.php +++ b/build/config.inc.php @@ -1,82 +1,76 @@ . + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. * - * @copyright GNU General Public License - * @author confirm IT solutions GmbH, Rathausstrase 14, CH-6340 Baar + * @copyright The MIT License (MIT) + * @author confirm IT solutions GmbH, Rathausstrase 14, CH-6340 Baar */ /** - * @brief Class name for the abstract API class. + * Class name for the abstract API class. */ - define('CLASSNAME_ABSTRACT', 'AbstractZabbixApi'); /** - * @brief Filename for the abstract API class. + * Filename for the abstract API class. */ - define('FILENAME_ABSTRACT', CLASSNAME_ABSTRACT.'.php'); /** - * @brief Class name for the concrete API class. + * Class name for the concrete API class. */ - define('CLASSNAME_CONCRETE', 'ZabbixApi'); /** - * @brief Filename for the abstract API class. + * Filename for the abstract API class. */ - define('FILENAME_CONCRETE', CLASSNAME_CONCRETE.'.php'); /** - * @brief Class name for the abstract API class. + * Class name for the abstract API class. */ - define('CLASSNAME_EXCEPTION', 'Exception'); /** - * @brief Filename for the abstract API class. + * Filename for the abstract API class. */ - define('FILENAME_EXCEPTION', CLASSNAME_EXCEPTION.'.php'); /** - * @brief Filesystem path to templates directory. + * Filesystem path to templates directory. * * This directory contains all templates to build the class files. */ - define('PATH_TEMPLATES', __DIR__.'/templates'); /** - * @brief Filesystem path to build directory. + * Filesystem path to build directory. * * This directory contains the built class files. */ - define('PATH_BUILD', __DIR__.'/../src'); /** - * @brief Filesystem path to the Zabbix PHP front-end root. + * Filesystem path to the Zabbix PHP front-end root. * * Trailing slash not required! * @@ -84,5 +78,4 @@ * the Zabbix PHP front-end (v2) on the same server, you probably only have * to update this constant! */ - define('PATH_ZABBIX', '/opt/zabbix/frontend'); diff --git a/build/replacePlaceholders.func.php b/build/replacePlaceholders.func.php index e105476..9cbffea 100644 --- a/build/replacePlaceholders.func.php +++ b/build/replacePlaceholders.func.php @@ -1,44 +1,45 @@ . - * - * @copyright GNU General Public License - * @author confirm IT solutions GmbH, Rathausstrase 14, CH-6340 Baar + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * @copyright The MIT License (MIT) + * @author confirm IT solutions GmbH, Rathausstrase 14, CH-6340 Baar */ - /** - * @brief Replace placeholders in a string. + * Replace placeholders in a string. * * Placeholders in the string are surrounded by '<' and '>' (e.g. ''). * - * @param $string Any string. - * @param $placeholders Array with placeholders (key-value pair). + * @param string $string any string + * @param array $placeholders array with placeholders (key-value pair) * - * @retval string Replaced string. + * @return string replaced string */ - function replacePlaceholders($string, $placeholders) { - foreach($placeholders as $placeholder => $value) + foreach ($placeholders as $placeholder => $value) { $string = str_replace('<'.strtoupper($placeholder).'>', $value, $string); + } return $string; } diff --git a/build/templates/abstract.tpl.php b/build/templates/abstract.tpl.php index a5e457f..a10d6b2 100644 --- a/build/templates/abstract.tpl.php +++ b/build/templates/abstract.tpl.php @@ -1,23 +1,6 @@ - * - * @brief Class file for the implementation of the class . - * - * __ ___ ____ _ _ ___ _ _ ____ - * \ \ / / \ | _ \| \ | |_ _| \ | |/ ___| - * \ \ /\ / / _ \ | |_) | \| || || \| | | _ - * \ V V / ___ \| _ <| |\ || || |\ | |_| | - * \_/\_/_/ \_\_| \_\_| \_|___|_| \_|\____| - * - * This class was automatically generated by the PhpZabbixApi builder script, - * and will be replaced as soon as the script is invoked again, or you're about - * to update the PhpZabbixApi version. Therefor do not modify this file and - * leave it as it is. After updating / regenerating the library, this file will - * be overwritten, and all modifications will be lost. - * If you need to customize the API class, please implement your customizations - * in the concrete class "". - * + +/* * This file is part of PhpZabbixApi. * * Permission is hereby granted, free of charge, to any person obtaining a copy @@ -38,258 +21,268 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @copyright The MIT License (MIT) - * @author confirm IT solutions GmbH, Rathausstrase 14, CH-6340 Baar + * @copyright The MIT License (MIT) + * @author confirm IT solutions GmbH, Rathausstrase 14, CH-6340 Baar */ namespace ZabbixApi; /** - * @brief Abstract class for the Zabbix API. + * Abstract class for the Zabbix API. */ - abstract class { - /** - * @brief Anonymous API functions. + * Anonymous API functions. + * + * @var string[] */ - - static private $anonymousFunctions = array( - 'apiinfo.version' + private static $anonymousFunctions = array( + 'apiinfo.version', ); /** - * @brief Boolean if requests/responses should be printed out (JSON). + * Boolean if requests/responses should be printed out (JSON). + * + * @var bool */ - - private $printCommunication = FALSE; + private $printCommunication = false; /** - * @brief API URL. + * API URL. + * + * @var string */ - private $apiUrl = ''; /** - * @brief Default params. + * Default params. + * + * @var array */ - private $defaultParams = array(); /** - * @brief Auth string. + * Auth string. + * + * @var string */ - - private $auth = ''; + private $authToken = ''; /** - * @brief Request ID. + * Request ID. + * + * @var int */ - private $id = 0; /** - * @brief Request array. + * Request array. + * + * @var array */ - private $request = array(); /** - * @brief JSON encoded request string. + * JSON encoded request string. + * + * @var string */ - private $requestEncoded = ''; /** - * @brief JSON decoded response string. + * JSON decoded response string. + * + * @var string */ - private $response = ''; /** - * @brief Response object. + * Response object. + * + * @var \stdClass|array */ - - private $responseDecoded = NULL; + private $responseDecoded; /** - * @brief Extra HTTP headers. + * Extra HTTP headers. + * + * @var string */ - private $extraHeaders = ''; /** - * @brief SSL context. + * SSL context. + * + * @var array */ - private $sslContext = array(); /** - * @brief Class constructor. - * - * @param $apiUrl API url (e.g. http://FQDN/zabbix/api_jsonrpc.php) - * @param $user Username for Zabbix API. - * @param $password Password for Zabbix API. - * @param $httpUser Username for HTTP basic authorization. - * @param $httpPassword Password for HTTP basic authorization. - * @param $authToken Already issued auth token (e.g. extracted from cookies) - * @param $sslContext SSL context for SSL-enabled connections + * @param string $apiUrl API url (e.g. http://FQDN/zabbix/api_jsonrpc.php) + * @param string $user Username for Zabbix API + * @param string $password Password for Zabbix API + * @param string $httpUser Username for HTTP basic authorization + * @param string $httpPassword Password for HTTP basic authorization + * @param string $authToken Already issued auth token (e.g. extracted from cookies) + * @param array|null $sslContext SSL context for SSL-enabled connections */ - - public function __construct($apiUrl='', $user='', $password='', $httpUser='', $httpPassword='', $authToken='', $sslContext=NULL) + public function __construct($apiUrl = '', $user = '', $password = '', $httpUser = '', $httpPassword = '', $authToken = '', array $sslContext = null) { - if($apiUrl) + if ($apiUrl) { $this->setApiUrl($apiUrl); + } - if ($httpUser && $httpPassword) + if ($httpUser && $httpPassword) { $this->setBasicAuthorization($httpUser, $httpPassword); + } - if($sslContext) + if ($sslContext) { $this->setSslContext($sslContext); + } - if ($authToken) + if ($authToken) { $this->setAuthToken($authToken); - elseif($user && $password) + } elseif ($user && $password) { $this->userLogin(array('user' => $user, 'password' => $password)); + } } /** - * @brief Returns the API url for all requests. + * Returns the API url for all requests. * - * @retval string API url. + * @return string API url */ - public function getApiUrl() { return $this->apiUrl; } /** - * @brief Sets the API url for all requests. + * Sets the API url for all requests. * - * @param $apiUrl API url. + * @param string $apiUrl API url * - * @retval + * @return */ - public function setApiUrl($apiUrl) { $this->apiUrl = $apiUrl; + return $this; } /** - * @brief Sets the API authorization ID. + * Sets the API authorization ID. * - * @param $authToken API auth ID. + * @param string $authToken API auth ID * - * @retval + * @return */ - public function setAuthToken($authToken) { $this->authToken = $authToken; + return $this; } /** - * @brief Sets the username and password for the HTTP basic authorization. + * Sets the username and password for the HTTP basic authorization. * - * @param $user HTTP basic authorization username - * @param $password HTTP basic authorization password + * @param string $user HTTP basic authorization username + * @param string $password HTTP basic authorization password * - * @retval + * @return */ - public function setBasicAuthorization($user, $password) { - if($user && $password) - $this->extraHeaders = 'Authorization: Basic ' . base64_encode($user.':'.$password); - else + if ($user && $password) { + $this->extraHeaders = 'Authorization: Basic '.base64_encode($user.':'.$password); + } else { $this->extraHeaders = ''; + } return $this; } /** - * @brief Sets the context for SSL-enabled connections. + * Sets the context for SSL-enabled connections. * - * See http://php.net/manual/en/context.ssl.php for more informations. + * @see http://php.net/manual/en/context.ssl.php. * - * @param $context Array with the SSL context + * @param array $context Array with the SSL context * - * @retval + * @return */ - public function setSslContext($context) { $this->sslContext = $context; + return $this; } /** - * @brief Returns the default params. + * Returns the default params. * - * @retval array Array with default params. + * @return array Array with default params */ - public function getDefaultParams() { return $this->defaultParams; } /** - * @brief Sets the default params. + * Sets the default params. * - * @param $defaultParams Array with default params. + * @param array $defaultParams Array with default params * - * @retval + * @throws Exception * - * @throws Exception + * @return */ - public function setDefaultParams($defaultParams) { + if (!is_array($defaultParams)) { + throw new \InvalidArgumentException('Argument 1 passsed to '.__METHOD__.'() must be an array.'); + } - if(is_array($defaultParams)) - $this->defaultParams = $defaultParams; - else - throw new Exception('The argument defaultParams on setDefaultParams() has to be an array.'); + $this->defaultParams = $defaultParams; return $this; } /** - * @brief Sets the flag to print communication requests/responses. + * Sets the flag to print communication requests/responses. * - * @param $print Boolean if requests/responses should be printed out. + * @param bool $print Boolean if requests/responses should be printed out * - * @retval + * @return */ - public function printCommunication($print = TRUE) + public function printCommunication($print = true) { $this->printCommunication = (bool) $print; + return $this; } /** - * @brief Sends are request to the Zabbix API and returns the response - * as object. + * Sends are request to the Zabbix API and returns the response as object. * - * @param $method Name of the API method. - * @param $params Additional parameters. - * @param $auth Enable authentication (default TRUE). + * @param string $method Name of the API method + * @param array|mixed|null $params Additional parameters + * @param string $resultArrayKey + * @param bool $auth Enable authentication (default true) * - * @retval stdClass API JSON response. + * @return mixed API JSON response */ - - public function request($method, $params=NULL, $resultArrayKey='', $auth=TRUE) + public function request($method, $params = null, $resultArrayKey = '', $auth = true) { - // sanity check and conversion for params array - if(!$params) $params = array(); - elseif(!is_array($params)) $params = array($params); + if (!$params) { + $params = array(); + } elseif (!is_array($params)) { + $params = array($params); + } // generate ID $this->id = number_format(microtime(true), 4, '', ''); @@ -297,160 +290,105 @@ public function request($method, $params=NULL, $resultArrayKey='', $auth=TRUE) // build request array $this->request = array( 'jsonrpc' => '2.0', - 'method' => $method, - 'params' => $params, - 'id' => $this->id + 'method' => $method, + 'params' => $params, + 'id' => $this->id, ); // add auth token if required - if ($auth) - $this->request['auth'] = ($this->authToken ? $this->authToken : NULL); + if ($auth) { + $this->request['auth'] = $this->authToken ?: null; + } // encode request array $this->requestEncoded = json_encode($this->request); // debug logging - if($this->printCommunication) + if ($this->printCommunication) { echo 'API request: '.$this->requestEncoded; + } // initialize context $context = array( 'http' => array( - 'method' => 'POST', - 'header' => 'Content-type: application/json-rpc'."\r\n".$this->extraHeaders, - 'content' => $this->requestEncoded - ) + 'method' => 'POST', + 'header' => 'Content-type: application/json-rpc'."\r\n".$this->extraHeaders, + 'content' => $this->requestEncoded, + ), ); - if($this->sslContext) + if ($this->sslContext) { $context['ssl'] = $this->sslContext; + } // create stream context $streamContext = stream_context_create($context); // get file handler - $fileHandler = @fopen($this->getApiUrl(), 'rb', false, $streamContext); - if(!$fileHandler) + $fileHandler = @fopen($this->getApiUrl(), 'r', false, $streamContext); + if (!$fileHandler) { throw new Exception('Could not connect to "'.$this->getApiUrl().'"'); + } // get response $this->response = @stream_get_contents($fileHandler); // debug logging - if($this->printCommunication) + if ($this->printCommunication) { echo $this->response."\n"; + } // response verification - if($this->response === FALSE) + if (false === $this->response) { throw new Exception('Could not read data from "'.$this->getApiUrl().'"'); + } // decode response $this->responseDecoded = json_decode($this->response); // validate response - if(!is_object($this->responseDecoded) && !is_array($this->responseDecoded)) + if (!is_object($this->responseDecoded) && !is_array($this->responseDecoded)) { throw new Exception('Could not decode JSON response.'); - if(array_key_exists('error', $this->responseDecoded)) - throw new Exception('API error '.$this->responseDecoded->error->code.': '.$this->responseDecoded->error->data); + } + + if (property_exists($this->responseDecoded, 'error') && $error = $this->responseDecoded->error) { + $message = 'API error'; + if ($error = $this->responseDecoded->error) { + $message .= ' '.$error->code.': '.$error->data; + } + + throw new Exception($message.'.'); + } // return response - if($resultArrayKey && is_array($this->responseDecoded->result)) + if ($resultArrayKey && is_array($this->responseDecoded->result)) { return $this->convertToAssociatveArray($this->responseDecoded->result, $resultArrayKey); - else - return $this->responseDecoded->result; + } + + return $this->responseDecoded->result; } /** - * @brief Returns the last JSON API request. + * Returns the last JSON API request. * - * @retval string JSON request. + * @return string JSON request */ - public function getRequest() { return $this->requestEncoded; } /** - * @brief Returns the last JSON API response. + * Returns the last JSON API response. * - * @retval string JSON response. + * @return string JSON response */ - public function getResponse() { return $this->response; } /** - * @brief Convertes an indexed array to an associative array. - * - * @param $indexedArray Indexed array with objects. - * @param $useObjectProperty Object property to use as array key. - * - * @retval associative Array - */ - - private function convertToAssociatveArray($objectArray, $useObjectProperty) - { - // sanity check - if(count($objectArray) == 0 || !property_exists($objectArray[0], $useObjectProperty)) - return $objectArray; - - // loop through array and replace keys - $newObjectArray = array(); - foreach($objectArray as $key => $object) - { - $newObjectArray[$object->{$useObjectProperty}] = $object; - } - - // return associative array - return $newObjectArray; - } - - /** - * @brief Returns a params array for the request. - * - * This method will automatically convert all provided types into a correct - * array. Which means: - * - * - arrays will not be converted (indexed & associative) - * - scalar values will be converted into an one-element array (indexed) - * - other values will result in an empty array - * - * Afterwards the array will be merged with all default params, while the - * default params have a lower priority (passed array will overwrite default - * params). But there is an Exception for merging: If the passed array is an - * indexed array, the default params will not be merged. This is because - * there are some API methods, which are expecting a simple JSON array (aka - * PHP indexed array) instead of an object (aka PHP associative array). - * Example for this behavior are delete operations, which are directly - * expecting an array of IDs '[ 1,2,3 ]' instead of '{ ids: [ 1,2,3 ] }'. - * - * @param $params Params array. - * - * @retval Array - */ - - private function getRequestParamsArray($params) - { - // if params is a scalar value, turn it into an array - if(is_scalar($params)) - $params = array($params); - - // if params isn't an array, create an empty one (e.g. for booleans, NULL) - elseif(!is_array($params)) - $params = array(); - - // if array isn't indexed, merge array with default params - if(count($params) == 0 || array_keys($params) !== range(0, count($params) - 1)) - $params = array_merge($this->getDefaultParams(), $params); - - // return params - return $params; - } - - /** - * @brief Login into the API. + * Login into the API. * * This will also retrieves the auth Token, which will be used for any * further requests. Please be aware that by default the received auth @@ -463,7 +401,7 @@ private function getRequestParamsArray($params) * will be executed, and the auth token will be cached again. * * The $params Array can be used, to pass parameters to the Zabbix API. - * For more informations about these parameters, check the Zabbix API + * For more information about these parameters, check the Zabbix API * documentation at https://www.zabbix.com/documentation/. * * The $arrayKeyProperty can be used to get an associative instead of an @@ -471,38 +409,32 @@ private function getRequestParamsArray($params) * is any property of the returned JSON objects (e.g. "name", "host", * "hostid", "graphid", "screenitemid"). * - * @param $params Parameters to pass through. - * @param $arrayKeyProperty Object property for key of array. - * @param $tokenCacheDir Path to a directory to store the auth token. + * @param array $params Parameters to pass through + * @param string $arrayKeyProperty Object property for key of array + * @param string $tokenCacheDir Path to a directory to store the auth token * - * @retval stdClass + * @throws Exception * - * @throws Exception + * @return string */ - - final public function userLogin($params=array(), $arrayKeyProperty='', $tokenCacheDir='/tmp') + final public function userLogin($params = array(), $arrayKeyProperty = '', $tokenCacheDir = '/tmp') { // reset auth token $this->authToken = ''; // build filename for cached auth token - if($tokenCacheDir && array_key_exists('user', $params) && is_dir($tokenCacheDir)) - { - $uid = function_exists('posix_getuid') ? posix_getuid() : -1; + if ($tokenCacheDir && array_key_exists('user', $params) && is_dir($tokenCacheDir)) { + $uid = function_exists('posix_getuid') ? posix_getuid() : -1; $tokenCacheFile = $tokenCacheDir.'/.zabbixapi-token-'.md5($params['user'].'|'.$uid); } // try to read cached auth token - if(isset($tokenCacheFile) && is_file($tokenCacheFile)) - { - try - { + if (isset($tokenCacheFile) && is_file($tokenCacheFile)) { + try { // get auth token and try to execute a user.get (dummy check) $this->authToken = file_get_contents($tokenCacheFile); $this->userGet(); - } - catch(Exception $e) - { + } catch (Exception $e) { // user.get failed, token invalid so reset it and remove file $this->authToken = ''; unlink($tokenCacheFile); @@ -510,15 +442,13 @@ final public function userLogin($params=array(), $arrayKeyProperty='', $tokenCac } // no cached token found so far, so login (again) - if(!$this->authToken) - { + if (!$this->authToken) { // login to get the auth token - $params = $this->getRequestParamsArray($params); - $this->authToken = $this->request('user.login', $params, $arrayKeyProperty, FALSE); + $params = $this->getRequestParamsArray($params); + $this->authToken = $this->request('user.login', $params, $arrayKeyProperty, false); // save cached auth token - if(isset($tokenCacheFile)) - { + if (isset($tokenCacheFile)) { file_put_contents($tokenCacheFile, $this->authToken); chmod($tokenCacheFile, 0600); } @@ -528,12 +458,12 @@ final public function userLogin($params=array(), $arrayKeyProperty='', $tokenCac } /** - * @brief Logout from the API. + * Logout from the API. * * This will also reset the auth Token. * * The $params Array can be used, to pass parameters to the Zabbix API. - * For more informations about these parameters, check the Zabbix API + * For more information about these parameters, check the Zabbix API * documentation at https://www.zabbix.com/documentation/. * * The $arrayKeyProperty can be used to get an associative instead of an @@ -541,29 +471,27 @@ final public function userLogin($params=array(), $arrayKeyProperty='', $tokenCac * is any property of the returned JSON objects (e.g. "name", "host", * "hostid", "graphid", "screenitemid"). * - * @param $params Parameters to pass through. - * @param $arrayKeyProperty Object property for key of array. + * @param array $params Parameters to pass through + * @param string $arrayKeyProperty Object property for key of array * - * @retval stdClass + * @throws Exception * - * @throws Exception + * @return mixed */ - - final public function userLogout($params=array(), $arrayKeyProperty='') + final public function userLogout($params = array(), $arrayKeyProperty = '') { - $params = $this->getRequestParamsArray($params); - $response = $this->request('user.logout', $params, $arrayKeyProperty); + $params = $this->getRequestParamsArray($params); + $response = $this->request('user.logout', $params, $arrayKeyProperty); $this->authToken = ''; + return $response; } - - + /** - * @brief Requests the Zabbix API and returns the response of the API - * method . + * Requests the Zabbix API and returns the response of the API method "". * * The $params Array can be used, to pass parameters to the Zabbix API. - * For more informations about these parameters, check the Zabbix API + * For more information about these parameters, check the Zabbix API * documentation at https://www.zabbix.com/documentation/. * * The $arrayKeyProperty can be used to get an associative instead of an @@ -571,25 +499,89 @@ final public function userLogout($params=array(), $arrayKeyProperty='') * is any property of the returned JSON objects (e.g. "name", "host", * "hostid", "graphid", "screenitemid"). * - * @param $params Zabbix API parameters. - * @param $arrayKeyProperty Object property for key of array. + * @param mixed $params Zabbix API parameters + * @param string $arrayKeyProperty Object property for key of array * - * @retval stdClass + * @throws Exception * - * @throws Exception + * @return mixed */ - - public function ($params=array(), $arrayKeyProperty='') + public function ($params = array(), $arrayKeyProperty = '') { // get params array for request $params = $this->getRequestParamsArray($params); // check if we've to authenticate - $auth = in_array('', self::$anonymousFunctions) ? FALSE : TRUE; + $auth = !in_array('', self::$anonymousFunctions, true); // request return $this->request('', $params, $arrayKeyProperty, $auth); } - + + /** + * Converts an indexed array to an associative array. + * + * @param array $objectArray Indexed array with objects + * @param string $useObjectProperty Object property to use as array key + * + * @return array associative array + */ + private function convertToAssociatveArray(array $objectArray, $useObjectProperty) + { + // sanity check + if (empty($objectArray) || !property_exists($objectArray[0], $useObjectProperty)) { + return $objectArray; + } + + // loop through array and replace keys + $newObjectArray = array(); + foreach ($objectArray as $key => $object) { + $newObjectArray[$object->{$useObjectProperty}] = $object; + } + + // return associative array + return $newObjectArray; + } + + /** + * Returns a params array for the request. + * + * This method will automatically convert all provided types into a correct + * array. Which means: + * + * - arrays will not be converted (indexed & associative) + * - scalar values will be converted into an one-element array (indexed) + * - other values will result in an empty array + * + * Afterwards the array will be merged with all default params, while the + * default params have a lower priority (passed array will overwrite default + * params). But there is an Exception for merging: If the passed array is an + * indexed array, the default params will not be merged. This is because + * there are some API methods, which are expecting a simple JSON array (aka + * PHP indexed array) instead of an object (aka PHP associative array). + * Example for this behavior are delete operations, which are directly + * expecting an array of IDs '[ 1,2,3 ]' instead of '{ ids: [ 1,2,3 ] }'. + * + * @param mixed $params Params array + * + * @return array + */ + private function getRequestParamsArray($params) + { + if (is_scalar($params)) { + // if params is a scalar value, turn it into an array + $params = array($params); + } elseif (!is_array($params)) { + // if params isn't an array, create an empty one (e.g. for booleans, null) + $params = array(); + } + // if array isn't indexed, merge array with default params + if (empty($params) || array_keys($params) !== range(0, count($params) - 1)) { + $params = array_merge($this->getDefaultParams(), $params); + } + + // return params + return $params; + } } diff --git a/build/templates/concrete.tpl.php b/build/templates/concrete.tpl.php index 77f4fae..1049e97 100644 --- a/build/templates/concrete.tpl.php +++ b/build/templates/concrete.tpl.php @@ -1,10 +1,6 @@ - * @brief Class file for the implementation of the class . - * - * Implement your customizations in this file. - * + +/* * This file is part of PhpZabbixApi. * * Permission is hereby granted, free of charge, to any person obtaining a copy @@ -25,17 +21,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @copyright The MIT License (MIT) - * @author confirm IT solutions GmbH, Rathausstrase 14, CH-6340 Baar + * @copyright The MIT License (MIT) + * @author confirm IT solutions GmbH, Rathausstrase 14, CH-6340 Baar */ namespace ZabbixApi; /** - * @brief Concrete class for the Zabbix API. + * Concrete class for the Zabbix API. */ - class extends { - } diff --git a/build/templates/exception.tpl.php b/build/templates/exception.tpl.php index 7970d76..0a8856d 100644 --- a/build/templates/exception.tpl.php +++ b/build/templates/exception.tpl.php @@ -1,21 +1,6 @@ - * - * @brief Class file for the implementation of the class . - * - * __ ___ ____ _ _ ___ _ _ ____ - * \ \ / / \ | _ \| \ | |_ _| \ | |/ ___| - * \ \ /\ / / _ \ | |_) | \| || || \| | | _ - * \ V V / ___ \| _ <| |\ || || |\ | |_| | - * \_/\_/_/ \_\_| \_\_| \_|___|_| \_|\____| - * - * This class was automatically generated by the PhpZabbixApi builder script, - * and will be replaced as soon as the script is invoked again, or you're about - * to update the PhpZabbixApi version. Therefor do not modify this file and - * leave it as it is. After updating / regenerating the library, this file will - * be overwritten, and all modifications will be lost. - * + +/* * This file is part of PhpZabbixApi. * * Permission is hereby granted, free of charge, to any person obtaining a copy @@ -36,16 +21,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @copyright The MIT License (MIT) - * @author confirm IT solutions GmbH, Rathausstrase 14, CH-6340 Baar + * @copyright The MIT License (MIT) + * @author confirm IT solutions GmbH, Rathausstrase 14, CH-6340 Baar */ namespace ZabbixApi; /** - * @brief Exception class for ZabbixApi namespace. + * Exception class for ZabbixApi namespace. */ - class Exception extends \Exception { } diff --git a/composer.json b/composer.json index 745ad42..3edc7a2 100644 --- a/composer.json +++ b/composer.json @@ -17,7 +17,8 @@ "php": "^5.3|^7.0" }, "require-dev": { - "phpunit/phpunit": "<4.8.35|<5.4.3,>=5.0" + "phpunit/phpunit": "<4.8.35|<5.4.3,>=5.0", + "friendsofphp/php-cs-fixer": "^1.13|^2.16" }, "autoload": { "psr-4": { "ZabbixApi\\": ["src/"] } diff --git a/tests/ZabbixApiTest.php b/tests/ZabbixApiTest.php index 592e63d..47b99c8 100644 --- a/tests/ZabbixApiTest.php +++ b/tests/ZabbixApiTest.php @@ -1,5 +1,30 @@