From 2da3ec10a0f2662774de007bba9b0ad25d7c7ed9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Demirta=C5=9F?= Date: Tue, 12 Oct 2021 01:21:37 +0300 Subject: [PATCH 01/22] First commit for new version of Jotform PHP API --- .editorconfig | 15 + .github/FUNDING.yml | 1 + .github/SECURITY.yml | 3 + .github/workflows/php-cs-fixer.yml | 23 + .github/workflows/run-tests.yml | 37 + .gitignore | 12 + .php-cs-fixer.dist.php | 39 + JotForm.php | 664 +----------------- README.md | 228 +++--- composer.json | 28 +- phpunit.xml.dist | 34 + src/Exceptions/InvalidKeyException.php | 11 + src/Exceptions/JotformException.php | 7 + .../ServiceUnavailableException.php | 11 + src/Jotform.php | 64 ++ src/JotformClient.php | 220 ++++++ src/JotformResponse.php | 49 ++ src/Services/Folder.php | 31 + src/Services/Form.php | 190 +++++ src/Services/Report.php | 36 + src/Services/Service.php | 19 + src/Services/Submission.php | 78 ++ src/Services/System.php | 21 + src/Services/User.php | 86 +++ src/Traits/UseConditions.php | 46 ++ src/Traits/UseQuery.php | 54 ++ tests/FolderTest.php | 17 + tests/FormTest.php | 16 + tests/ReportTest.php | 20 + tests/SubmissionTest.php | 26 + tests/SystemTest.php | 41 ++ tests/TestCase.php | 23 + tests/UserTest.php | 27 + 33 files changed, 1405 insertions(+), 772 deletions(-) create mode 100644 .editorconfig create mode 100644 .github/FUNDING.yml create mode 100644 .github/SECURITY.yml create mode 100644 .github/workflows/php-cs-fixer.yml create mode 100644 .github/workflows/run-tests.yml create mode 100644 .gitignore create mode 100644 .php-cs-fixer.dist.php create mode 100644 phpunit.xml.dist create mode 100644 src/Exceptions/InvalidKeyException.php create mode 100644 src/Exceptions/JotformException.php create mode 100644 src/Exceptions/ServiceUnavailableException.php create mode 100644 src/Jotform.php create mode 100644 src/JotformClient.php create mode 100644 src/JotformResponse.php create mode 100644 src/Services/Folder.php create mode 100644 src/Services/Form.php create mode 100644 src/Services/Report.php create mode 100644 src/Services/Service.php create mode 100644 src/Services/Submission.php create mode 100644 src/Services/System.php create mode 100644 src/Services/User.php create mode 100644 src/Traits/UseConditions.php create mode 100644 src/Traits/UseQuery.php create mode 100644 tests/FolderTest.php create mode 100644 tests/FormTest.php create mode 100644 tests/ReportTest.php create mode 100644 tests/SubmissionTest.php create mode 100644 tests/SystemTest.php create mode 100644 tests/TestCase.php create mode 100644 tests/UserTest.php diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..665acc3 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +root = true + +[*] +charset = utf-8 +indent_size = 4 +indent_style = space +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false + +[*.{yml,yaml}] +indent_size = 2 \ No newline at end of file diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..fcd2991 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +github: :jotform-api-php diff --git a/.github/SECURITY.yml b/.github/SECURITY.yml new file mode 100644 index 0000000..15e17cf --- /dev/null +++ b/.github/SECURITY.yml @@ -0,0 +1,3 @@ +# Security Policy + +If you discover any security related issues, please email api@jotform.com instead of using the issue tracker. \ No newline at end of file diff --git a/.github/workflows/php-cs-fixer.yml b/.github/workflows/php-cs-fixer.yml new file mode 100644 index 0000000..584dc55 --- /dev/null +++ b/.github/workflows/php-cs-fixer.yml @@ -0,0 +1,23 @@ +name: Check & fix styling + +on: [push] + +jobs: + php-cs-fixer: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v2 + with: + ref: ${{ github.head_ref }} + + - name: Run PHP CS Fixer + uses: docker://oskarstark/php-cs-fixer-ga + with: + args: --config=.php-cs-fixer.dist.php --allow-risky=yes + + - name: Commit changes + uses: stefanzweifel/git-auto-commit-action@v4 + with: + commit_message: Fix syntax styling \ No newline at end of file diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml new file mode 100644 index 0000000..edc2f41 --- /dev/null +++ b/.github/workflows/run-tests.yml @@ -0,0 +1,37 @@ +name: Tests + +on: [push, pull_request] + +jobs: + test: + runs-on: ${{ matrix.os }} + strategy: + fail-fast: true + matrix: + os: [ubuntu-latest, windows-latest] + php: [7.3, 8.0] + stability: [prefer-lowest, prefer-stable] + + name: P${{ matrix.php }} - ${{ matrix.stability }} - ${{ matrix.os }} + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, fileinfo + coverage: none + + - name: Setup problem matchers + run: | + echo "::add-matcher::${{ runner.tool_cache }}/php.json" + echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" + + - name: Install dependencies + run: composer update --${{ matrix.stability }} --prefer-dist --no-interaction + + - name: Execute tests + run: composer test \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d687012 --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +.idea +.vscode +.php_cs +.php_cs.cache +.phpunit.result.cache +build +composer.lock +coverage +docs +phpunit.xml +vendor +.php-cs-fixer.cache \ No newline at end of file diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 0000000..33b3b63 --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,39 @@ +in([ + __DIR__ . '/src', + __DIR__ . '/tests', + ]) + ->name('*.php') + ->ignoreDotFiles(true) + ->ignoreVCS(true); + +return (new PhpCsFixer\Config()) + ->setRules([ + '@PSR12' => true, + 'array_syntax' => ['syntax' => 'short'], + 'ordered_imports' => ['sort_algorithm' => 'alpha'], + 'no_unused_imports' => true, + 'not_operator_with_successor_space' => true, + 'trailing_comma_in_multiline' => true, + 'phpdoc_scalar' => true, + 'unary_operator_spaces' => true, + 'binary_operator_spaces' => true, + 'blank_line_before_statement' => [ + 'statements' => ['break', 'continue', 'declare', 'return', 'throw', 'try'], + ], + 'phpdoc_single_line_var_spacing' => true, + 'phpdoc_var_without_name' => true, + 'class_attributes_separation' => [ + 'elements' => [ + 'method' => 'one', + ], + ], + 'method_argument_space' => [ + 'on_multiline' => 'ensure_fully_multiline', + 'keep_multiple_spaces_after_comma' => true, + ], + 'single_trait_insert_per_statement' => true, + ]) + ->setFinder($finder); \ No newline at end of file diff --git a/JotForm.php b/JotForm.php index 836367a..5224f63 100644 --- a/JotForm.php +++ b/JotForm.php @@ -2,656 +2,22 @@ /** * JotForm API - PHP Client * - * @copyright 2013 Interlogy, LLC. - * @link http://www.jotform.com - * @version 1.0 - * @package JotFormAPI + * @copyright 2021 Jotform, LLC. + * @link https://www.jotform.com + * @version 2.0 + * @package Jotform */ -class JotForm { - public $baseURL = 'https://api.jotform.com'; - private $apiKey; - private $debugMode; - private $outputType; - private $apiVersion = 'v1'; - - public function __construct($apiKey = '', $outputType = 'json', $debugMode = false) { - - $this->apiKey = $apiKey; - $this->debugMode = $debugMode; - $this->outputType = strtolower($outputType); - $user = $this->getUser(); - # set base url for EU users - if (isset($user['euOnly'])) { - $this->baseURL = 'https://eu-api.jotform.com'; - } - } - - public function __get($property) { - if (property_exists($this, $property)) { - return $this->$property; - } - } - - public function __set($property, $value) { - if (property_exists($this, $property)) { - $this->$property = $value; - } - } - - private function _debugLog($str) { - if ($this->debugMode){ - print_r(PHP_EOL); - print_r($str); - } - } - - private function _debugDump($obj) { - if ($this->debugMode){ - print_r(PHP_EOL); - var_dump($obj); - } - } - - private function _executeHttpRequest($path, $params = array(), $method) { - if ($this->outputType != 'json') { - $path = "{$path}.xml"; - } - - $url = implode('/', array($this->baseURL, $this->apiVersion, $path)); - - $this->_debugDump($params); - - if ($method == 'GET' && $params != null){ - $params_array = array(); - foreach ($params as $key => $value) { - $params_array[] = "{$key}={$value}"; - } - $params_string = '?' . implode('&', $params_array); - unset($params_array); - $url = $url.$params_string; - $this->_debugLog('params string: '.$params_string); - } - - $this->_debugLog('fetching url: '.$url); - - $ch = curl_init(); - - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_USERAGENT, 'JOTFORM_PHP_WRAPPER'); - curl_setopt($ch, CURLOPT_HTTPHEADER, array('APIKEY: '.$this->apiKey)); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); - - switch ($method) { - case 'POST': - $this->_debugLog('posting'); - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, $params); - break; - case 'PUT': - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); - curl_setopt($ch, CURLOPT_POSTFIELDS, $params); - break; - case 'DELETE': - $this->_debugLog('delete'); - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); - break; - } - - $result = curl_exec($ch); - - if ($result == false) { - throw new Exception(curl_error($ch), 400); - } - - $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE); - $this->_debugLog('http code is: '.$http_status); - - if ($this->outputType == 'json') { - $result_obj = json_decode($result, true); - } else { - $result_obj = utf8_decode($result); - } - - if ($http_status != 200) { - - switch ($http_status) { - case 400: - case 403: - case 404: - throw new JotFormException($result_obj["message"], $http_status ); - break; - case 401: - throw new JotFormException("Invalid API key or Unauthorized API call", $http_status); - break; - case 503: - throw new JotFormException("Service is unavailable, rate limits etc exceeded!", $http_status); - break; - - default: - throw new JotFormException($result_obj["info"], $http_status); - break; - } - } - - curl_close($ch); - - if ($this->outputType == 'json') { - if (isset($result_obj['content'])) { - return $result_obj['content']; - } else { - return $result_obj; - } - } else { - return $result_obj; - } - } - - private function _executeGetRequest($url, $params = array()) { - return $this->_executeHttpRequest($url, $params, 'GET'); - } - - private function _executePostRequest($url, $params) { - return $this->_executeHttpRequest($url, $params, 'POST'); - } - - private function _executePutRequest($url, $params) { - return $this->_executeHttpRequest($url, $params, 'PUT'); - } - - private function _executeDeleteRequest($url, $params = array()) { - return $this->_executeHttpRequest($url, $params, 'DELETE'); - } - - private function createConditions($offset, $limit, $filter, $orderby) { - $params = array(); - foreach (array('offset', 'limit', 'filter', 'orderby') as $arg) { - if (${$arg}) { - $params[strtolower($arg)] = ${$arg}; - if ($arg == "filter") { - $params[$arg] = urlencode(json_encode($params[$arg])); - } - } - } - return $params; - } - - private function createHistoryQuery($action, $date, $sortBy, $startDate, $endDate) { - foreach (array('action', 'date', 'sortBy', 'startDate', 'endDate') as $arg) { - if (${$arg}) { - $params[$arg] = ${$arg}; - } - } - return $params; - } - - /** - * [getUser Get user account details for a JotForm user] - * @return [array] [Returns user account type, avatar URL, name, email, website URL and account limits.] - */ - public function getUser() { - $res = $this->_executeGetRequest('user'); - return $res; - } - - /** - * [getUserUsage Get number of form submissions received this month] - * @return [array] [Returns number of submissions, number of SSL form submissions, payment form submissions and upload space used by user.] - */ - public function getUsage(){ - return $this->_executeGetRequest('user/usage'); - } - - /** - * [getForms Get a list of forms for this account] - * @param [integer] $offset [Start of each result set for form list. (optional)] - * @param [integer] $limit [Number of results in each result set for form list. (optional)] - * @param [array] $filter [Filters the query results to fetch a specific form range.(optional)] - * @param [string] $orderBy [Order results by a form field name. (optional)] - * @return [array] [Returns basic details such as title of the form, when it was created, number of new and total submissions.] - */ - public function getForms($offset = 0, $limit = 0, $filter = null, $orderby = null) { - $params = $this->createConditions($offset, $limit, $filter, $orderby); - return $this->_executeGetRequest('user/forms', $params); - } - - /** - * [getSubmissions Get a list of submissions for this account] - * @param [int] $offset [Start of each result set for form list. (optional)] - * @param [int] $limit [Number of results in each result set for form list. (optional)] - * @param [array] $filter [Filters the query results to fetch a specific form range.(optional)] - * @param [string] $orderBy [Order results by a form field name. (optional)] - * @return [array] [Returns basic details such as title of the form, when it was created, number of new and total submissions.] - */ - public function getSubmissions($offset = 0, $limit = 0, $filter = null, $orderby = null) { - $params = $this->createConditions($offset, $limit, $filter, $orderby); - return $this->_executeGetRequest('user/submissions', $params); - } - - /** - * [getUserSubusers Get a list of sub users for this account] - * @return [array] [Returns list of forms and form folders with access privileges.] - */ - public function getSubusers() { - return $this->_executeGetRequest('user/subusers'); - } - - /** - * [getUserFolders Get a list of form folders for this account] - * @return [array] [Returns name of the folder and owner of the folder for shared folders.] - */ - public function getFolders() { - return $this->_executeGetRequest('user/folders'); - } - - /** - * [getReports List of URLS for reports in this account] - * @return [array] [Returns reports for all of the forms. ie. Excel, CSV, printable charts, embeddable HTML tables.] - */ - public function getReports() { - return $this->_executeGetRequest('user/reports'); - } - - /** - * [getSettings Get user's settings for this account] - * @return [array] [Returns user's time zone and language.] - */ - public function getSettings() { - return $this->_executeGetRequest('user/settings'); - } - - /** - * [updateSettings Update user's settings] - * @param [array] $settings [New user setting values with setting keys] - * @return [array] [Returns changes on user settings] - */ - public function updateSettings($settings) { - return $this->_executePostRequest('user/settings', $settings); - } - - /** - * [getHistory Get user activity log] - * @param [enum] $action [Filter results by activity performed. Default is 'all'.] - * @param [enum] $date [Limit results by a date range. If you'd like to limit results by specific dates you can use startDate and endDate fields instead.] - * @param [enum] $sortBy [Lists results by ascending and descending order.] - * @param [string] $startDate [Limit results to only after a specific date. Format: MM/DD/YYYY.] - * @param [string] $endDate [Limit results to only before a specific date. Format: MM/DD/YYYY.] - * @return [array] [Returns activity log about things like forms created/modified/deleted, account logins and other operations.] - */ - public function getHistory($action = null, $date = null, $sortBy = null, $startDate = null, $endDate = null) { - $params = $this->createHistoryQuery($action, $date, $sortBy, $startDate, $endDate); - return $this->_executeGetRequest('user/history', $params); - } - - /** - * [getForm Get basic information about a form.] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @return [array] [Returns form ID, status, update and creation dates, submission count etc.] - */ - public function getForm($formID) { - return $this->_executeGetRequest('form/'. $formID); - } - - /** - * [getFormQuestions Get a list of all questions on a form.] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @return [array] [Returns question properties of a form.] - */ - public function getFormQuestions($formID) { - return $this->_executeGetRequest("form/{$formID}/questions"); - } - - /** - *[getFormQuestion Get details about a question] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [integer] $qid [Identifier for each question on a form. You can get a list of question IDs from /form/{id}/questions.] - * @return [array] [Returns question properties like required and validation.] - */ - public function getFormQuestion($formID, $qid) { - return $this->_executeGetRequest("form/{$formID}/question/{$qid}"); - } - - /** - * [getFormSubmissions List of a form submissions] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [int] $offset [Start of each result set for form list. (optional)] - * @param [int] $limit [Number of results in each result set for form list. (optional)] - * @param [array] $filter [Filters the query results to fetch a specific form range.(optional)] - * @param [string] $orderBy [Order results by a form field name. (optional)] - * @return [array] [Returns submissions of a specific form.] - */ - public function getFormSubmissions($formID, $offset = 0, $limit = 0, $filter = null, $orderby = null) { - $params = $this->createConditions($offset, $limit, $filter, $orderby); - return $this->_executeGetRequest("form/{$formID}/submissions", $params); - } - - /** - * [createFormSubmissions Submit data to this form using the API] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [array] $submission [Submission data with question IDs.] - * @return [array] [Returns posted submission ID and URL.] - */ - public function createFormSubmission($formID, $submission) { - $sub = array(); - foreach ($submission as $key => $value) { - if (strpos($key, '_')) { - $qid = substr($key, 0, strpos($key, '_')); - $type = substr($key, strpos($key, '_') + 1); - $sub["submission[{$qid}][{$type}]"] = $value; - } else { - $sub["submission[{$key}]"] = $value; - } - } - return $this->_executePostRequest("form/{$formID}/submissions", $sub); - } - - /** - * [createFormSubmissions Submit data to this form using the API] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [json] $submissions [Submission data with question IDs.] - * @return [array] - */ - public function createFormSubmissions($formID, $submissions) { - return $this->_executePutRequest("form/".$formID."/submissions", $submissions); - } - - /** - * [getFormFiles List of files uploaded on a form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @return [array] [Returns uploaded file information and URLs on a specific form.] - */ - public function getFormFiles($formID) { - return $this->_executeGetRequest("form/{$formID}/files"); - } - - /** - * [getFormWebhooks Get list of webhooks for a form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @return [array] [Returns list of webhooks for a specific form.] - */ - public function getFormWebhooks($formID) { - return $this->_executeGetRequest("form/{$formID}/webhooks"); - } - - /** - * [createFormWebhook Add a new webhook] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [string] $webhookURL [Webhook URL is where form data will be posted when form is submitted.] - * @return [array] [Returns list of webhooks for a specific form.] - */ - public function createFormWebhook($formID, $webhookURL) { - return $this->_executePostRequest("form/{$formID}/webhooks", array('webhookURL' => $webhookURL) ); - } - - /** - * [deleteFormWebhook] [Delete a specific webhook of a form.] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [integer] $webhookID [You can get webhook IDs when you call /form/{formID}/webhooks.] - * @return [array] [Returns remaining webhook URLs of form.] - */ - public function deleteFormWebhook($formID, $webhookID) { - return $this->_executeDeleteRequest("form/{$formID}/webhooks/{$webhookID}", null); - } - - /** - * [getSubmission Get submission data] - * @param [integer] $sid [You can get submission IDs when you call /form/{id}/submissions.] - * @return [array] [Returns information and answers of a specific submission.] - */ - public function getSubmission($sid) { - return $this->_executeGetRequest("submission/{$sid}"); - } - - /** - * [getReport Get report details] - * @param [integer] $reportID [You can get a list of reports from /user/reports.] - * @return [array] [Returns properties of a speceific report like fields and status.] - */ - public function getReport($reportID) { - return $this->_executeGetRequest("report/{$reportID}"); - } - - /** - * [getFolder Get folder details] - * @param [integer] $folderID [You can get a list of folders from /user/folders.] - * @return [array] [Returns a list of forms in a folder, and other details about the form such as folder color.] - */ - public function getFolder($folderID) { - return $this->_executeGetRequest("folder/{$folderID}"); - } - - /** - * [getFormProperties Get a list of all properties on a form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @return [array] [Returns form properties like width, expiration date, style etc.] - */ - public function getFormProperties($formID) { - return $this->_executeGetRequest("form/{$formID}/properties"); - } - - /** - * [getFormProperty Get a specific property of the form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [string] $propertyKey [You can get property keys when you call /form/{id}/properties.] - * @return [array] [Returns given property key value.] - */ - public function getFormProperty($formID, $propertyKey) { - return $this->_executeGetRequest("form/{$formID}/properties/{$propertyKey}"); - } - - /** - * [getFormReports Get all the reports of a form, such as excel, csv, grid, html, etc.] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @return [array] [Returns a list of reports in a form, and other details about the reports such as title.] - */ - public function getFormReports($formID) { - return $this->_executeGetRequest("form/{$formID}/reports"); - } - - /** - * [createReport Create new report of a form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [array] $report [Report details. List type, title etc.] - * @return [array] [Returns report details and URL.] - */ - public function createReport($formID, $report) { - return $this->_executePostRequest("form/{$formID}/reports", $report); - } - - /** - * [deleteSubmission Delete a single submission] - * @param [integer] $sid [You can get submission IDs when you call /user/submissions.] - * @return [array] [Returns status of request.] - */ - public function deleteSubmission($sid) { - return $this->_executeDeleteRequest("submission/{$sid}"); - } - - /** - * [editSubmission Edit a single submission] - * @param [integer] $sid [You can get submission IDs when you call /form/{id}/submissions.] - * @param [array] $submission [New submission data with question IDs.] - * @return [array] [Returns status of request.] - */ - public function editSubmission($sid, $submission) { - $sub = array(); - foreach ($submission as $key => $value) { - if (strpos($key, '_') && $key != 'created_at') { - $qid = substr($key, 0, strpos($key, '_')); - $type = substr($key, strpos($key, '_') + 1); - $sub["submission[{$qid}][{$type}]"] = $value; - } else { - $sub["submission[{$key}]"] = $value; - } - } - return $this->_executePostRequest("submission/".$sid, $sub); - } - - /** - * [cloneForm Clone a single form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @return [array] [Returns status of request.] - */ - public function cloneForm($formID) { - return $this->_executePostRequest("form/{$formID}/clone", null); - } - - /** - * [deleteFormQuestion Delete a single form question] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [integer] $qid [Identifier for each question on a form. You can get a list of question IDs from /form/{id}/questions.] - * @return [array] [Returns status of request.] - */ - public function deleteFormQuestion($formID, $qid) { - return $this->_executeDeleteRequest("form/{$formID}/question/{$qid}", null); - } - - /** - * [createFormQuestion Add new question to specified form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [array] $question [New question properties like type and text.] - * @return [array] [Returns properties of new question.] - */ - public function createFormQuestion($formID, $question) { - $params = array(); - foreach ($question as $key => $value) { - $params["question[{$key}]"] = $value; +spl_autoload_register(function ($class) { + $paths = [ + __DIR__ . '/src', + __DIR__ . '/src/Services', + __DIR__ . '/src/Traits', + __DIR__ . '/src/Exceptions', + ]; + foreach ($paths as $path) { + if (is_readable($file = "{$path}/{$class}.php")) { + include_once($file); } - return $this->_executePostRequest("form/{$formID}/questions", $params); - } - - /** - * [createFormQuestions Add new questions to specified form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [json] $questions [New question properties like type and text.] - * @return [array] [Returns properties of new questions.] - */ - public function createFormQuestions($formID, $questions) { - return $this->_executePutRequest("form/{$formID}/questions", $questions); - } - - /** - * [editFormQuestion Add or edit a single question properties] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [integer] $qid [Identifier for each question on a form. You can get a list of question IDs from /form/{id}/questions.] - * @param [array] $questionProperties [New question properties like text and order.] - * @return [array] [Returns edited property and type of question.] - */ - public function editFormQuestion($formID, $qid, $questionProperties) { - $question = array(); - foreach ($questionProperties as $key => $value) { - $question["question[{$key}]"] = $value; - } - return $this->_executePostRequest("form/{$formID}/question/{$qid}", $question); - } - - /** - * [setFormProperties Add or edit properties of a specific form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [array] $formProperties [New properties like label width.] - * @return [array] [Returns edited properties.] - */ - public function setFormProperties($formID, $formProperties) { - $properties = array(); - foreach ($formProperties as $key => $value) { - $properties["properties[{$key}]"] = $value; - } - return $this->_executePostRequest("form/{$formID}/properties", $properties); - } - - /** - *[setMultipleFormProperties Add or edit properties of a specific form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [json] $formProperties [New properties like label width.] - * @return [array] [Returns edited properties.] - */ - public function setMultipleFormProperties($formID, $formProperties) { - return $this->_executePutRequest("form/{$formID}/properties", $formProperties); } - - /** - * [createForm Create a new form] - * @param [array] $form [Questions, properties and emails of new form.] - * @return [array] [Returns new form.] - */ - public function createForm($form) { - $params = array(); - foreach ($form as $key => $value) { - foreach ($value as $k => $v) { - if ($key == "properties") { - $params["{$key}[{$k}]"] = $v; - } else { - foreach ($v as $a => $b) { - $params["{$key}[{$k}][{$a}]"] = $b; - } - } - } - } - return $this->_executePostRequest('user/forms', $params); - } - - /** - * [createForm Create new forms] - * @param [json] $form [Questions, properties and emails of forms.] - * @return [array] [Returns new forms.] - */ - public function createForms($forms) { - return $this->_executePutRequest('user/forms', $forms); - } - - /** - * [deleteForm Delete a specific form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @return [array] [Returns roperties of deleted form.] - */ - public function deleteForm($formID) { - return $this->_executeDeleteRequest("form/{$formID}", null); - } - - /** - * [registerUser Register with username, password and email] - * @param [array] $userDetails [username, password and email to register a new user] - * @return [array] [Returns new user's details] - */ - public function registerUser($userDetails) { - return $this->_executePostRequest('user/register', $userDetails); - } - - /** - * [loginUser Login user with given credentials] - * @param [array] $credentials [Username, password, application name and access type of user] - * @return [array] [Returns logged in user's settings and app key.] - */ - public function loginUser($credentials) { - return $this->_executePostRequest('user/login', $credentials); - } - - /** - * [logoutUser Logout User] - * @return [array] [Status of request] - */ - public function logoutUser() { - return $this->_executeGetRequest('user/logout'); - } - - /** - * [getPlan Get details of a plan] - * @param [string] $planName [Name of the requested plan. FREE, PREMIUM etc.] - * @return [array] [Returns details of a plan] - */ - public function getPlan($planName) { - return $this->_executeGetRequest("system/plan/{$planName}"); - } - - /** - * [deleteReport Delete a specific report] - * @param [integer] $formID [$reportID [You can get a list of reports from /user/reports.] - * @return [array] [Returns status of request.] - */ - public function deleteReport($reportID) { - return $this->_executeDeleteRequest("report/{$reportID}", null); - } -} - -class JotFormException extends Exception {} +}); diff --git a/README.md b/README.md index 5c96746..963a893 100644 --- a/README.md +++ b/README.md @@ -3,157 +3,153 @@ jotform-api-php [JotForm API](http://api.jotform.com/docs/) - PHP Client -### Installation +## Installation -Install via git clone: - - $ git clone git://github.com/jotform/jotform-api-php.git - $ cd jotform-api-php +1- Install via [Composer](http://getcomposer.org/) -or +``` +$ composer require jotform/jotform-api-php +``` +and add following line to your php file: +```php +require "vendor/autoload.php"; +``` -Install via Composer package manager (http://getcomposer.org/) - -_composer.json_ -```json - { - "require": { - "jotform/jotform-api-php": "dev-master" - } - } +2- Install and use manually: +``` +$ git clone https://github.com/jotform/jotform-api-php.git ``` +and add following line to your php file: +```php +require "jotform-api-php/Jotform.php"; +``` +If you install the package into another directory, you should update path for `require` command above. - $ php composer.phar install -### Documentation +## Documentation -You can find the docs for the API of this client at [http://api.jotform.com/docs/](http://api.jotform.com/docs) +You can find the docs for the API of this client at [Jotform API Documentation](http://api.jotform.com/docs). -### Authentication +## Authentication -JotForm API requires API key for all user related calls. You can create your API Keys at [API section](http://www.jotform.com/myaccount/api) of My Account page. +JotForm API requires API key for all user related calls. You can create your API Keys at [API section](http://www.jotform.com/myaccount/api) of My Account page. -### Examples +## Examples -Print all forms of the user - +1- Print all forms of the user: ```php getForms(); - - foreach ($forms as $form) { - print $form["title"]; - } +require "vendor/autoload.php"; -?> -``` -Get submissions of the latest form - +use Jotform\Jotform; +use Jotform\JotformClient; + +$client = new JotformClient(""); +$jotform = new Jotform($client); + +$forms = $jotform->user()->forms(); +foreach ($forms->toArray() as $form) { + echo $form["title"] . PHP_EOL; +} +``` + +2- Get submissions of the latest form: ```php getForms(0, 1, null, null); +require 'vendor/autoload.php'; - $latestForm = $forms[0]; +use Jotform\Jotform; +use Jotform\JotformClient; - $latestFormID = $latestForm["id"]; +try { + $client = new JotformClient(''); + $jotform = new Jotform($client); - $submissions = $jotformAPI->getFormSubmissions($latestFormID); + $forms = $jotform->user()->forms()->toArray(); + $latestForm = $forms[0]; + $latestFormId = $latestForm['id']; - var_dump($submissions); - - } - catch (Exception $e) { - var_dump($e->getMessage()); - } - -?> + $submissions = $jotform->form($latestFormId)->getSubmissions(); + var_dump($submissions); +} +catch (Exception $e) { + var_dump($e->getMessage()); +} ``` -Get latest 100 submissions ordered by creation date - +3- Get latest 100 submissions ordered by creation date: ```php -getSubmissions(0, 100, null, "created_at"); +require 'vendor/autoload.php'; - var_dump($submissions); - } - catch (Exception $e) { - var_dump($e->getMessage()); - } - -?> +use Jotform\Jotform; +use Jotform\JotformClient; + +try { + $client = new JotformClient(''); + $jotform = new Jotform($client); + + $submissions = $jotform->user()->limit(100)->orderBy('created_at')->submissions(); + var_dump($submissions); +} catch (Exception $e) { + var_dump($e->getMessage()); +} ``` -Submission and form filter examples - +4- Submission and form filter examples: ```php - "239252191641336722", - "created_at:gt" => "2013-07-09 07:48:34", - ); - - $subs = $jotformAPI->getSubmissions(0, 0, $filter, ""); - var_dump($subs); - - $filter = array( - "id:gt" => "239176717911737253", - ); - - $formSubs = $jotformAPI->getForms(0, 0, 2, $filter); - var_dump($formSubs); - } catch (Exception $e) { - var_dump($e->getMessage()); - } +require 'vendor/autoload.php'; + +use Jotform\Jotform; +use Jotform\JotformClient; + +try { + $client = new JotformClient(''); + $jotform = new Jotform($client); -?> -``` + $filter = [ + "id:gt" => "239252191641336722", + "created_at:gt" => "2013-07-09 07:48:34", + ]; -Delete last 50 submissions + $submissions = $jotform->user()->filter($filter)->submissions(); + var_dump($submissions); + + $filter = [ + "id:gt" => "239176717911737253", + ]; + + $forms = $jotform->user()->filter($filter)->forms(); + var_dump($forms); +} catch (Exception $e) { + var_dump($e->getMessage()); +} +``` +5- Delete last 50 submissions: ```php -getSubmissions(0, 50, null, null); +require 'vendor/autoload.php'; - foreach ($submissions as $submission) { - $result = $jotformAPI->deleteSubmission($submission["id"]); - print $result; - } - } - catch (Exception $e) { - var_dump($e->getMessage()); +use Jotform\Jotform; +use Jotform\JotformClient; + +try { + $client = new JotformClient(''); + $jotform = new Jotform($client); + + $submissions = $jotform->user()->limit(50)->orderBy('created_at')->submissions(); + foreach ($submissions->toArray() as $submission) { + $result = $jotform->submission($submission["id"])->delete(); + echo $result . PHP_EOL; } - -?> -``` - -First the _JotForm_ class is included from the _jotform-api-php/JotForm.php_ file. This class provides access to JotForm's API. You have to create an API client instance with your API key. -In case of an exception (wrong authentication etc.), you can catch it or let it fail with a fatal error. +} +catch (Exception $e) { + var_dump($e->getMessage()); +} +``` +--- +Jotform diff --git a/composer.json b/composer.json index 9f25b8b..d760733 100644 --- a/composer.json +++ b/composer.json @@ -1,18 +1,32 @@ { "name": "jotform/jotform-api-php", - "version" : "1.0.0-dev", "license": "GPL-3.0+", - "homepage": "http://api.jotform.com", + "homepage": "https://api.jotform.com", "support": { "email": "api@jotform.com", - "wiki": "http://api.jotform.com" + "wiki": "https://api.jotform.com" }, "require": { - "php": ">=5.3.0" + "php": "^7.3|^8.0", + "ext-curl": "*" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^3.0", + "phpunit/phpunit": "^9.5" }, "autoload": { - "classmap": [ - "JotForm.php" - ] + "psr-4": { + "Jotform\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Tests\\": "tests" + } + }, + "scripts": { + "test": "vendor/bin/phpunit", + "coverage": "vendor/bin/phpunit --coverage-html coverage", + "format": "vendor/bin/php-cs-fixer fix --allow-risky=yes" } } diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..1aa095f --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,34 @@ + + + + + ./tests + + + + + ./src + + + + + + \ No newline at end of file diff --git a/src/Exceptions/InvalidKeyException.php b/src/Exceptions/InvalidKeyException.php new file mode 100644 index 0000000..c982064 --- /dev/null +++ b/src/Exceptions/InvalidKeyException.php @@ -0,0 +1,11 @@ +client = $client; + + // Check 'euOnly' flag for User while initializing. + if ($euCheck) { + $user = $this->user()->get()->toArray(); + if (isset($user['euOnly'])) { + $this->client->europeOnly(true); + } + } + } + + public function europeOnly(bool $europeOnly): void + { + $this->client->europeOnly($europeOnly); + } + + public function user(): User + { + return new User($this->client); + } + + public function form(string $formId): Form + { + return new Form($this->client, $formId); + } + + public function submission(string $submissionId): Submission + { + return new Submission($this->client, $submissionId); + } + + public function report(string $reportId): Report + { + return new Report($this->client, $reportId); + } + + public function folder(string $folderId): Folder + { + return new Folder($this->client, $folderId); + } + + public function system(): System + { + return new System($this->client); + } +} diff --git a/src/JotformClient.php b/src/JotformClient.php new file mode 100644 index 0000000..7877a0e --- /dev/null +++ b/src/JotformClient.php @@ -0,0 +1,220 @@ +apiKey = $apiKey; + $this->outputType = $outputType; + $this->debug = $debug; + } + + public function europeOnly(bool $value): void + { + $this->europeOnly = $value; + } + + public function setApiKey(string $apiKey): void + { + $this->apiKey = $apiKey; + } + + public function getApiKey(): string + { + return $this->apiKey; + } + + public function setOutputType(string $outputType): void + { + $this->outputType = $outputType; + } + + public function getOutputType(): string + { + return $this->outputType; + } + + public function setDebugMode(string $debugMode): void + { + $this->debugMode = $debugMode; + } + + public function getDebugMode(): bool + { + return $this->debugMode; + } + + public function get(string $path, array $params = []): JotformResponse + { + return $this->request('get', $path, $params); + } + + public function post(string $path, array $params = []): JotformResponse + { + return $this->request('post', $path, $params); + } + + public function put(string $path, array $params = []): JotformResponse + { + return $this->request('put', $path, $params); + } + + public function delete(string $path, array $params = []): JotformResponse + { + return $this->request('delete', $path, $params); + } + + public function postJson(string $path, string $params = ''): JotformResponse + { + return $this->requestJson('post', $path, $params); + } + + public function putJson(string $path, string $params = ''): JotformResponse + { + return $this->requestJson('put', $path, $params); + } + + public function deleteJson(string $path, string $params = ''): JotformResponse + { + return $this->requestJson('delete', $path, $params); + } + + protected function request(string $method, string $path, array $params = []): JotformResponse + { + return $this->prepareAndSendRequest($method, $path, $params); + } + + protected function requestJson(string $method, string $path, string $params = ''): JotformResponse + { + return $this->prepareAndSendRequest($method, $path, $params); + } + + /** + * @param string  $method Request Method + * @param string $path Request Path/URL + * @param array|string $params Data Array or JSON string + * @return JotformResponse + */ + protected function prepareAndSendRequest(string $method, string $path, $params = []): JotformResponse + { + $method = strtoupper($method); + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $this->normalizeRequestUrl($path, $method)); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_USERAGENT, 'JOTFORM_PHP_WRAPPER'); + curl_setopt($ch, CURLOPT_HTTPHEADER, $this->prepareRequestHeaders($params)); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + + if (in_array($method, ['POST', 'PUT', 'DELETE'])) { + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); + if (! empty($params)) { + curl_setopt($ch, CURLOPT_POSTFIELDS, $params); + } + } + + $response = curl_exec($ch); + $info = curl_getinfo($ch); + $statusCode = $info['http_code']; + curl_close($ch); + + if ($this->debug) { + // [TODO] + // var_dump([ + // 'parameters' => $params, + // 'info' => $info, + // ]); + } + + if ($response == false) { + throw new JotFormException(curl_error($ch), 400); + } + + $response = $this->outputType === self::OUTPUT_JSON + ? json_decode($response, true) + : utf8_decode($response); + + if ($statusCode !== 200) { + switch ($statusCode) { + case 400: + case 403: + case 404: + throw new JotFormException($response["message"] ?? 'Not Found', $statusCode); + + break; + case 401: + throw new InvalidKeyException(); + + break; + case 503: + throw new ServiceUnavailableException(); + + break; + default: + throw new JotFormException($response["info"] ?? 'Unexpected Error', $statusCode); + } + } + + if ($this->outputType === self::OUTPUT_JSON) { + $response = $response['content'] ?? $response; + } + + return new JotformResponse($response, $statusCode, $response["message"] ?? null); + } + + /** + * @param array|string Data Array or JSON string + * @return array + */ + private function prepareRequestHeaders($params): array + { + $headers = [ + "APIKEY: {$this->apiKey}", + ]; + + if (is_string($params)) { + $headers[] = "Content-Type: application/json"; + } + + return $headers; + } + + private function normalizeRequestUrl(string $path, string $method): string + { + $server = $this->europeOnly ? 'eu-api' : 'api'; + $segments = [ + "https://{$server}.jotform.com", + // 'v' . self::API_VERSION, + $path . ($this->outputType === self::OUTPUT_JSON ? '' : '.xml'), + ]; + + $url = implode('/', $segments); + + return $method === 'GET' && ! empty($params) + ? "{$url}?" . http_build_query($params) + : $url; + } +} diff --git a/src/JotformResponse.php b/src/JotformResponse.php new file mode 100644 index 0000000..a0b48dd --- /dev/null +++ b/src/JotformResponse.php @@ -0,0 +1,49 @@ +content = $content; + $this->statusCode = $statusCode; + $this->message = $message; + } + + public function toArray(): ?array + { + return $this->content; + } + + public function toJson(): ?string + { + return json_encode($this->content); + } + + public function toObject(): ?object + { + $object = json_decode($this->toJson()); + + return empty($object) ? null : $object; + } + + public function getStatusCode(): int + { + return $this->statusCode; + } + + public function getMessage(): ?string + { + return $this->message; + } + + public function __toString(): ?string + { + return $this->toJson(); + } +} diff --git a/src/Services/Folder.php b/src/Services/Folder.php new file mode 100644 index 0000000..9634ae6 --- /dev/null +++ b/src/Services/Folder.php @@ -0,0 +1,31 @@ +folderId = $folderId; + } + + public function id(): string + { + return $this->folderId; + } + + public function get(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->folderId}"); + } +} diff --git a/src/Services/Form.php b/src/Services/Form.php new file mode 100644 index 0000000..0e8ec7a --- /dev/null +++ b/src/Services/Form.php @@ -0,0 +1,190 @@ +formId = $formId; + } + + public function id(): string + { + return $this->formId; + } + + public function get(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->formId}"); + } + + /** + * @param array|string $params Array or Json + * @return JotformResponse + */ + public function create($params): JotformResponse + { + if (is_string($params)) { + return $this->client->putJson($this->name, $params); + } + + $form = []; + foreach ($params as $key => $value) { + foreach ($value as $k => $v) { + if ($key === "properties") { + $form["{$key}[{$k}]"] = $v; + } else { + foreach ($v as $a => $b) { + $form["{$key}[{$k}][{$a}]"] = $b; + } + } + } + } + + return $this->client->post($this->name, $form); + } + + public function delete(): JotformResponse + { + return $this->client->delete("{$this->name}/{$this->formId}"); + } + + public function clone(string $formId): JotformResponse + { + return $this->client->post("{$this->name}/{$formId}/clone"); + } + + public function questions(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->formId}/questions", $this->getConditions()); + } + + public function question(string $questionId): JotformResponse + { + return $this->client->get("{$this->name}/{$this->formId}/questions/{$questionId}"); + } + + /** + * @param array|string $params Data Array or JSON String + * @return JotformResponse + */ + public function createQuestion($params): JotformResponse + { + $endpoint = "{$this->name}/{$this->formId}/questions"; + + if (is_string($params)) { + return $this->client->putJson($endpoint, $params); + } + + return $this->client->post($endpoint, $this->prepareQuestionParams($params)); + } + + public function editQuestion(string $questionId, array $params): JotformResponse + { + return $this->client->post( + "{$this->name}/{$this->formId}/question/{$questionId}", + $this->prepareQuestionParams($params) + ); + } + + public function deleteQuestion(string $questionId): JotformResponse + { + return $this->client->delete("{$this->name}/{$this->formId}/question/{$questionId}"); + } + + public function submissions(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->formId}/submissions", $this->getConditions()); + } + + public function createSubmission(array $params): JotformResponse + { + return (new Submission($this->client, null))->create($this->formId, $params); + } + + public function files(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->formId}/files", $this->getConditions()); + } + + public function webhooks(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->formId}/webhooks", $this->getConditions()); + } + + public function createWebhook(string $url): JotformResponse + { + return $this->client->post("{$this->name}/{$this->formId}/webhooks", [ + 'webhookURL' => $url, + ]); + } + + public function deleteWebhook(string $webhookId): JotformResponse + { + return $this->client->delete("{$this->name}/{$this->formId}/webhooks/{$webhookId}"); + } + + public function properties(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->formId}/properties"); + } + + public function property(string $key): JotformResponse + { + return $this->client->get("{$this->name}/{$this->formId}/properties/{$key}"); + } + + /** + * @param array|string $params Data Array or JSON String + * @return JotformResponse + */ + public function setProperties($params): JotformResponse + { + $endpoint = "{$this->name}/{$this->formId}/properties"; + + if (is_string($params)) { + return $this->client->putJson($endpoint, $params); + } + + $properties = []; + foreach ($params as $key => $value) { + $properties["properties[{$key}]"] = $value; + } + + return $this->client->post($endpoint, $properties); + } + + public function reports(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->formId}/reports", $this->getConditions()); + } + + public function createReport(array $params): JotformResponse + { + return $this->client->post("{$this->name}/{$this->formId}/reports", $params); + } + + protected function prepareQuestionParams(array $params): array + { + $question = []; + foreach ($params as $key => $value) { + $question["question[{$key}]"] = $value; + } + + return $question; + } +} diff --git a/src/Services/Report.php b/src/Services/Report.php new file mode 100644 index 0000000..62b652e --- /dev/null +++ b/src/Services/Report.php @@ -0,0 +1,36 @@ +reportId = $reportId; + } + + public function id(): string + { + return $this->reportId; + } + + public function get(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->reportId}"); + } + + public function delete(): JotformResponse + { + return $this->client->delete("{$this->name}/{$this->reportId}"); + } +} diff --git a/src/Services/Service.php b/src/Services/Service.php new file mode 100644 index 0000000..1c240da --- /dev/null +++ b/src/Services/Service.php @@ -0,0 +1,19 @@ +client = $client; + } +} diff --git a/src/Services/Submission.php b/src/Services/Submission.php new file mode 100644 index 0000000..a330765 --- /dev/null +++ b/src/Services/Submission.php @@ -0,0 +1,78 @@ +submissionId = $submissionId; + } + + public function id(): string + { + return $this->submissionId; + } + + public function get(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->submissionId}"); + } + + public function getAll(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->submissionId}"); + } + + /** + * @param string $formId + * @param array|string $params Data Array or JSON String + * @return JotformResponse + */ + public function create(string $formId, $params): JotformResponse + { + $endpoint = "form/{$formId}/submissions"; + + if (is_string($params)) { + return $this->client->putJson($endpoint, $params); + } + + return $this->client->post($endpoint, $this->prepareParams($params)); + } + + public function update(array $params): JotformResponse + { + return $this->client->post("{$this->name}/{$this->submissionId}", $this->prepareParams($params)); + } + + public function delete(): JotformResponse + { + return $this->client->delete("{$this->name}/{$this->submissionId}"); + } + + protected function prepareParams(array $params): array + { + $submission = []; + foreach ($params as $key => $value) { + if (strpos($key, '_') && $key !== 'created_at') { + $qid = substr($key, 0, strpos($key, '_')); + $type = substr($key, strpos($key, '_') + 1); + $submission["submission[{$qid}][{$type}]"] = $value; + } else { + $submission["submission[{$key}]"] = $value; + } + } + + return $submission; + } +} diff --git a/src/Services/System.php b/src/Services/System.php new file mode 100644 index 0000000..e2ab7be --- /dev/null +++ b/src/Services/System.php @@ -0,0 +1,21 @@ +folderId; + } + + public function plan(string $name): JotformResponse + { + return $this->client->get("{$this->name}/plan/" . strtoupper($name)); + } +} diff --git a/src/Services/User.php b/src/Services/User.php new file mode 100644 index 0000000..b6f7569 --- /dev/null +++ b/src/Services/User.php @@ -0,0 +1,86 @@ +client->get($this->name); + } + + public function register(array $user): JotformResponse + { + return $this->client->post("{$this->name}/register", $user); + } + + public function login(array $credentials): JotformResponse + { + return $this->client->post("{$this->name}/login", $credentials); + } + + public function logout(): JotformResponse + { + return $this->client->get("{$this->name}/logout"); + } + + public function usage(): JotformResponse + { + return $this->client->get("{$this->name}/usage"); + } + + public function forms(): JotformResponse + { + return $this->client->get("{$this->name}/forms", $this->getConditions()); + } + + public function createForm(array $params): JotformResponse + { + return (new Form($this->client, null))->create($params); + } + + public function submissions(): JotformResponse + { + return $this->client->get("{$this->name}/submissions", $this->getConditions()); + } + + public function subUsers(): JotformResponse + { + return $this->client->get("{$this->name}/subusers"); + } + + public function folders(): JotformResponse + { + return $this->client->get("{$this->name}/folders"); + } + + public function reports(): JotformResponse + { + return $this->client->get('{$this->name}/reports'); + } + + public function settings(): JotformResponse + { + return $this->client->get("{$this->name}/settings"); + } + + public function updateSettings(array $params): JotformResponse + { + return $this->client->post("{$this->name}/settings", $params); + } + + public function history(): JotformResponse + { + return $this->client->get("{$this->name}/history", $this->getQueries()); + } +} diff --git a/src/Traits/UseConditions.php b/src/Traits/UseConditions.php new file mode 100644 index 0000000..4f381a0 --- /dev/null +++ b/src/Traits/UseConditions.php @@ -0,0 +1,46 @@ +offset = $offset; + + return $this; + } + + public function limit(int $limit): self + { + $this->limit = $limit; + + return $this; + } + + public function filter(array $filter): self + { + $this->filter = urlencode(json_encode($filter)); + + return $this; + } + + public function orderBy(string $orderBy): self + { + $this->orderBy = $orderBy; + + return $this; + } + + protected function getConditions() + { + $conditions = []; + + return $conditions; + } +} diff --git a/src/Traits/UseQuery.php b/src/Traits/UseQuery.php new file mode 100644 index 0000000..c2e82a4 --- /dev/null +++ b/src/Traits/UseQuery.php @@ -0,0 +1,54 @@ +action = $action; + + return $this; + } + + public function date(int $date): self + { + $this->date = $date; + + return $this; + } + + public function sortBy(array $sortBy): self + { + $this->sortBy = urlencode(json_encode($sortBy)); + + return $this; + } + + public function startDate(string $startDate): self + { + $this->startDate = $startDate; + + return $this; + } + + public function endDate(string $endDate): self + { + $this->endDate = $endDate; + + return $this; + } + + protected function getQueries() + { + $queries = []; + + return $queries; + } +} diff --git a/tests/FolderTest.php b/tests/FolderTest.php new file mode 100644 index 0000000..c039a63 --- /dev/null +++ b/tests/FolderTest.php @@ -0,0 +1,17 @@ +jotform->folder("")->get(); + $folder = $response->toObject(); + + $this->assertEquals(200, $response->getStatusCode()); + $this->assertEmpty($folder); + } +} diff --git a/tests/FormTest.php b/tests/FormTest.php new file mode 100644 index 0000000..fc1b08a --- /dev/null +++ b/tests/FormTest.php @@ -0,0 +1,16 @@ +expectException(JotformException::class); + $this->jotform->form("")->get(); + } +} diff --git a/tests/ReportTest.php b/tests/ReportTest.php new file mode 100644 index 0000000..035a33f --- /dev/null +++ b/tests/ReportTest.php @@ -0,0 +1,20 @@ +expectException(JotformException::class); + $response = $this->jotform->report("")->get(); + $report = $response->toArray(); + + $this->assertEquals(200, $response->getStatusCode()); + $this->assertEmpty($report); + } +} diff --git a/tests/SubmissionTest.php b/tests/SubmissionTest.php new file mode 100644 index 0000000..09feae3 --- /dev/null +++ b/tests/SubmissionTest.php @@ -0,0 +1,26 @@ +expectException(JotformException::class); + $this->jotform->submission("")->get(); + } + + /** @test */ + public function test_get_all_submissions_by_form_id() + { + // [TODO] + $response = $this->jotform->form("") + ->limit(100)->orderBy('created_at')->getSubmissions(); + + $this->assertEquals(200, $response->getStatusCode()); + } +} diff --git a/tests/SystemTest.php b/tests/SystemTest.php new file mode 100644 index 0000000..550c352 --- /dev/null +++ b/tests/SystemTest.php @@ -0,0 +1,41 @@ +jotform->system()->plan('free'); + $this->assertEquals(200, $response->getStatusCode()); + } + + /** @test */ + public function test_get_system_plan_for_bronze() + { + $response = $this->jotform->system()->plan('bronze'); + $this->assertEquals(200, $response->getStatusCode()); + } + + /** @test */ + public function test_get_system_plan_for_silver() + { + $response = $this->jotform->system()->plan('silver'); + $this->assertEquals(200, $response->getStatusCode()); + } + + /** @test */ + public function test_get_system_plan_for_gold() + { + $response = $this->jotform->system()->plan('gold'); + $this->assertEquals(200, $response->getStatusCode()); + } + + /** @test */ + public function test_get_system_plan_for_platinum() + { + $response = $this->jotform->system()->plan('platinum'); + $this->assertEquals(200, $response->getStatusCode()); + } +} diff --git a/tests/TestCase.php b/tests/TestCase.php new file mode 100644 index 0000000..bc6a87d --- /dev/null +++ b/tests/TestCase.php @@ -0,0 +1,23 @@ +client = new JotformClient($_ENV['API_KEY']); + $this->jotform = new Jotform($this->client); + } +} diff --git a/tests/UserTest.php b/tests/UserTest.php new file mode 100644 index 0000000..5f6e13c --- /dev/null +++ b/tests/UserTest.php @@ -0,0 +1,27 @@ +jotform->user()->get(); + $this->assertEquals(200, $response->getStatusCode()); + } + + /** @test */ + public function test_get_user_usage() + { + $response = $this->jotform->user()->usage(); + $this->assertEquals(200, $response->getStatusCode()); + } + + /** @test */ + public function test_get_user_forms() + { + $response = $this->jotform->user()->forms(); + $this->assertEquals(200, $response->getStatusCode()); + } +} From d1d35841728e1afe9da8cfe23c464fb38da00d7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Demirta=C5=9F?= Date: Fri, 15 Oct 2021 09:10:41 +0300 Subject: [PATCH 02/22] Updated condition and query preparing. --- src/Traits/UseConditions.php | 25 +++++++++++++++++++++++- src/Traits/UseQuery.php | 37 ++++++++++++++++++++++++++++++++---- 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/src/Traits/UseConditions.php b/src/Traits/UseConditions.php index 4f381a0..a7ecaf5 100644 --- a/src/Traits/UseConditions.php +++ b/src/Traits/UseConditions.php @@ -4,9 +4,16 @@ trait UseConditions { + /** @var int */ private $offset; + + /** @var int */ private $limit; + + /** @var array */ private $filter; + + /** @var string */ private $orderBy; public function offset(int $offset): self @@ -25,7 +32,7 @@ public function limit(int $limit): self public function filter(array $filter): self { - $this->filter = urlencode(json_encode($filter)); + $this->filter = $filter; return $this; } @@ -41,6 +48,22 @@ protected function getConditions() { $conditions = []; + if ($this->offset) { + $conditions['offset'] = $this->offset; + } + + if ($this->limit) { + $conditions['limit'] = $this->limit; + } + + if ($this->filter) { + $conditions['filter'] = urlencode(json_encode($this->filter)); + } + + if ($this->orderBy) { + $conditions['orderby'] = $this->orderBy; + } + return $conditions; } } diff --git a/src/Traits/UseQuery.php b/src/Traits/UseQuery.php index c2e82a4..e0b765c 100644 --- a/src/Traits/UseQuery.php +++ b/src/Traits/UseQuery.php @@ -4,29 +4,38 @@ trait UseQuery { + /** @var string */ private $action; + + /** @var string */ private $date; + + /** @var string */ private $sortBy; + + /** @var string */ private $startDate; + + /** @var string */ private $endDate; - public function action(int $action): self + public function action(string $action): self { $this->action = $action; return $this; } - public function date(int $date): self + public function date(string $date): self { $this->date = $date; return $this; } - public function sortBy(array $sortBy): self + public function sortBy(string $sortBy): self { - $this->sortBy = urlencode(json_encode($sortBy)); + $this->sortBy = $sortBy; return $this; } @@ -49,6 +58,26 @@ protected function getQueries() { $queries = []; + if ($this->action) { + $conditions['action'] = $this->action; + } + + if ($this->date) { + $conditions['date'] = $this->date; + } + + if ($this->sortBy) { + $conditions['sortBy'] = $this->sortBy; + } + + if ($this->startDate) { + $conditions['startDate'] = $this->startDate; + } + + if ($this->endDate) { + $conditions['endDate'] = $this->endDate; + } + return $queries; } } From a7100bfc4b791a68c1dda70dae3b2aec9b1ad6b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Demirta=C5=9F?= Date: Mon, 25 Oct 2021 10:58:53 +0300 Subject: [PATCH 03/22] Added API version into the base URL. Also, updated code format. --- .php-cs-fixer.dist.php | 2 +- src/JotformClient.php | 18 ++++++++++++------ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 33b3b63..f285388 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -15,7 +15,7 @@ 'array_syntax' => ['syntax' => 'short'], 'ordered_imports' => ['sort_algorithm' => 'alpha'], 'no_unused_imports' => true, - 'not_operator_with_successor_space' => true, + 'not_operator_with_successor_space' => false, 'trailing_comma_in_multiline' => true, 'phpdoc_scalar' => true, 'unary_operator_spaces' => true, diff --git a/src/JotformClient.php b/src/JotformClient.php index 7877a0e..3850eed 100644 --- a/src/JotformClient.php +++ b/src/JotformClient.php @@ -117,13 +117,13 @@ protected function requestJson(string $method, string $path, string $params = '' * @param string  $method Request Method * @param string $path Request Path/URL * @param array|string $params Data Array or JSON string - * @return JotformResponse + * @return JotformResponse */ protected function prepareAndSendRequest(string $method, string $path, $params = []): JotformResponse { $method = strtoupper($method); $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $this->normalizeRequestUrl($path, $method)); + curl_setopt($ch, CURLOPT_URL, $this->normalizeRequestUrl($path, $method, $params)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, 'JOTFORM_PHP_WRAPPER'); curl_setopt($ch, CURLOPT_HTTPHEADER, $this->prepareRequestHeaders($params)); @@ -131,7 +131,7 @@ protected function prepareAndSendRequest(string $method, string $path, $params = if (in_array($method, ['POST', 'PUT', 'DELETE'])) { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); - if (! empty($params)) { + if (!empty($params)) { curl_setopt($ch, CURLOPT_POSTFIELDS, $params); } } @@ -202,18 +202,24 @@ private function prepareRequestHeaders($params): array return $headers; } - private function normalizeRequestUrl(string $path, string $method): string + /** + * @param string $path + * @param string $method + * @param array|string $params + * @return string + */ + private function normalizeRequestUrl(string $path, string $method, $params): string { $server = $this->europeOnly ? 'eu-api' : 'api'; $segments = [ "https://{$server}.jotform.com", - // 'v' . self::API_VERSION, + 'v' . self::API_VERSION, $path . ($this->outputType === self::OUTPUT_JSON ? '' : '.xml'), ]; $url = implode('/', $segments); - return $method === 'GET' && ! empty($params) + return $method === 'GET' && is_array($params) && !empty($params) ? "{$url}?" . http_build_query($params) : $url; } From 9c2a170d20037c7c1e5f84914a336290032041f2 Mon Sep 17 00:00:00 2001 From: ibd <91189135+burakdemirtas-jtf@users.noreply.github.com> Date: Wed, 27 Oct 2021 09:21:01 +0300 Subject: [PATCH 04/22] Update filename --- JotForm.php => Jotform.php | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename JotForm.php => Jotform.php (100%) diff --git a/JotForm.php b/Jotform.php similarity index 100% rename from JotForm.php rename to Jotform.php From 0cee829c97bb06c9bda77add2093d26fee2af78c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Demirta=C5=9F?= Date: Wed, 27 Oct 2021 09:21:54 +0300 Subject: [PATCH 05/22] Updated README. --- README.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 963a893..6e8f3dc 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ jotform-api-php =============== -[JotForm API](http://api.jotform.com/docs/) - PHP Client +[Jotform API](http://api.jotform.com/docs/) - PHP Client ## Installation @@ -12,7 +12,7 @@ $ composer require jotform/jotform-api-php ``` and add following line to your php file: ```php -require "vendor/autoload.php"; +require 'vendor/autoload.php'; ``` 2- Install and use manually: @@ -21,7 +21,7 @@ $ git clone https://github.com/jotform/jotform-api-php.git ``` and add following line to your php file: ```php -require "jotform-api-php/Jotform.php"; +require 'jotform-api-php/Jotform.php'; ``` If you install the package into another directory, you should update path for `require` command above. @@ -32,7 +32,7 @@ You can find the docs for the API of this client at [Jotform API Documentation]( ## Authentication -JotForm API requires API key for all user related calls. You can create your API Keys at [API section](http://www.jotform.com/myaccount/api) of My Account page. +Jotform API requires API key for all user related calls. You can create your API Keys at [API section](http://www.jotform.com/myaccount/api) of My Account page. ## Examples @@ -40,17 +40,17 @@ JotForm API requires API key for all user related calls. You can create your API ```php "); +$client = new JotformClient(''); $jotform = new Jotform($client); $forms = $jotform->user()->forms(); foreach ($forms->toArray() as $form) { - echo $form["title"] . PHP_EOL; + echo $form['title'] . PHP_EOL; } ``` @@ -111,15 +111,15 @@ try { $jotform = new Jotform($client); $filter = [ - "id:gt" => "239252191641336722", - "created_at:gt" => "2013-07-09 07:48:34", + 'id:gt' => '239252191641336722', + 'created_at:gt' => '2013-07-09 07:48:34', ]; $submissions = $jotform->user()->filter($filter)->submissions(); var_dump($submissions); $filter = [ - "id:gt" => "239176717911737253", + 'id:gt' => '239176717911737253', ]; $forms = $jotform->user()->filter($filter)->forms(); @@ -143,7 +143,7 @@ try { $submissions = $jotform->user()->limit(50)->orderBy('created_at')->submissions(); foreach ($submissions->toArray() as $submission) { - $result = $jotform->submission($submission["id"])->delete(); + $result = $jotform->submission($submission['id'])->delete(); echo $result . PHP_EOL; } } From 04fdbd43ef805062448244350e2084f9e67fb0a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Demirta=C5=9F?= Date: Mon, 8 Nov 2021 10:23:13 +0300 Subject: [PATCH 06/22] Update services and tests. Also, configured workflow. --- .github/workflows/run-tests.yml | 4 +++- Jotform.php | 2 +- phpunit.xml.dist | 3 --- src/Jotform.php | 7 +++++- src/JotformClient.php | 28 +++++++++++++---------- src/JotformResponse.php | 5 ----- src/Services/Folder.php | 2 +- src/Services/Form.php | 40 ++++++++++++++++----------------- src/Services/Report.php | 4 ++-- src/Services/Submission.php | 10 ++++----- src/Services/System.php | 2 +- src/Services/User.php | 28 +++++++++++------------ tests/FolderTest.php | 5 ++--- tests/ReportTest.php | 7 +++--- tests/SubmissionTest.php | 29 ++++++++++++++++++------ tests/SystemTest.php | 20 ++++++++--------- tests/TestCase.php | 3 +-- tests/UserTest.php | 12 +++++----- 18 files changed, 113 insertions(+), 98 deletions(-) diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index edc2f41..e2b386d 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -34,4 +34,6 @@ jobs: run: composer update --${{ matrix.stability }} --prefer-dist --no-interaction - name: Execute tests - run: composer test \ No newline at end of file + run: composer test + env: + JOTFORM_API_KEY: ${{ secrets.JOTFORM_API_KEY }} diff --git a/Jotform.php b/Jotform.php index 5224f63..4f733f7 100644 --- a/Jotform.php +++ b/Jotform.php @@ -1,6 +1,6 @@ ./src - - - \ No newline at end of file diff --git a/src/Jotform.php b/src/Jotform.php index 223d647..0082dde 100644 --- a/src/Jotform.php +++ b/src/Jotform.php @@ -20,7 +20,7 @@ public function __construct(JotformClient $client, bool $euCheck = true) // Check 'euOnly' flag for User while initializing. if ($euCheck) { - $user = $this->user()->get()->toArray(); + $user = $this->user()->get(); if (isset($user['euOnly'])) { $this->client->europeOnly(true); } @@ -61,4 +61,9 @@ public function system(): System { return new System($this->client); } + + public function response(): JotformResponse + { + return $this->client->response; + } } diff --git a/src/JotformClient.php b/src/JotformClient.php index 3850eed..64ae9bd 100644 --- a/src/JotformClient.php +++ b/src/JotformClient.php @@ -26,6 +26,9 @@ class JotformClient /** @var bool */ private $debug; + /** @var JotformResponse */ + public $response; + public function __construct(string $apiKey, string $outputType = self::OUTPUT_JSON, bool $debug = false) { $this->apiKey = $apiKey; @@ -68,47 +71,47 @@ public function getDebugMode(): bool return $this->debugMode; } - public function get(string $path, array $params = []): JotformResponse + public function get(string $path, array $params = []): ?array { return $this->request('get', $path, $params); } - public function post(string $path, array $params = []): JotformResponse + public function post(string $path, array $params = []): ?array { return $this->request('post', $path, $params); } - public function put(string $path, array $params = []): JotformResponse + public function put(string $path, array $params = []): ?array { return $this->request('put', $path, $params); } - public function delete(string $path, array $params = []): JotformResponse + public function delete(string $path, array $params = []): ?array { return $this->request('delete', $path, $params); } - public function postJson(string $path, string $params = ''): JotformResponse + public function postJson(string $path, string $params = ''): ?array { return $this->requestJson('post', $path, $params); } - public function putJson(string $path, string $params = ''): JotformResponse + public function putJson(string $path, string $params = ''): ?array { return $this->requestJson('put', $path, $params); } - public function deleteJson(string $path, string $params = ''): JotformResponse + public function deleteJson(string $path, string $params = ''): ?array { return $this->requestJson('delete', $path, $params); } - protected function request(string $method, string $path, array $params = []): JotformResponse + protected function request(string $method, string $path, array $params = []): ?array { return $this->prepareAndSendRequest($method, $path, $params); } - protected function requestJson(string $method, string $path, string $params = ''): JotformResponse + protected function requestJson(string $method, string $path, string $params = ''): ?array { return $this->prepareAndSendRequest($method, $path, $params); } @@ -117,9 +120,9 @@ protected function requestJson(string $method, string $path, string $params = '' * @param string  $method Request Method * @param string $path Request Path/URL * @param array|string $params Data Array or JSON string - * @return JotformResponse + * @return array|null */ - protected function prepareAndSendRequest(string $method, string $path, $params = []): JotformResponse + protected function prepareAndSendRequest(string $method, string $path, $params = []): ?array { $method = strtoupper($method); $ch = curl_init(); @@ -182,7 +185,8 @@ protected function prepareAndSendRequest(string $method, string $path, $params = $response = $response['content'] ?? $response; } - return new JotformResponse($response, $statusCode, $response["message"] ?? null); + $this->response = new JotformResponse($response, $statusCode, $response["message"] ?? null); + return $response; } /** diff --git a/src/JotformResponse.php b/src/JotformResponse.php index a0b48dd..d01525a 100644 --- a/src/JotformResponse.php +++ b/src/JotformResponse.php @@ -15,11 +15,6 @@ public function __construct($content, int $statusCode, ?string $message) $this->message = $message; } - public function toArray(): ?array - { - return $this->content; - } - public function toJson(): ?string { return json_encode($this->content); diff --git a/src/Services/Folder.php b/src/Services/Folder.php index 9634ae6..294823d 100644 --- a/src/Services/Folder.php +++ b/src/Services/Folder.php @@ -24,7 +24,7 @@ public function id(): string return $this->folderId; } - public function get(): JotformResponse + public function get(): ?array { return $this->client->get("{$this->name}/{$this->folderId}"); } diff --git a/src/Services/Form.php b/src/Services/Form.php index 0e8ec7a..f9a3b68 100644 --- a/src/Services/Form.php +++ b/src/Services/Form.php @@ -27,7 +27,7 @@ public function id(): string return $this->formId; } - public function get(): JotformResponse + public function get(): ?array { return $this->client->get("{$this->name}/{$this->formId}"); } @@ -36,7 +36,7 @@ public function get(): JotformResponse * @param array|string $params Array or Json * @return JotformResponse */ - public function create($params): JotformResponse + public function create($params): ?array { if (is_string($params)) { return $this->client->putJson($this->name, $params); @@ -58,22 +58,22 @@ public function create($params): JotformResponse return $this->client->post($this->name, $form); } - public function delete(): JotformResponse + public function delete(): ?array { return $this->client->delete("{$this->name}/{$this->formId}"); } - public function clone(string $formId): JotformResponse + public function clone(string $formId): ?array { return $this->client->post("{$this->name}/{$formId}/clone"); } - public function questions(): JotformResponse + public function questions(): ?array { return $this->client->get("{$this->name}/{$this->formId}/questions", $this->getConditions()); } - public function question(string $questionId): JotformResponse + public function question(string $questionId): ?array { return $this->client->get("{$this->name}/{$this->formId}/questions/{$questionId}"); } @@ -82,7 +82,7 @@ public function question(string $questionId): JotformResponse * @param array|string $params Data Array or JSON String * @return JotformResponse */ - public function createQuestion($params): JotformResponse + public function createQuestion($params): ?array { $endpoint = "{$this->name}/{$this->formId}/questions"; @@ -93,7 +93,7 @@ public function createQuestion($params): JotformResponse return $this->client->post($endpoint, $this->prepareQuestionParams($params)); } - public function editQuestion(string $questionId, array $params): JotformResponse + public function editQuestion(string $questionId, array $params): ?array { return $this->client->post( "{$this->name}/{$this->formId}/question/{$questionId}", @@ -101,49 +101,49 @@ public function editQuestion(string $questionId, array $params): JotformResponse ); } - public function deleteQuestion(string $questionId): JotformResponse + public function deleteQuestion(string $questionId): ?array { return $this->client->delete("{$this->name}/{$this->formId}/question/{$questionId}"); } - public function submissions(): JotformResponse + public function submissions(): ?array { return $this->client->get("{$this->name}/{$this->formId}/submissions", $this->getConditions()); } - public function createSubmission(array $params): JotformResponse + public function createSubmission(array $params): ?array { return (new Submission($this->client, null))->create($this->formId, $params); } - public function files(): JotformResponse + public function files(): ?array { return $this->client->get("{$this->name}/{$this->formId}/files", $this->getConditions()); } - public function webhooks(): JotformResponse + public function webhooks(): ?array { return $this->client->get("{$this->name}/{$this->formId}/webhooks", $this->getConditions()); } - public function createWebhook(string $url): JotformResponse + public function createWebhook(string $url): ?array { return $this->client->post("{$this->name}/{$this->formId}/webhooks", [ 'webhookURL' => $url, ]); } - public function deleteWebhook(string $webhookId): JotformResponse + public function deleteWebhook(string $webhookId): ?array { return $this->client->delete("{$this->name}/{$this->formId}/webhooks/{$webhookId}"); } - public function properties(): JotformResponse + public function properties(): ?array { return $this->client->get("{$this->name}/{$this->formId}/properties"); } - public function property(string $key): JotformResponse + public function property(string $key): ?array { return $this->client->get("{$this->name}/{$this->formId}/properties/{$key}"); } @@ -152,7 +152,7 @@ public function property(string $key): JotformResponse * @param array|string $params Data Array or JSON String * @return JotformResponse */ - public function setProperties($params): JotformResponse + public function setProperties($params): ?array { $endpoint = "{$this->name}/{$this->formId}/properties"; @@ -168,12 +168,12 @@ public function setProperties($params): JotformResponse return $this->client->post($endpoint, $properties); } - public function reports(): JotformResponse + public function reports(): ?array { return $this->client->get("{$this->name}/{$this->formId}/reports", $this->getConditions()); } - public function createReport(array $params): JotformResponse + public function createReport(array $params): ?array { return $this->client->post("{$this->name}/{$this->formId}/reports", $params); } diff --git a/src/Services/Report.php b/src/Services/Report.php index 62b652e..85ff121 100644 --- a/src/Services/Report.php +++ b/src/Services/Report.php @@ -24,12 +24,12 @@ public function id(): string return $this->reportId; } - public function get(): JotformResponse + public function get(): ?array { return $this->client->get("{$this->name}/{$this->reportId}"); } - public function delete(): JotformResponse + public function delete(): ?array { return $this->client->delete("{$this->name}/{$this->reportId}"); } diff --git a/src/Services/Submission.php b/src/Services/Submission.php index a330765..57c4d1f 100644 --- a/src/Services/Submission.php +++ b/src/Services/Submission.php @@ -24,12 +24,12 @@ public function id(): string return $this->submissionId; } - public function get(): JotformResponse + public function get(): ?array { return $this->client->get("{$this->name}/{$this->submissionId}"); } - public function getAll(): JotformResponse + public function getAll(): ?array { return $this->client->get("{$this->name}/{$this->submissionId}"); } @@ -39,7 +39,7 @@ public function getAll(): JotformResponse * @param array|string $params Data Array or JSON String * @return JotformResponse */ - public function create(string $formId, $params): JotformResponse + public function create(string $formId, $params): ?array { $endpoint = "form/{$formId}/submissions"; @@ -50,12 +50,12 @@ public function create(string $formId, $params): JotformResponse return $this->client->post($endpoint, $this->prepareParams($params)); } - public function update(array $params): JotformResponse + public function update(array $params): ?array { return $this->client->post("{$this->name}/{$this->submissionId}", $this->prepareParams($params)); } - public function delete(): JotformResponse + public function delete(): ?array { return $this->client->delete("{$this->name}/{$this->submissionId}"); } diff --git a/src/Services/System.php b/src/Services/System.php index e2ab7be..82f4ebb 100644 --- a/src/Services/System.php +++ b/src/Services/System.php @@ -14,7 +14,7 @@ public function id(): string return $this->folderId; } - public function plan(string $name): JotformResponse + public function plan(string $name): ?array { return $this->client->get("{$this->name}/plan/" . strtoupper($name)); } diff --git a/src/Services/User.php b/src/Services/User.php index b6f7569..8850136 100644 --- a/src/Services/User.php +++ b/src/Services/User.php @@ -14,72 +14,72 @@ class User extends Service /** @var string */ protected $name = 'user'; - public function get(): JotformResponse + public function get(): ?array { return $this->client->get($this->name); } - public function register(array $user): JotformResponse + public function register(array $user): ?array { return $this->client->post("{$this->name}/register", $user); } - public function login(array $credentials): JotformResponse + public function login(array $credentials): ?array { return $this->client->post("{$this->name}/login", $credentials); } - public function logout(): JotformResponse + public function logout(): ?array { return $this->client->get("{$this->name}/logout"); } - public function usage(): JotformResponse + public function usage(): ?array { return $this->client->get("{$this->name}/usage"); } - public function forms(): JotformResponse + public function forms(): ?array { return $this->client->get("{$this->name}/forms", $this->getConditions()); } - public function createForm(array $params): JotformResponse + public function createForm(array $params): ?array { return (new Form($this->client, null))->create($params); } - public function submissions(): JotformResponse + public function submissions(): ?array { return $this->client->get("{$this->name}/submissions", $this->getConditions()); } - public function subUsers(): JotformResponse + public function subUsers(): ?array { return $this->client->get("{$this->name}/subusers"); } - public function folders(): JotformResponse + public function folders(): ?array { return $this->client->get("{$this->name}/folders"); } - public function reports(): JotformResponse + public function reports(): ?array { return $this->client->get('{$this->name}/reports'); } - public function settings(): JotformResponse + public function settings(): ?array { return $this->client->get("{$this->name}/settings"); } - public function updateSettings(array $params): JotformResponse + public function updateSettings(array $params): ?array { return $this->client->post("{$this->name}/settings", $params); } - public function history(): JotformResponse + public function history(): ?array { return $this->client->get("{$this->name}/history", $this->getQueries()); } diff --git a/tests/FolderTest.php b/tests/FolderTest.php index c039a63..83badcf 100644 --- a/tests/FolderTest.php +++ b/tests/FolderTest.php @@ -8,10 +8,9 @@ class FolderTest extends TestCase public function test_get_folder_with_invalid_id() { // [TODO] - $response = $this->jotform->folder("")->get(); - $folder = $response->toObject(); + $folder = $this->jotform->folder("")->get(); - $this->assertEquals(200, $response->getStatusCode()); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); $this->assertEmpty($folder); } } diff --git a/tests/ReportTest.php b/tests/ReportTest.php index 035a33f..4a3614e 100644 --- a/tests/ReportTest.php +++ b/tests/ReportTest.php @@ -10,11 +10,10 @@ class ReportTest extends TestCase public function test_get_report_with_invalid_id() { // [TODO] - // $this->expectException(JotformException::class); - $response = $this->jotform->report("")->get(); - $report = $response->toArray(); + $this->expectException(JotformException::class); + $report = $this->jotform->report("")->get(); - $this->assertEquals(200, $response->getStatusCode()); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); $this->assertEmpty($report); } } diff --git a/tests/SubmissionTest.php b/tests/SubmissionTest.php index 09feae3..fa3fcc3 100644 --- a/tests/SubmissionTest.php +++ b/tests/SubmissionTest.php @@ -7,20 +7,35 @@ class SubmissionTest extends TestCase { /** @test */ - public function test_get_submission_with_invalid_id() + // public function test_get_submission_with_invalid_id() + // { + // $this->expectException(JotformException::class); + // $submissions = $this->jotform->form('111222333444')->submissions(); + // $this->jotform->submission($submissions[0]['id'])->get(); + // } + + /** @test */ + public function test_get_submission_with_valid_id() { - // [TODO] - $this->expectException(JotformException::class); - $this->jotform->submission("")->get(); + $forms = $this->jotform->user()->forms(); + $forms = array_filter($forms, function ($form) { + return !is_null($form['last_submission']); + }); + $form = array_shift($forms); + $submissions = $this->jotform->form($form['id'])->submissions(); + $this->jotform->submission($submissions[0]['id'])->get(); + + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); } /** @test */ public function test_get_all_submissions_by_form_id() { // [TODO] - $response = $this->jotform->form("") - ->limit(100)->orderBy('created_at')->getSubmissions(); + $forms = $this->jotform->user()->forms(); + $response = $this->jotform->form($forms[0]['id']) + ->limit(100)->orderBy('created_at')->submissions(); - $this->assertEquals(200, $response->getStatusCode()); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); } } diff --git a/tests/SystemTest.php b/tests/SystemTest.php index 550c352..047729f 100644 --- a/tests/SystemTest.php +++ b/tests/SystemTest.php @@ -7,35 +7,35 @@ class SystemTest extends TestCase /** @test */ public function test_get_system_plan_for_free() { - $response = $this->jotform->system()->plan('free'); - $this->assertEquals(200, $response->getStatusCode()); + $this->jotform->system()->plan('free'); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); } /** @test */ public function test_get_system_plan_for_bronze() { - $response = $this->jotform->system()->plan('bronze'); - $this->assertEquals(200, $response->getStatusCode()); + $this->jotform->system()->plan('bronze'); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); } /** @test */ public function test_get_system_plan_for_silver() { - $response = $this->jotform->system()->plan('silver'); - $this->assertEquals(200, $response->getStatusCode()); + $this->jotform->system()->plan('silver'); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); } /** @test */ public function test_get_system_plan_for_gold() { - $response = $this->jotform->system()->plan('gold'); - $this->assertEquals(200, $response->getStatusCode()); + $this->jotform->system()->plan('gold'); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); } /** @test */ public function test_get_system_plan_for_platinum() { - $response = $this->jotform->system()->plan('platinum'); - $this->assertEquals(200, $response->getStatusCode()); + $this->jotform->system()->plan('platinum'); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); } } diff --git a/tests/TestCase.php b/tests/TestCase.php index bc6a87d..e76c597 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -16,8 +16,7 @@ abstract class TestCase extends BaseTestCase protected function setUp(): void { - // [TODO] - $this->client = new JotformClient($_ENV['API_KEY']); + $this->client = new JotformClient(getenv('JOTFORM_API_KEY')); $this->jotform = new Jotform($this->client); } } diff --git a/tests/UserTest.php b/tests/UserTest.php index 5f6e13c..3ab8f41 100644 --- a/tests/UserTest.php +++ b/tests/UserTest.php @@ -7,21 +7,21 @@ class UserTest extends TestCase /** @test */ public function test_get_user() { - $response = $this->jotform->user()->get(); - $this->assertEquals(200, $response->getStatusCode()); + $this->jotform->user()->get(); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); } /** @test */ public function test_get_user_usage() { - $response = $this->jotform->user()->usage(); - $this->assertEquals(200, $response->getStatusCode()); + $this->jotform->user()->usage(); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); } /** @test */ public function test_get_user_forms() { - $response = $this->jotform->user()->forms(); - $this->assertEquals(200, $response->getStatusCode()); + $this->jotform->user()->forms(); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); } } From b3c20fc903f637845efb2dea50703c8c2562e0e9 Mon Sep 17 00:00:00 2001 From: burakdemirtas-jtf Date: Mon, 8 Nov 2021 07:23:37 +0000 Subject: [PATCH 07/22] Fix syntax styling --- src/JotformClient.php | 1 + src/Services/Folder.php | 1 - src/Services/Report.php | 1 - src/Services/System.php | 2 -- src/Services/User.php | 1 - 5 files changed, 1 insertion(+), 5 deletions(-) diff --git a/src/JotformClient.php b/src/JotformClient.php index 64ae9bd..7919c74 100644 --- a/src/JotformClient.php +++ b/src/JotformClient.php @@ -186,6 +186,7 @@ protected function prepareAndSendRequest(string $method, string $path, $params = } $this->response = new JotformResponse($response, $statusCode, $response["message"] ?? null); + return $response; } diff --git a/src/Services/Folder.php b/src/Services/Folder.php index 294823d..ec967a1 100644 --- a/src/Services/Folder.php +++ b/src/Services/Folder.php @@ -3,7 +3,6 @@ namespace Jotform\Services; use Jotform\JotformClient; -use Jotform\JotformResponse; class Folder extends Service { diff --git a/src/Services/Report.php b/src/Services/Report.php index 85ff121..9836549 100644 --- a/src/Services/Report.php +++ b/src/Services/Report.php @@ -3,7 +3,6 @@ namespace Jotform\Services; use Jotform\JotformClient; -use Jotform\JotformResponse; class Report extends Service { diff --git a/src/Services/System.php b/src/Services/System.php index 82f4ebb..fd09b8d 100644 --- a/src/Services/System.php +++ b/src/Services/System.php @@ -2,8 +2,6 @@ namespace Jotform\Services; -use Jotform\JotformResponse; - class System extends Service { /** @var string */ diff --git a/src/Services/User.php b/src/Services/User.php index 8850136..bceea34 100644 --- a/src/Services/User.php +++ b/src/Services/User.php @@ -2,7 +2,6 @@ namespace Jotform\Services; -use Jotform\JotformResponse; use Jotform\Traits\UseConditions; use Jotform\Traits\UseQuery; From 36c8e9193a374a16568cb9e1c5224b76b0860163 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Demirta=C5=9F?= Date: Mon, 8 Nov 2021 10:27:52 +0300 Subject: [PATCH 08/22] Updated workflow --- .github/workflows/run-tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index e2b386d..f2b2318 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -10,7 +10,7 @@ jobs: matrix: os: [ubuntu-latest, windows-latest] php: [7.3, 8.0] - stability: [prefer-lowest, prefer-stable] + stability: [prefer-stable] name: P${{ matrix.php }} - ${{ matrix.stability }} - ${{ matrix.os }} From 58802943d79020109baf84676b5a80b42e29f93e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Demirta=C5=9F?= Date: Mon, 8 Nov 2021 10:31:41 +0300 Subject: [PATCH 09/22] Fixed Stringable::__toString() compatible. --- src/JotformResponse.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/JotformResponse.php b/src/JotformResponse.php index d01525a..92828f2 100644 --- a/src/JotformResponse.php +++ b/src/JotformResponse.php @@ -37,7 +37,7 @@ public function getMessage(): ?string return $this->message; } - public function __toString(): ?string + public function __toString(): string { return $this->toJson(); } From 0ebfd1b5de629261e535cf5879e8c78a91bfc408 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Demirta=C5=9F?= Date: Mon, 8 Nov 2021 10:49:02 +0300 Subject: [PATCH 10/22] Update README --- README.md | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6e8f3dc..33633b1 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ $client = new JotformClient(''); $jotform = new Jotform($client); $forms = $jotform->user()->forms(); -foreach ($forms->toArray() as $form) { +foreach ($forms as $form) { echo $form['title'] . PHP_EOL; } ``` @@ -67,7 +67,7 @@ try { $client = new JotformClient(''); $jotform = new Jotform($client); - $forms = $jotform->user()->forms()->toArray(); + $forms = $jotform->user()->forms(); $latestForm = $forms[0]; $latestFormId = $latestForm['id']; @@ -142,7 +142,7 @@ try { $jotform = new Jotform($client); $submissions = $jotform->user()->limit(50)->orderBy('created_at')->submissions(); - foreach ($submissions->toArray() as $submission) { + foreach ($submissions as $submission) { $result = $jotform->submission($submission['id'])->delete(); echo $result . PHP_EOL; } @@ -151,5 +151,12 @@ catch (Exception $e) { var_dump($e->getMessage()); } ``` + +## Notes +- Condition methods: `filter`, `limit`, `offset`, `orderBy` +- Query methods: `action`, `sortBy`, `date`, `startDate`, `endDate` +- Limitation: *(for now)* + - **Condition methods** can be used with `Form` and `User` services. + - **Query methods** can be used with `User` service. --- Jotform From e84ae4d5038f13b0a4820c83e42a1df882a40ff3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Demirta=C5=9F?= Date: Tue, 12 Oct 2021 01:21:37 +0300 Subject: [PATCH 11/22] First commit for new version of Jotform PHP API --- .editorconfig | 15 + .github/FUNDING.yml | 1 + .github/SECURITY.yml | 3 + .github/workflows/php-cs-fixer.yml | 23 + .github/workflows/run-tests.yml | 37 + .gitignore | 12 + .php-cs-fixer.dist.php | 39 + JotForm.php | 664 +----------------- README.md | 228 +++--- composer.json | 28 +- phpunit.xml.dist | 34 + src/Exceptions/InvalidKeyException.php | 11 + src/Exceptions/JotformException.php | 7 + .../ServiceUnavailableException.php | 11 + src/Jotform.php | 64 ++ src/JotformClient.php | 220 ++++++ src/JotformResponse.php | 49 ++ src/Services/Folder.php | 31 + src/Services/Form.php | 190 +++++ src/Services/Report.php | 36 + src/Services/Service.php | 19 + src/Services/Submission.php | 78 ++ src/Services/System.php | 21 + src/Services/User.php | 86 +++ src/Traits/UseConditions.php | 46 ++ src/Traits/UseQuery.php | 54 ++ tests/FolderTest.php | 17 + tests/FormTest.php | 16 + tests/ReportTest.php | 20 + tests/SubmissionTest.php | 26 + tests/SystemTest.php | 41 ++ tests/TestCase.php | 23 + tests/UserTest.php | 27 + 33 files changed, 1405 insertions(+), 772 deletions(-) create mode 100644 .editorconfig create mode 100644 .github/FUNDING.yml create mode 100644 .github/SECURITY.yml create mode 100644 .github/workflows/php-cs-fixer.yml create mode 100644 .github/workflows/run-tests.yml create mode 100644 .gitignore create mode 100644 .php-cs-fixer.dist.php create mode 100644 phpunit.xml.dist create mode 100644 src/Exceptions/InvalidKeyException.php create mode 100644 src/Exceptions/JotformException.php create mode 100644 src/Exceptions/ServiceUnavailableException.php create mode 100644 src/Jotform.php create mode 100644 src/JotformClient.php create mode 100644 src/JotformResponse.php create mode 100644 src/Services/Folder.php create mode 100644 src/Services/Form.php create mode 100644 src/Services/Report.php create mode 100644 src/Services/Service.php create mode 100644 src/Services/Submission.php create mode 100644 src/Services/System.php create mode 100644 src/Services/User.php create mode 100644 src/Traits/UseConditions.php create mode 100644 src/Traits/UseQuery.php create mode 100644 tests/FolderTest.php create mode 100644 tests/FormTest.php create mode 100644 tests/ReportTest.php create mode 100644 tests/SubmissionTest.php create mode 100644 tests/SystemTest.php create mode 100644 tests/TestCase.php create mode 100644 tests/UserTest.php diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..665acc3 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +root = true + +[*] +charset = utf-8 +indent_size = 4 +indent_style = space +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false + +[*.{yml,yaml}] +indent_size = 2 \ No newline at end of file diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..fcd2991 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +github: :jotform-api-php diff --git a/.github/SECURITY.yml b/.github/SECURITY.yml new file mode 100644 index 0000000..15e17cf --- /dev/null +++ b/.github/SECURITY.yml @@ -0,0 +1,3 @@ +# Security Policy + +If you discover any security related issues, please email api@jotform.com instead of using the issue tracker. \ No newline at end of file diff --git a/.github/workflows/php-cs-fixer.yml b/.github/workflows/php-cs-fixer.yml new file mode 100644 index 0000000..584dc55 --- /dev/null +++ b/.github/workflows/php-cs-fixer.yml @@ -0,0 +1,23 @@ +name: Check & fix styling + +on: [push] + +jobs: + php-cs-fixer: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v2 + with: + ref: ${{ github.head_ref }} + + - name: Run PHP CS Fixer + uses: docker://oskarstark/php-cs-fixer-ga + with: + args: --config=.php-cs-fixer.dist.php --allow-risky=yes + + - name: Commit changes + uses: stefanzweifel/git-auto-commit-action@v4 + with: + commit_message: Fix syntax styling \ No newline at end of file diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml new file mode 100644 index 0000000..edc2f41 --- /dev/null +++ b/.github/workflows/run-tests.yml @@ -0,0 +1,37 @@ +name: Tests + +on: [push, pull_request] + +jobs: + test: + runs-on: ${{ matrix.os }} + strategy: + fail-fast: true + matrix: + os: [ubuntu-latest, windows-latest] + php: [7.3, 8.0] + stability: [prefer-lowest, prefer-stable] + + name: P${{ matrix.php }} - ${{ matrix.stability }} - ${{ matrix.os }} + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, fileinfo + coverage: none + + - name: Setup problem matchers + run: | + echo "::add-matcher::${{ runner.tool_cache }}/php.json" + echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" + + - name: Install dependencies + run: composer update --${{ matrix.stability }} --prefer-dist --no-interaction + + - name: Execute tests + run: composer test \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d687012 --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +.idea +.vscode +.php_cs +.php_cs.cache +.phpunit.result.cache +build +composer.lock +coverage +docs +phpunit.xml +vendor +.php-cs-fixer.cache \ No newline at end of file diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 0000000..33b3b63 --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,39 @@ +in([ + __DIR__ . '/src', + __DIR__ . '/tests', + ]) + ->name('*.php') + ->ignoreDotFiles(true) + ->ignoreVCS(true); + +return (new PhpCsFixer\Config()) + ->setRules([ + '@PSR12' => true, + 'array_syntax' => ['syntax' => 'short'], + 'ordered_imports' => ['sort_algorithm' => 'alpha'], + 'no_unused_imports' => true, + 'not_operator_with_successor_space' => true, + 'trailing_comma_in_multiline' => true, + 'phpdoc_scalar' => true, + 'unary_operator_spaces' => true, + 'binary_operator_spaces' => true, + 'blank_line_before_statement' => [ + 'statements' => ['break', 'continue', 'declare', 'return', 'throw', 'try'], + ], + 'phpdoc_single_line_var_spacing' => true, + 'phpdoc_var_without_name' => true, + 'class_attributes_separation' => [ + 'elements' => [ + 'method' => 'one', + ], + ], + 'method_argument_space' => [ + 'on_multiline' => 'ensure_fully_multiline', + 'keep_multiple_spaces_after_comma' => true, + ], + 'single_trait_insert_per_statement' => true, + ]) + ->setFinder($finder); \ No newline at end of file diff --git a/JotForm.php b/JotForm.php index 836367a..5224f63 100644 --- a/JotForm.php +++ b/JotForm.php @@ -2,656 +2,22 @@ /** * JotForm API - PHP Client * - * @copyright 2013 Interlogy, LLC. - * @link http://www.jotform.com - * @version 1.0 - * @package JotFormAPI + * @copyright 2021 Jotform, LLC. + * @link https://www.jotform.com + * @version 2.0 + * @package Jotform */ -class JotForm { - public $baseURL = 'https://api.jotform.com'; - private $apiKey; - private $debugMode; - private $outputType; - private $apiVersion = 'v1'; - - public function __construct($apiKey = '', $outputType = 'json', $debugMode = false) { - - $this->apiKey = $apiKey; - $this->debugMode = $debugMode; - $this->outputType = strtolower($outputType); - $user = $this->getUser(); - # set base url for EU users - if (isset($user['euOnly'])) { - $this->baseURL = 'https://eu-api.jotform.com'; - } - } - - public function __get($property) { - if (property_exists($this, $property)) { - return $this->$property; - } - } - - public function __set($property, $value) { - if (property_exists($this, $property)) { - $this->$property = $value; - } - } - - private function _debugLog($str) { - if ($this->debugMode){ - print_r(PHP_EOL); - print_r($str); - } - } - - private function _debugDump($obj) { - if ($this->debugMode){ - print_r(PHP_EOL); - var_dump($obj); - } - } - - private function _executeHttpRequest($path, $params = array(), $method) { - if ($this->outputType != 'json') { - $path = "{$path}.xml"; - } - - $url = implode('/', array($this->baseURL, $this->apiVersion, $path)); - - $this->_debugDump($params); - - if ($method == 'GET' && $params != null){ - $params_array = array(); - foreach ($params as $key => $value) { - $params_array[] = "{$key}={$value}"; - } - $params_string = '?' . implode('&', $params_array); - unset($params_array); - $url = $url.$params_string; - $this->_debugLog('params string: '.$params_string); - } - - $this->_debugLog('fetching url: '.$url); - - $ch = curl_init(); - - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_USERAGENT, 'JOTFORM_PHP_WRAPPER'); - curl_setopt($ch, CURLOPT_HTTPHEADER, array('APIKEY: '.$this->apiKey)); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); - - switch ($method) { - case 'POST': - $this->_debugLog('posting'); - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, $params); - break; - case 'PUT': - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); - curl_setopt($ch, CURLOPT_POSTFIELDS, $params); - break; - case 'DELETE': - $this->_debugLog('delete'); - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); - break; - } - - $result = curl_exec($ch); - - if ($result == false) { - throw new Exception(curl_error($ch), 400); - } - - $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE); - $this->_debugLog('http code is: '.$http_status); - - if ($this->outputType == 'json') { - $result_obj = json_decode($result, true); - } else { - $result_obj = utf8_decode($result); - } - - if ($http_status != 200) { - - switch ($http_status) { - case 400: - case 403: - case 404: - throw new JotFormException($result_obj["message"], $http_status ); - break; - case 401: - throw new JotFormException("Invalid API key or Unauthorized API call", $http_status); - break; - case 503: - throw new JotFormException("Service is unavailable, rate limits etc exceeded!", $http_status); - break; - - default: - throw new JotFormException($result_obj["info"], $http_status); - break; - } - } - - curl_close($ch); - - if ($this->outputType == 'json') { - if (isset($result_obj['content'])) { - return $result_obj['content']; - } else { - return $result_obj; - } - } else { - return $result_obj; - } - } - - private function _executeGetRequest($url, $params = array()) { - return $this->_executeHttpRequest($url, $params, 'GET'); - } - - private function _executePostRequest($url, $params) { - return $this->_executeHttpRequest($url, $params, 'POST'); - } - - private function _executePutRequest($url, $params) { - return $this->_executeHttpRequest($url, $params, 'PUT'); - } - - private function _executeDeleteRequest($url, $params = array()) { - return $this->_executeHttpRequest($url, $params, 'DELETE'); - } - - private function createConditions($offset, $limit, $filter, $orderby) { - $params = array(); - foreach (array('offset', 'limit', 'filter', 'orderby') as $arg) { - if (${$arg}) { - $params[strtolower($arg)] = ${$arg}; - if ($arg == "filter") { - $params[$arg] = urlencode(json_encode($params[$arg])); - } - } - } - return $params; - } - - private function createHistoryQuery($action, $date, $sortBy, $startDate, $endDate) { - foreach (array('action', 'date', 'sortBy', 'startDate', 'endDate') as $arg) { - if (${$arg}) { - $params[$arg] = ${$arg}; - } - } - return $params; - } - - /** - * [getUser Get user account details for a JotForm user] - * @return [array] [Returns user account type, avatar URL, name, email, website URL and account limits.] - */ - public function getUser() { - $res = $this->_executeGetRequest('user'); - return $res; - } - - /** - * [getUserUsage Get number of form submissions received this month] - * @return [array] [Returns number of submissions, number of SSL form submissions, payment form submissions and upload space used by user.] - */ - public function getUsage(){ - return $this->_executeGetRequest('user/usage'); - } - - /** - * [getForms Get a list of forms for this account] - * @param [integer] $offset [Start of each result set for form list. (optional)] - * @param [integer] $limit [Number of results in each result set for form list. (optional)] - * @param [array] $filter [Filters the query results to fetch a specific form range.(optional)] - * @param [string] $orderBy [Order results by a form field name. (optional)] - * @return [array] [Returns basic details such as title of the form, when it was created, number of new and total submissions.] - */ - public function getForms($offset = 0, $limit = 0, $filter = null, $orderby = null) { - $params = $this->createConditions($offset, $limit, $filter, $orderby); - return $this->_executeGetRequest('user/forms', $params); - } - - /** - * [getSubmissions Get a list of submissions for this account] - * @param [int] $offset [Start of each result set for form list. (optional)] - * @param [int] $limit [Number of results in each result set for form list. (optional)] - * @param [array] $filter [Filters the query results to fetch a specific form range.(optional)] - * @param [string] $orderBy [Order results by a form field name. (optional)] - * @return [array] [Returns basic details such as title of the form, when it was created, number of new and total submissions.] - */ - public function getSubmissions($offset = 0, $limit = 0, $filter = null, $orderby = null) { - $params = $this->createConditions($offset, $limit, $filter, $orderby); - return $this->_executeGetRequest('user/submissions', $params); - } - - /** - * [getUserSubusers Get a list of sub users for this account] - * @return [array] [Returns list of forms and form folders with access privileges.] - */ - public function getSubusers() { - return $this->_executeGetRequest('user/subusers'); - } - - /** - * [getUserFolders Get a list of form folders for this account] - * @return [array] [Returns name of the folder and owner of the folder for shared folders.] - */ - public function getFolders() { - return $this->_executeGetRequest('user/folders'); - } - - /** - * [getReports List of URLS for reports in this account] - * @return [array] [Returns reports for all of the forms. ie. Excel, CSV, printable charts, embeddable HTML tables.] - */ - public function getReports() { - return $this->_executeGetRequest('user/reports'); - } - - /** - * [getSettings Get user's settings for this account] - * @return [array] [Returns user's time zone and language.] - */ - public function getSettings() { - return $this->_executeGetRequest('user/settings'); - } - - /** - * [updateSettings Update user's settings] - * @param [array] $settings [New user setting values with setting keys] - * @return [array] [Returns changes on user settings] - */ - public function updateSettings($settings) { - return $this->_executePostRequest('user/settings', $settings); - } - - /** - * [getHistory Get user activity log] - * @param [enum] $action [Filter results by activity performed. Default is 'all'.] - * @param [enum] $date [Limit results by a date range. If you'd like to limit results by specific dates you can use startDate and endDate fields instead.] - * @param [enum] $sortBy [Lists results by ascending and descending order.] - * @param [string] $startDate [Limit results to only after a specific date. Format: MM/DD/YYYY.] - * @param [string] $endDate [Limit results to only before a specific date. Format: MM/DD/YYYY.] - * @return [array] [Returns activity log about things like forms created/modified/deleted, account logins and other operations.] - */ - public function getHistory($action = null, $date = null, $sortBy = null, $startDate = null, $endDate = null) { - $params = $this->createHistoryQuery($action, $date, $sortBy, $startDate, $endDate); - return $this->_executeGetRequest('user/history', $params); - } - - /** - * [getForm Get basic information about a form.] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @return [array] [Returns form ID, status, update and creation dates, submission count etc.] - */ - public function getForm($formID) { - return $this->_executeGetRequest('form/'. $formID); - } - - /** - * [getFormQuestions Get a list of all questions on a form.] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @return [array] [Returns question properties of a form.] - */ - public function getFormQuestions($formID) { - return $this->_executeGetRequest("form/{$formID}/questions"); - } - - /** - *[getFormQuestion Get details about a question] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [integer] $qid [Identifier for each question on a form. You can get a list of question IDs from /form/{id}/questions.] - * @return [array] [Returns question properties like required and validation.] - */ - public function getFormQuestion($formID, $qid) { - return $this->_executeGetRequest("form/{$formID}/question/{$qid}"); - } - - /** - * [getFormSubmissions List of a form submissions] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [int] $offset [Start of each result set for form list. (optional)] - * @param [int] $limit [Number of results in each result set for form list. (optional)] - * @param [array] $filter [Filters the query results to fetch a specific form range.(optional)] - * @param [string] $orderBy [Order results by a form field name. (optional)] - * @return [array] [Returns submissions of a specific form.] - */ - public function getFormSubmissions($formID, $offset = 0, $limit = 0, $filter = null, $orderby = null) { - $params = $this->createConditions($offset, $limit, $filter, $orderby); - return $this->_executeGetRequest("form/{$formID}/submissions", $params); - } - - /** - * [createFormSubmissions Submit data to this form using the API] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [array] $submission [Submission data with question IDs.] - * @return [array] [Returns posted submission ID and URL.] - */ - public function createFormSubmission($formID, $submission) { - $sub = array(); - foreach ($submission as $key => $value) { - if (strpos($key, '_')) { - $qid = substr($key, 0, strpos($key, '_')); - $type = substr($key, strpos($key, '_') + 1); - $sub["submission[{$qid}][{$type}]"] = $value; - } else { - $sub["submission[{$key}]"] = $value; - } - } - return $this->_executePostRequest("form/{$formID}/submissions", $sub); - } - - /** - * [createFormSubmissions Submit data to this form using the API] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [json] $submissions [Submission data with question IDs.] - * @return [array] - */ - public function createFormSubmissions($formID, $submissions) { - return $this->_executePutRequest("form/".$formID."/submissions", $submissions); - } - - /** - * [getFormFiles List of files uploaded on a form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @return [array] [Returns uploaded file information and URLs on a specific form.] - */ - public function getFormFiles($formID) { - return $this->_executeGetRequest("form/{$formID}/files"); - } - - /** - * [getFormWebhooks Get list of webhooks for a form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @return [array] [Returns list of webhooks for a specific form.] - */ - public function getFormWebhooks($formID) { - return $this->_executeGetRequest("form/{$formID}/webhooks"); - } - - /** - * [createFormWebhook Add a new webhook] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [string] $webhookURL [Webhook URL is where form data will be posted when form is submitted.] - * @return [array] [Returns list of webhooks for a specific form.] - */ - public function createFormWebhook($formID, $webhookURL) { - return $this->_executePostRequest("form/{$formID}/webhooks", array('webhookURL' => $webhookURL) ); - } - - /** - * [deleteFormWebhook] [Delete a specific webhook of a form.] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [integer] $webhookID [You can get webhook IDs when you call /form/{formID}/webhooks.] - * @return [array] [Returns remaining webhook URLs of form.] - */ - public function deleteFormWebhook($formID, $webhookID) { - return $this->_executeDeleteRequest("form/{$formID}/webhooks/{$webhookID}", null); - } - - /** - * [getSubmission Get submission data] - * @param [integer] $sid [You can get submission IDs when you call /form/{id}/submissions.] - * @return [array] [Returns information and answers of a specific submission.] - */ - public function getSubmission($sid) { - return $this->_executeGetRequest("submission/{$sid}"); - } - - /** - * [getReport Get report details] - * @param [integer] $reportID [You can get a list of reports from /user/reports.] - * @return [array] [Returns properties of a speceific report like fields and status.] - */ - public function getReport($reportID) { - return $this->_executeGetRequest("report/{$reportID}"); - } - - /** - * [getFolder Get folder details] - * @param [integer] $folderID [You can get a list of folders from /user/folders.] - * @return [array] [Returns a list of forms in a folder, and other details about the form such as folder color.] - */ - public function getFolder($folderID) { - return $this->_executeGetRequest("folder/{$folderID}"); - } - - /** - * [getFormProperties Get a list of all properties on a form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @return [array] [Returns form properties like width, expiration date, style etc.] - */ - public function getFormProperties($formID) { - return $this->_executeGetRequest("form/{$formID}/properties"); - } - - /** - * [getFormProperty Get a specific property of the form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [string] $propertyKey [You can get property keys when you call /form/{id}/properties.] - * @return [array] [Returns given property key value.] - */ - public function getFormProperty($formID, $propertyKey) { - return $this->_executeGetRequest("form/{$formID}/properties/{$propertyKey}"); - } - - /** - * [getFormReports Get all the reports of a form, such as excel, csv, grid, html, etc.] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @return [array] [Returns a list of reports in a form, and other details about the reports such as title.] - */ - public function getFormReports($formID) { - return $this->_executeGetRequest("form/{$formID}/reports"); - } - - /** - * [createReport Create new report of a form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [array] $report [Report details. List type, title etc.] - * @return [array] [Returns report details and URL.] - */ - public function createReport($formID, $report) { - return $this->_executePostRequest("form/{$formID}/reports", $report); - } - - /** - * [deleteSubmission Delete a single submission] - * @param [integer] $sid [You can get submission IDs when you call /user/submissions.] - * @return [array] [Returns status of request.] - */ - public function deleteSubmission($sid) { - return $this->_executeDeleteRequest("submission/{$sid}"); - } - - /** - * [editSubmission Edit a single submission] - * @param [integer] $sid [You can get submission IDs when you call /form/{id}/submissions.] - * @param [array] $submission [New submission data with question IDs.] - * @return [array] [Returns status of request.] - */ - public function editSubmission($sid, $submission) { - $sub = array(); - foreach ($submission as $key => $value) { - if (strpos($key, '_') && $key != 'created_at') { - $qid = substr($key, 0, strpos($key, '_')); - $type = substr($key, strpos($key, '_') + 1); - $sub["submission[{$qid}][{$type}]"] = $value; - } else { - $sub["submission[{$key}]"] = $value; - } - } - return $this->_executePostRequest("submission/".$sid, $sub); - } - - /** - * [cloneForm Clone a single form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @return [array] [Returns status of request.] - */ - public function cloneForm($formID) { - return $this->_executePostRequest("form/{$formID}/clone", null); - } - - /** - * [deleteFormQuestion Delete a single form question] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [integer] $qid [Identifier for each question on a form. You can get a list of question IDs from /form/{id}/questions.] - * @return [array] [Returns status of request.] - */ - public function deleteFormQuestion($formID, $qid) { - return $this->_executeDeleteRequest("form/{$formID}/question/{$qid}", null); - } - - /** - * [createFormQuestion Add new question to specified form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [array] $question [New question properties like type and text.] - * @return [array] [Returns properties of new question.] - */ - public function createFormQuestion($formID, $question) { - $params = array(); - foreach ($question as $key => $value) { - $params["question[{$key}]"] = $value; +spl_autoload_register(function ($class) { + $paths = [ + __DIR__ . '/src', + __DIR__ . '/src/Services', + __DIR__ . '/src/Traits', + __DIR__ . '/src/Exceptions', + ]; + foreach ($paths as $path) { + if (is_readable($file = "{$path}/{$class}.php")) { + include_once($file); } - return $this->_executePostRequest("form/{$formID}/questions", $params); - } - - /** - * [createFormQuestions Add new questions to specified form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [json] $questions [New question properties like type and text.] - * @return [array] [Returns properties of new questions.] - */ - public function createFormQuestions($formID, $questions) { - return $this->_executePutRequest("form/{$formID}/questions", $questions); - } - - /** - * [editFormQuestion Add or edit a single question properties] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [integer] $qid [Identifier for each question on a form. You can get a list of question IDs from /form/{id}/questions.] - * @param [array] $questionProperties [New question properties like text and order.] - * @return [array] [Returns edited property and type of question.] - */ - public function editFormQuestion($formID, $qid, $questionProperties) { - $question = array(); - foreach ($questionProperties as $key => $value) { - $question["question[{$key}]"] = $value; - } - return $this->_executePostRequest("form/{$formID}/question/{$qid}", $question); - } - - /** - * [setFormProperties Add or edit properties of a specific form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [array] $formProperties [New properties like label width.] - * @return [array] [Returns edited properties.] - */ - public function setFormProperties($formID, $formProperties) { - $properties = array(); - foreach ($formProperties as $key => $value) { - $properties["properties[{$key}]"] = $value; - } - return $this->_executePostRequest("form/{$formID}/properties", $properties); - } - - /** - *[setMultipleFormProperties Add or edit properties of a specific form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @param [json] $formProperties [New properties like label width.] - * @return [array] [Returns edited properties.] - */ - public function setMultipleFormProperties($formID, $formProperties) { - return $this->_executePutRequest("form/{$formID}/properties", $formProperties); } - - /** - * [createForm Create a new form] - * @param [array] $form [Questions, properties and emails of new form.] - * @return [array] [Returns new form.] - */ - public function createForm($form) { - $params = array(); - foreach ($form as $key => $value) { - foreach ($value as $k => $v) { - if ($key == "properties") { - $params["{$key}[{$k}]"] = $v; - } else { - foreach ($v as $a => $b) { - $params["{$key}[{$k}][{$a}]"] = $b; - } - } - } - } - return $this->_executePostRequest('user/forms', $params); - } - - /** - * [createForm Create new forms] - * @param [json] $form [Questions, properties and emails of forms.] - * @return [array] [Returns new forms.] - */ - public function createForms($forms) { - return $this->_executePutRequest('user/forms', $forms); - } - - /** - * [deleteForm Delete a specific form] - * @param [integer] $formID [Form ID is the numbers you see on a form URL. You can get form IDs when you call /user/forms.] - * @return [array] [Returns roperties of deleted form.] - */ - public function deleteForm($formID) { - return $this->_executeDeleteRequest("form/{$formID}", null); - } - - /** - * [registerUser Register with username, password and email] - * @param [array] $userDetails [username, password and email to register a new user] - * @return [array] [Returns new user's details] - */ - public function registerUser($userDetails) { - return $this->_executePostRequest('user/register', $userDetails); - } - - /** - * [loginUser Login user with given credentials] - * @param [array] $credentials [Username, password, application name and access type of user] - * @return [array] [Returns logged in user's settings and app key.] - */ - public function loginUser($credentials) { - return $this->_executePostRequest('user/login', $credentials); - } - - /** - * [logoutUser Logout User] - * @return [array] [Status of request] - */ - public function logoutUser() { - return $this->_executeGetRequest('user/logout'); - } - - /** - * [getPlan Get details of a plan] - * @param [string] $planName [Name of the requested plan. FREE, PREMIUM etc.] - * @return [array] [Returns details of a plan] - */ - public function getPlan($planName) { - return $this->_executeGetRequest("system/plan/{$planName}"); - } - - /** - * [deleteReport Delete a specific report] - * @param [integer] $formID [$reportID [You can get a list of reports from /user/reports.] - * @return [array] [Returns status of request.] - */ - public function deleteReport($reportID) { - return $this->_executeDeleteRequest("report/{$reportID}", null); - } -} - -class JotFormException extends Exception {} +}); diff --git a/README.md b/README.md index 5c96746..963a893 100644 --- a/README.md +++ b/README.md @@ -3,157 +3,153 @@ jotform-api-php [JotForm API](http://api.jotform.com/docs/) - PHP Client -### Installation +## Installation -Install via git clone: - - $ git clone git://github.com/jotform/jotform-api-php.git - $ cd jotform-api-php +1- Install via [Composer](http://getcomposer.org/) -or +``` +$ composer require jotform/jotform-api-php +``` +and add following line to your php file: +```php +require "vendor/autoload.php"; +``` -Install via Composer package manager (http://getcomposer.org/) - -_composer.json_ -```json - { - "require": { - "jotform/jotform-api-php": "dev-master" - } - } +2- Install and use manually: +``` +$ git clone https://github.com/jotform/jotform-api-php.git ``` +and add following line to your php file: +```php +require "jotform-api-php/Jotform.php"; +``` +If you install the package into another directory, you should update path for `require` command above. - $ php composer.phar install -### Documentation +## Documentation -You can find the docs for the API of this client at [http://api.jotform.com/docs/](http://api.jotform.com/docs) +You can find the docs for the API of this client at [Jotform API Documentation](http://api.jotform.com/docs). -### Authentication +## Authentication -JotForm API requires API key for all user related calls. You can create your API Keys at [API section](http://www.jotform.com/myaccount/api) of My Account page. +JotForm API requires API key for all user related calls. You can create your API Keys at [API section](http://www.jotform.com/myaccount/api) of My Account page. -### Examples +## Examples -Print all forms of the user - +1- Print all forms of the user: ```php getForms(); - - foreach ($forms as $form) { - print $form["title"]; - } +require "vendor/autoload.php"; -?> -``` -Get submissions of the latest form - +use Jotform\Jotform; +use Jotform\JotformClient; + +$client = new JotformClient(""); +$jotform = new Jotform($client); + +$forms = $jotform->user()->forms(); +foreach ($forms->toArray() as $form) { + echo $form["title"] . PHP_EOL; +} +``` + +2- Get submissions of the latest form: ```php getForms(0, 1, null, null); +require 'vendor/autoload.php'; - $latestForm = $forms[0]; +use Jotform\Jotform; +use Jotform\JotformClient; - $latestFormID = $latestForm["id"]; +try { + $client = new JotformClient(''); + $jotform = new Jotform($client); - $submissions = $jotformAPI->getFormSubmissions($latestFormID); + $forms = $jotform->user()->forms()->toArray(); + $latestForm = $forms[0]; + $latestFormId = $latestForm['id']; - var_dump($submissions); - - } - catch (Exception $e) { - var_dump($e->getMessage()); - } - -?> + $submissions = $jotform->form($latestFormId)->getSubmissions(); + var_dump($submissions); +} +catch (Exception $e) { + var_dump($e->getMessage()); +} ``` -Get latest 100 submissions ordered by creation date - +3- Get latest 100 submissions ordered by creation date: ```php -getSubmissions(0, 100, null, "created_at"); +require 'vendor/autoload.php'; - var_dump($submissions); - } - catch (Exception $e) { - var_dump($e->getMessage()); - } - -?> +use Jotform\Jotform; +use Jotform\JotformClient; + +try { + $client = new JotformClient(''); + $jotform = new Jotform($client); + + $submissions = $jotform->user()->limit(100)->orderBy('created_at')->submissions(); + var_dump($submissions); +} catch (Exception $e) { + var_dump($e->getMessage()); +} ``` -Submission and form filter examples - +4- Submission and form filter examples: ```php - "239252191641336722", - "created_at:gt" => "2013-07-09 07:48:34", - ); - - $subs = $jotformAPI->getSubmissions(0, 0, $filter, ""); - var_dump($subs); - - $filter = array( - "id:gt" => "239176717911737253", - ); - - $formSubs = $jotformAPI->getForms(0, 0, 2, $filter); - var_dump($formSubs); - } catch (Exception $e) { - var_dump($e->getMessage()); - } +require 'vendor/autoload.php'; + +use Jotform\Jotform; +use Jotform\JotformClient; + +try { + $client = new JotformClient(''); + $jotform = new Jotform($client); -?> -``` + $filter = [ + "id:gt" => "239252191641336722", + "created_at:gt" => "2013-07-09 07:48:34", + ]; -Delete last 50 submissions + $submissions = $jotform->user()->filter($filter)->submissions(); + var_dump($submissions); + + $filter = [ + "id:gt" => "239176717911737253", + ]; + + $forms = $jotform->user()->filter($filter)->forms(); + var_dump($forms); +} catch (Exception $e) { + var_dump($e->getMessage()); +} +``` +5- Delete last 50 submissions: ```php -getSubmissions(0, 50, null, null); +require 'vendor/autoload.php'; - foreach ($submissions as $submission) { - $result = $jotformAPI->deleteSubmission($submission["id"]); - print $result; - } - } - catch (Exception $e) { - var_dump($e->getMessage()); +use Jotform\Jotform; +use Jotform\JotformClient; + +try { + $client = new JotformClient(''); + $jotform = new Jotform($client); + + $submissions = $jotform->user()->limit(50)->orderBy('created_at')->submissions(); + foreach ($submissions->toArray() as $submission) { + $result = $jotform->submission($submission["id"])->delete(); + echo $result . PHP_EOL; } - -?> -``` - -First the _JotForm_ class is included from the _jotform-api-php/JotForm.php_ file. This class provides access to JotForm's API. You have to create an API client instance with your API key. -In case of an exception (wrong authentication etc.), you can catch it or let it fail with a fatal error. +} +catch (Exception $e) { + var_dump($e->getMessage()); +} +``` +--- +Jotform diff --git a/composer.json b/composer.json index 9f25b8b..d760733 100644 --- a/composer.json +++ b/composer.json @@ -1,18 +1,32 @@ { "name": "jotform/jotform-api-php", - "version" : "1.0.0-dev", "license": "GPL-3.0+", - "homepage": "http://api.jotform.com", + "homepage": "https://api.jotform.com", "support": { "email": "api@jotform.com", - "wiki": "http://api.jotform.com" + "wiki": "https://api.jotform.com" }, "require": { - "php": ">=5.3.0" + "php": "^7.3|^8.0", + "ext-curl": "*" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^3.0", + "phpunit/phpunit": "^9.5" }, "autoload": { - "classmap": [ - "JotForm.php" - ] + "psr-4": { + "Jotform\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Tests\\": "tests" + } + }, + "scripts": { + "test": "vendor/bin/phpunit", + "coverage": "vendor/bin/phpunit --coverage-html coverage", + "format": "vendor/bin/php-cs-fixer fix --allow-risky=yes" } } diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..1aa095f --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,34 @@ + + + + + ./tests + + + + + ./src + + + + + + \ No newline at end of file diff --git a/src/Exceptions/InvalidKeyException.php b/src/Exceptions/InvalidKeyException.php new file mode 100644 index 0000000..c982064 --- /dev/null +++ b/src/Exceptions/InvalidKeyException.php @@ -0,0 +1,11 @@ +client = $client; + + // Check 'euOnly' flag for User while initializing. + if ($euCheck) { + $user = $this->user()->get()->toArray(); + if (isset($user['euOnly'])) { + $this->client->europeOnly(true); + } + } + } + + public function europeOnly(bool $europeOnly): void + { + $this->client->europeOnly($europeOnly); + } + + public function user(): User + { + return new User($this->client); + } + + public function form(string $formId): Form + { + return new Form($this->client, $formId); + } + + public function submission(string $submissionId): Submission + { + return new Submission($this->client, $submissionId); + } + + public function report(string $reportId): Report + { + return new Report($this->client, $reportId); + } + + public function folder(string $folderId): Folder + { + return new Folder($this->client, $folderId); + } + + public function system(): System + { + return new System($this->client); + } +} diff --git a/src/JotformClient.php b/src/JotformClient.php new file mode 100644 index 0000000..7877a0e --- /dev/null +++ b/src/JotformClient.php @@ -0,0 +1,220 @@ +apiKey = $apiKey; + $this->outputType = $outputType; + $this->debug = $debug; + } + + public function europeOnly(bool $value): void + { + $this->europeOnly = $value; + } + + public function setApiKey(string $apiKey): void + { + $this->apiKey = $apiKey; + } + + public function getApiKey(): string + { + return $this->apiKey; + } + + public function setOutputType(string $outputType): void + { + $this->outputType = $outputType; + } + + public function getOutputType(): string + { + return $this->outputType; + } + + public function setDebugMode(string $debugMode): void + { + $this->debugMode = $debugMode; + } + + public function getDebugMode(): bool + { + return $this->debugMode; + } + + public function get(string $path, array $params = []): JotformResponse + { + return $this->request('get', $path, $params); + } + + public function post(string $path, array $params = []): JotformResponse + { + return $this->request('post', $path, $params); + } + + public function put(string $path, array $params = []): JotformResponse + { + return $this->request('put', $path, $params); + } + + public function delete(string $path, array $params = []): JotformResponse + { + return $this->request('delete', $path, $params); + } + + public function postJson(string $path, string $params = ''): JotformResponse + { + return $this->requestJson('post', $path, $params); + } + + public function putJson(string $path, string $params = ''): JotformResponse + { + return $this->requestJson('put', $path, $params); + } + + public function deleteJson(string $path, string $params = ''): JotformResponse + { + return $this->requestJson('delete', $path, $params); + } + + protected function request(string $method, string $path, array $params = []): JotformResponse + { + return $this->prepareAndSendRequest($method, $path, $params); + } + + protected function requestJson(string $method, string $path, string $params = ''): JotformResponse + { + return $this->prepareAndSendRequest($method, $path, $params); + } + + /** + * @param string  $method Request Method + * @param string $path Request Path/URL + * @param array|string $params Data Array or JSON string + * @return JotformResponse + */ + protected function prepareAndSendRequest(string $method, string $path, $params = []): JotformResponse + { + $method = strtoupper($method); + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $this->normalizeRequestUrl($path, $method)); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_USERAGENT, 'JOTFORM_PHP_WRAPPER'); + curl_setopt($ch, CURLOPT_HTTPHEADER, $this->prepareRequestHeaders($params)); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + + if (in_array($method, ['POST', 'PUT', 'DELETE'])) { + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); + if (! empty($params)) { + curl_setopt($ch, CURLOPT_POSTFIELDS, $params); + } + } + + $response = curl_exec($ch); + $info = curl_getinfo($ch); + $statusCode = $info['http_code']; + curl_close($ch); + + if ($this->debug) { + // [TODO] + // var_dump([ + // 'parameters' => $params, + // 'info' => $info, + // ]); + } + + if ($response == false) { + throw new JotFormException(curl_error($ch), 400); + } + + $response = $this->outputType === self::OUTPUT_JSON + ? json_decode($response, true) + : utf8_decode($response); + + if ($statusCode !== 200) { + switch ($statusCode) { + case 400: + case 403: + case 404: + throw new JotFormException($response["message"] ?? 'Not Found', $statusCode); + + break; + case 401: + throw new InvalidKeyException(); + + break; + case 503: + throw new ServiceUnavailableException(); + + break; + default: + throw new JotFormException($response["info"] ?? 'Unexpected Error', $statusCode); + } + } + + if ($this->outputType === self::OUTPUT_JSON) { + $response = $response['content'] ?? $response; + } + + return new JotformResponse($response, $statusCode, $response["message"] ?? null); + } + + /** + * @param array|string Data Array or JSON string + * @return array + */ + private function prepareRequestHeaders($params): array + { + $headers = [ + "APIKEY: {$this->apiKey}", + ]; + + if (is_string($params)) { + $headers[] = "Content-Type: application/json"; + } + + return $headers; + } + + private function normalizeRequestUrl(string $path, string $method): string + { + $server = $this->europeOnly ? 'eu-api' : 'api'; + $segments = [ + "https://{$server}.jotform.com", + // 'v' . self::API_VERSION, + $path . ($this->outputType === self::OUTPUT_JSON ? '' : '.xml'), + ]; + + $url = implode('/', $segments); + + return $method === 'GET' && ! empty($params) + ? "{$url}?" . http_build_query($params) + : $url; + } +} diff --git a/src/JotformResponse.php b/src/JotformResponse.php new file mode 100644 index 0000000..a0b48dd --- /dev/null +++ b/src/JotformResponse.php @@ -0,0 +1,49 @@ +content = $content; + $this->statusCode = $statusCode; + $this->message = $message; + } + + public function toArray(): ?array + { + return $this->content; + } + + public function toJson(): ?string + { + return json_encode($this->content); + } + + public function toObject(): ?object + { + $object = json_decode($this->toJson()); + + return empty($object) ? null : $object; + } + + public function getStatusCode(): int + { + return $this->statusCode; + } + + public function getMessage(): ?string + { + return $this->message; + } + + public function __toString(): ?string + { + return $this->toJson(); + } +} diff --git a/src/Services/Folder.php b/src/Services/Folder.php new file mode 100644 index 0000000..9634ae6 --- /dev/null +++ b/src/Services/Folder.php @@ -0,0 +1,31 @@ +folderId = $folderId; + } + + public function id(): string + { + return $this->folderId; + } + + public function get(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->folderId}"); + } +} diff --git a/src/Services/Form.php b/src/Services/Form.php new file mode 100644 index 0000000..0e8ec7a --- /dev/null +++ b/src/Services/Form.php @@ -0,0 +1,190 @@ +formId = $formId; + } + + public function id(): string + { + return $this->formId; + } + + public function get(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->formId}"); + } + + /** + * @param array|string $params Array or Json + * @return JotformResponse + */ + public function create($params): JotformResponse + { + if (is_string($params)) { + return $this->client->putJson($this->name, $params); + } + + $form = []; + foreach ($params as $key => $value) { + foreach ($value as $k => $v) { + if ($key === "properties") { + $form["{$key}[{$k}]"] = $v; + } else { + foreach ($v as $a => $b) { + $form["{$key}[{$k}][{$a}]"] = $b; + } + } + } + } + + return $this->client->post($this->name, $form); + } + + public function delete(): JotformResponse + { + return $this->client->delete("{$this->name}/{$this->formId}"); + } + + public function clone(string $formId): JotformResponse + { + return $this->client->post("{$this->name}/{$formId}/clone"); + } + + public function questions(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->formId}/questions", $this->getConditions()); + } + + public function question(string $questionId): JotformResponse + { + return $this->client->get("{$this->name}/{$this->formId}/questions/{$questionId}"); + } + + /** + * @param array|string $params Data Array or JSON String + * @return JotformResponse + */ + public function createQuestion($params): JotformResponse + { + $endpoint = "{$this->name}/{$this->formId}/questions"; + + if (is_string($params)) { + return $this->client->putJson($endpoint, $params); + } + + return $this->client->post($endpoint, $this->prepareQuestionParams($params)); + } + + public function editQuestion(string $questionId, array $params): JotformResponse + { + return $this->client->post( + "{$this->name}/{$this->formId}/question/{$questionId}", + $this->prepareQuestionParams($params) + ); + } + + public function deleteQuestion(string $questionId): JotformResponse + { + return $this->client->delete("{$this->name}/{$this->formId}/question/{$questionId}"); + } + + public function submissions(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->formId}/submissions", $this->getConditions()); + } + + public function createSubmission(array $params): JotformResponse + { + return (new Submission($this->client, null))->create($this->formId, $params); + } + + public function files(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->formId}/files", $this->getConditions()); + } + + public function webhooks(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->formId}/webhooks", $this->getConditions()); + } + + public function createWebhook(string $url): JotformResponse + { + return $this->client->post("{$this->name}/{$this->formId}/webhooks", [ + 'webhookURL' => $url, + ]); + } + + public function deleteWebhook(string $webhookId): JotformResponse + { + return $this->client->delete("{$this->name}/{$this->formId}/webhooks/{$webhookId}"); + } + + public function properties(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->formId}/properties"); + } + + public function property(string $key): JotformResponse + { + return $this->client->get("{$this->name}/{$this->formId}/properties/{$key}"); + } + + /** + * @param array|string $params Data Array or JSON String + * @return JotformResponse + */ + public function setProperties($params): JotformResponse + { + $endpoint = "{$this->name}/{$this->formId}/properties"; + + if (is_string($params)) { + return $this->client->putJson($endpoint, $params); + } + + $properties = []; + foreach ($params as $key => $value) { + $properties["properties[{$key}]"] = $value; + } + + return $this->client->post($endpoint, $properties); + } + + public function reports(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->formId}/reports", $this->getConditions()); + } + + public function createReport(array $params): JotformResponse + { + return $this->client->post("{$this->name}/{$this->formId}/reports", $params); + } + + protected function prepareQuestionParams(array $params): array + { + $question = []; + foreach ($params as $key => $value) { + $question["question[{$key}]"] = $value; + } + + return $question; + } +} diff --git a/src/Services/Report.php b/src/Services/Report.php new file mode 100644 index 0000000..62b652e --- /dev/null +++ b/src/Services/Report.php @@ -0,0 +1,36 @@ +reportId = $reportId; + } + + public function id(): string + { + return $this->reportId; + } + + public function get(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->reportId}"); + } + + public function delete(): JotformResponse + { + return $this->client->delete("{$this->name}/{$this->reportId}"); + } +} diff --git a/src/Services/Service.php b/src/Services/Service.php new file mode 100644 index 0000000..1c240da --- /dev/null +++ b/src/Services/Service.php @@ -0,0 +1,19 @@ +client = $client; + } +} diff --git a/src/Services/Submission.php b/src/Services/Submission.php new file mode 100644 index 0000000..a330765 --- /dev/null +++ b/src/Services/Submission.php @@ -0,0 +1,78 @@ +submissionId = $submissionId; + } + + public function id(): string + { + return $this->submissionId; + } + + public function get(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->submissionId}"); + } + + public function getAll(): JotformResponse + { + return $this->client->get("{$this->name}/{$this->submissionId}"); + } + + /** + * @param string $formId + * @param array|string $params Data Array or JSON String + * @return JotformResponse + */ + public function create(string $formId, $params): JotformResponse + { + $endpoint = "form/{$formId}/submissions"; + + if (is_string($params)) { + return $this->client->putJson($endpoint, $params); + } + + return $this->client->post($endpoint, $this->prepareParams($params)); + } + + public function update(array $params): JotformResponse + { + return $this->client->post("{$this->name}/{$this->submissionId}", $this->prepareParams($params)); + } + + public function delete(): JotformResponse + { + return $this->client->delete("{$this->name}/{$this->submissionId}"); + } + + protected function prepareParams(array $params): array + { + $submission = []; + foreach ($params as $key => $value) { + if (strpos($key, '_') && $key !== 'created_at') { + $qid = substr($key, 0, strpos($key, '_')); + $type = substr($key, strpos($key, '_') + 1); + $submission["submission[{$qid}][{$type}]"] = $value; + } else { + $submission["submission[{$key}]"] = $value; + } + } + + return $submission; + } +} diff --git a/src/Services/System.php b/src/Services/System.php new file mode 100644 index 0000000..e2ab7be --- /dev/null +++ b/src/Services/System.php @@ -0,0 +1,21 @@ +folderId; + } + + public function plan(string $name): JotformResponse + { + return $this->client->get("{$this->name}/plan/" . strtoupper($name)); + } +} diff --git a/src/Services/User.php b/src/Services/User.php new file mode 100644 index 0000000..b6f7569 --- /dev/null +++ b/src/Services/User.php @@ -0,0 +1,86 @@ +client->get($this->name); + } + + public function register(array $user): JotformResponse + { + return $this->client->post("{$this->name}/register", $user); + } + + public function login(array $credentials): JotformResponse + { + return $this->client->post("{$this->name}/login", $credentials); + } + + public function logout(): JotformResponse + { + return $this->client->get("{$this->name}/logout"); + } + + public function usage(): JotformResponse + { + return $this->client->get("{$this->name}/usage"); + } + + public function forms(): JotformResponse + { + return $this->client->get("{$this->name}/forms", $this->getConditions()); + } + + public function createForm(array $params): JotformResponse + { + return (new Form($this->client, null))->create($params); + } + + public function submissions(): JotformResponse + { + return $this->client->get("{$this->name}/submissions", $this->getConditions()); + } + + public function subUsers(): JotformResponse + { + return $this->client->get("{$this->name}/subusers"); + } + + public function folders(): JotformResponse + { + return $this->client->get("{$this->name}/folders"); + } + + public function reports(): JotformResponse + { + return $this->client->get('{$this->name}/reports'); + } + + public function settings(): JotformResponse + { + return $this->client->get("{$this->name}/settings"); + } + + public function updateSettings(array $params): JotformResponse + { + return $this->client->post("{$this->name}/settings", $params); + } + + public function history(): JotformResponse + { + return $this->client->get("{$this->name}/history", $this->getQueries()); + } +} diff --git a/src/Traits/UseConditions.php b/src/Traits/UseConditions.php new file mode 100644 index 0000000..4f381a0 --- /dev/null +++ b/src/Traits/UseConditions.php @@ -0,0 +1,46 @@ +offset = $offset; + + return $this; + } + + public function limit(int $limit): self + { + $this->limit = $limit; + + return $this; + } + + public function filter(array $filter): self + { + $this->filter = urlencode(json_encode($filter)); + + return $this; + } + + public function orderBy(string $orderBy): self + { + $this->orderBy = $orderBy; + + return $this; + } + + protected function getConditions() + { + $conditions = []; + + return $conditions; + } +} diff --git a/src/Traits/UseQuery.php b/src/Traits/UseQuery.php new file mode 100644 index 0000000..c2e82a4 --- /dev/null +++ b/src/Traits/UseQuery.php @@ -0,0 +1,54 @@ +action = $action; + + return $this; + } + + public function date(int $date): self + { + $this->date = $date; + + return $this; + } + + public function sortBy(array $sortBy): self + { + $this->sortBy = urlencode(json_encode($sortBy)); + + return $this; + } + + public function startDate(string $startDate): self + { + $this->startDate = $startDate; + + return $this; + } + + public function endDate(string $endDate): self + { + $this->endDate = $endDate; + + return $this; + } + + protected function getQueries() + { + $queries = []; + + return $queries; + } +} diff --git a/tests/FolderTest.php b/tests/FolderTest.php new file mode 100644 index 0000000..c039a63 --- /dev/null +++ b/tests/FolderTest.php @@ -0,0 +1,17 @@ +jotform->folder("")->get(); + $folder = $response->toObject(); + + $this->assertEquals(200, $response->getStatusCode()); + $this->assertEmpty($folder); + } +} diff --git a/tests/FormTest.php b/tests/FormTest.php new file mode 100644 index 0000000..fc1b08a --- /dev/null +++ b/tests/FormTest.php @@ -0,0 +1,16 @@ +expectException(JotformException::class); + $this->jotform->form("")->get(); + } +} diff --git a/tests/ReportTest.php b/tests/ReportTest.php new file mode 100644 index 0000000..035a33f --- /dev/null +++ b/tests/ReportTest.php @@ -0,0 +1,20 @@ +expectException(JotformException::class); + $response = $this->jotform->report("")->get(); + $report = $response->toArray(); + + $this->assertEquals(200, $response->getStatusCode()); + $this->assertEmpty($report); + } +} diff --git a/tests/SubmissionTest.php b/tests/SubmissionTest.php new file mode 100644 index 0000000..09feae3 --- /dev/null +++ b/tests/SubmissionTest.php @@ -0,0 +1,26 @@ +expectException(JotformException::class); + $this->jotform->submission("")->get(); + } + + /** @test */ + public function test_get_all_submissions_by_form_id() + { + // [TODO] + $response = $this->jotform->form("") + ->limit(100)->orderBy('created_at')->getSubmissions(); + + $this->assertEquals(200, $response->getStatusCode()); + } +} diff --git a/tests/SystemTest.php b/tests/SystemTest.php new file mode 100644 index 0000000..550c352 --- /dev/null +++ b/tests/SystemTest.php @@ -0,0 +1,41 @@ +jotform->system()->plan('free'); + $this->assertEquals(200, $response->getStatusCode()); + } + + /** @test */ + public function test_get_system_plan_for_bronze() + { + $response = $this->jotform->system()->plan('bronze'); + $this->assertEquals(200, $response->getStatusCode()); + } + + /** @test */ + public function test_get_system_plan_for_silver() + { + $response = $this->jotform->system()->plan('silver'); + $this->assertEquals(200, $response->getStatusCode()); + } + + /** @test */ + public function test_get_system_plan_for_gold() + { + $response = $this->jotform->system()->plan('gold'); + $this->assertEquals(200, $response->getStatusCode()); + } + + /** @test */ + public function test_get_system_plan_for_platinum() + { + $response = $this->jotform->system()->plan('platinum'); + $this->assertEquals(200, $response->getStatusCode()); + } +} diff --git a/tests/TestCase.php b/tests/TestCase.php new file mode 100644 index 0000000..bc6a87d --- /dev/null +++ b/tests/TestCase.php @@ -0,0 +1,23 @@ +client = new JotformClient($_ENV['API_KEY']); + $this->jotform = new Jotform($this->client); + } +} diff --git a/tests/UserTest.php b/tests/UserTest.php new file mode 100644 index 0000000..5f6e13c --- /dev/null +++ b/tests/UserTest.php @@ -0,0 +1,27 @@ +jotform->user()->get(); + $this->assertEquals(200, $response->getStatusCode()); + } + + /** @test */ + public function test_get_user_usage() + { + $response = $this->jotform->user()->usage(); + $this->assertEquals(200, $response->getStatusCode()); + } + + /** @test */ + public function test_get_user_forms() + { + $response = $this->jotform->user()->forms(); + $this->assertEquals(200, $response->getStatusCode()); + } +} From 952bc8481280f8b76309531afd58a860f71bc30f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Demirta=C5=9F?= Date: Fri, 15 Oct 2021 09:10:41 +0300 Subject: [PATCH 12/22] Updated condition and query preparing. --- src/Traits/UseConditions.php | 25 +++++++++++++++++++++++- src/Traits/UseQuery.php | 37 ++++++++++++++++++++++++++++++++---- 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/src/Traits/UseConditions.php b/src/Traits/UseConditions.php index 4f381a0..a7ecaf5 100644 --- a/src/Traits/UseConditions.php +++ b/src/Traits/UseConditions.php @@ -4,9 +4,16 @@ trait UseConditions { + /** @var int */ private $offset; + + /** @var int */ private $limit; + + /** @var array */ private $filter; + + /** @var string */ private $orderBy; public function offset(int $offset): self @@ -25,7 +32,7 @@ public function limit(int $limit): self public function filter(array $filter): self { - $this->filter = urlencode(json_encode($filter)); + $this->filter = $filter; return $this; } @@ -41,6 +48,22 @@ protected function getConditions() { $conditions = []; + if ($this->offset) { + $conditions['offset'] = $this->offset; + } + + if ($this->limit) { + $conditions['limit'] = $this->limit; + } + + if ($this->filter) { + $conditions['filter'] = urlencode(json_encode($this->filter)); + } + + if ($this->orderBy) { + $conditions['orderby'] = $this->orderBy; + } + return $conditions; } } diff --git a/src/Traits/UseQuery.php b/src/Traits/UseQuery.php index c2e82a4..e0b765c 100644 --- a/src/Traits/UseQuery.php +++ b/src/Traits/UseQuery.php @@ -4,29 +4,38 @@ trait UseQuery { + /** @var string */ private $action; + + /** @var string */ private $date; + + /** @var string */ private $sortBy; + + /** @var string */ private $startDate; + + /** @var string */ private $endDate; - public function action(int $action): self + public function action(string $action): self { $this->action = $action; return $this; } - public function date(int $date): self + public function date(string $date): self { $this->date = $date; return $this; } - public function sortBy(array $sortBy): self + public function sortBy(string $sortBy): self { - $this->sortBy = urlencode(json_encode($sortBy)); + $this->sortBy = $sortBy; return $this; } @@ -49,6 +58,26 @@ protected function getQueries() { $queries = []; + if ($this->action) { + $conditions['action'] = $this->action; + } + + if ($this->date) { + $conditions['date'] = $this->date; + } + + if ($this->sortBy) { + $conditions['sortBy'] = $this->sortBy; + } + + if ($this->startDate) { + $conditions['startDate'] = $this->startDate; + } + + if ($this->endDate) { + $conditions['endDate'] = $this->endDate; + } + return $queries; } } From b3288c2db88e0f6d8927c4e4564357e2a1ab48d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Demirta=C5=9F?= Date: Mon, 25 Oct 2021 10:58:53 +0300 Subject: [PATCH 13/22] Added API version into the base URL. Also, updated code format. --- .php-cs-fixer.dist.php | 2 +- src/JotformClient.php | 18 ++++++++++++------ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 33b3b63..f285388 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -15,7 +15,7 @@ 'array_syntax' => ['syntax' => 'short'], 'ordered_imports' => ['sort_algorithm' => 'alpha'], 'no_unused_imports' => true, - 'not_operator_with_successor_space' => true, + 'not_operator_with_successor_space' => false, 'trailing_comma_in_multiline' => true, 'phpdoc_scalar' => true, 'unary_operator_spaces' => true, diff --git a/src/JotformClient.php b/src/JotformClient.php index 7877a0e..3850eed 100644 --- a/src/JotformClient.php +++ b/src/JotformClient.php @@ -117,13 +117,13 @@ protected function requestJson(string $method, string $path, string $params = '' * @param string  $method Request Method * @param string $path Request Path/URL * @param array|string $params Data Array or JSON string - * @return JotformResponse + * @return JotformResponse */ protected function prepareAndSendRequest(string $method, string $path, $params = []): JotformResponse { $method = strtoupper($method); $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $this->normalizeRequestUrl($path, $method)); + curl_setopt($ch, CURLOPT_URL, $this->normalizeRequestUrl($path, $method, $params)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, 'JOTFORM_PHP_WRAPPER'); curl_setopt($ch, CURLOPT_HTTPHEADER, $this->prepareRequestHeaders($params)); @@ -131,7 +131,7 @@ protected function prepareAndSendRequest(string $method, string $path, $params = if (in_array($method, ['POST', 'PUT', 'DELETE'])) { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); - if (! empty($params)) { + if (!empty($params)) { curl_setopt($ch, CURLOPT_POSTFIELDS, $params); } } @@ -202,18 +202,24 @@ private function prepareRequestHeaders($params): array return $headers; } - private function normalizeRequestUrl(string $path, string $method): string + /** + * @param string $path + * @param string $method + * @param array|string $params + * @return string + */ + private function normalizeRequestUrl(string $path, string $method, $params): string { $server = $this->europeOnly ? 'eu-api' : 'api'; $segments = [ "https://{$server}.jotform.com", - // 'v' . self::API_VERSION, + 'v' . self::API_VERSION, $path . ($this->outputType === self::OUTPUT_JSON ? '' : '.xml'), ]; $url = implode('/', $segments); - return $method === 'GET' && ! empty($params) + return $method === 'GET' && is_array($params) && !empty($params) ? "{$url}?" . http_build_query($params) : $url; } From 265a1e11f1f59c5f0e2f2efbd541b0198271025d Mon Sep 17 00:00:00 2001 From: ibd <91189135+burakdemirtas-jtf@users.noreply.github.com> Date: Wed, 27 Oct 2021 09:21:01 +0300 Subject: [PATCH 14/22] Update filename --- JotForm.php => Jotform.php | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename JotForm.php => Jotform.php (100%) diff --git a/JotForm.php b/Jotform.php similarity index 100% rename from JotForm.php rename to Jotform.php From 7d12578f21f4053d01ce0d59d78478d2fb2f56ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Demirta=C5=9F?= Date: Wed, 27 Oct 2021 09:21:54 +0300 Subject: [PATCH 15/22] Updated README. --- README.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 963a893..6e8f3dc 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ jotform-api-php =============== -[JotForm API](http://api.jotform.com/docs/) - PHP Client +[Jotform API](http://api.jotform.com/docs/) - PHP Client ## Installation @@ -12,7 +12,7 @@ $ composer require jotform/jotform-api-php ``` and add following line to your php file: ```php -require "vendor/autoload.php"; +require 'vendor/autoload.php'; ``` 2- Install and use manually: @@ -21,7 +21,7 @@ $ git clone https://github.com/jotform/jotform-api-php.git ``` and add following line to your php file: ```php -require "jotform-api-php/Jotform.php"; +require 'jotform-api-php/Jotform.php'; ``` If you install the package into another directory, you should update path for `require` command above. @@ -32,7 +32,7 @@ You can find the docs for the API of this client at [Jotform API Documentation]( ## Authentication -JotForm API requires API key for all user related calls. You can create your API Keys at [API section](http://www.jotform.com/myaccount/api) of My Account page. +Jotform API requires API key for all user related calls. You can create your API Keys at [API section](http://www.jotform.com/myaccount/api) of My Account page. ## Examples @@ -40,17 +40,17 @@ JotForm API requires API key for all user related calls. You can create your API ```php "); +$client = new JotformClient(''); $jotform = new Jotform($client); $forms = $jotform->user()->forms(); foreach ($forms->toArray() as $form) { - echo $form["title"] . PHP_EOL; + echo $form['title'] . PHP_EOL; } ``` @@ -111,15 +111,15 @@ try { $jotform = new Jotform($client); $filter = [ - "id:gt" => "239252191641336722", - "created_at:gt" => "2013-07-09 07:48:34", + 'id:gt' => '239252191641336722', + 'created_at:gt' => '2013-07-09 07:48:34', ]; $submissions = $jotform->user()->filter($filter)->submissions(); var_dump($submissions); $filter = [ - "id:gt" => "239176717911737253", + 'id:gt' => '239176717911737253', ]; $forms = $jotform->user()->filter($filter)->forms(); @@ -143,7 +143,7 @@ try { $submissions = $jotform->user()->limit(50)->orderBy('created_at')->submissions(); foreach ($submissions->toArray() as $submission) { - $result = $jotform->submission($submission["id"])->delete(); + $result = $jotform->submission($submission['id'])->delete(); echo $result . PHP_EOL; } } From 0e219773186e955975ed99ddf50c027bc0157744 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Demirta=C5=9F?= Date: Mon, 8 Nov 2021 10:23:13 +0300 Subject: [PATCH 16/22] Update services and tests. Also, configured workflow. --- .github/workflows/run-tests.yml | 4 +++- Jotform.php | 2 +- phpunit.xml.dist | 3 --- src/Jotform.php | 7 +++++- src/JotformClient.php | 28 +++++++++++++---------- src/JotformResponse.php | 5 ----- src/Services/Folder.php | 2 +- src/Services/Form.php | 40 ++++++++++++++++----------------- src/Services/Report.php | 4 ++-- src/Services/Submission.php | 10 ++++----- src/Services/System.php | 2 +- src/Services/User.php | 28 +++++++++++------------ tests/FolderTest.php | 5 ++--- tests/ReportTest.php | 7 +++--- tests/SubmissionTest.php | 29 ++++++++++++++++++------ tests/SystemTest.php | 20 ++++++++--------- tests/TestCase.php | 3 +-- tests/UserTest.php | 12 +++++----- 18 files changed, 113 insertions(+), 98 deletions(-) diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index edc2f41..e2b386d 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -34,4 +34,6 @@ jobs: run: composer update --${{ matrix.stability }} --prefer-dist --no-interaction - name: Execute tests - run: composer test \ No newline at end of file + run: composer test + env: + JOTFORM_API_KEY: ${{ secrets.JOTFORM_API_KEY }} diff --git a/Jotform.php b/Jotform.php index 5224f63..4f733f7 100644 --- a/Jotform.php +++ b/Jotform.php @@ -1,6 +1,6 @@ ./src - - - \ No newline at end of file diff --git a/src/Jotform.php b/src/Jotform.php index 223d647..0082dde 100644 --- a/src/Jotform.php +++ b/src/Jotform.php @@ -20,7 +20,7 @@ public function __construct(JotformClient $client, bool $euCheck = true) // Check 'euOnly' flag for User while initializing. if ($euCheck) { - $user = $this->user()->get()->toArray(); + $user = $this->user()->get(); if (isset($user['euOnly'])) { $this->client->europeOnly(true); } @@ -61,4 +61,9 @@ public function system(): System { return new System($this->client); } + + public function response(): JotformResponse + { + return $this->client->response; + } } diff --git a/src/JotformClient.php b/src/JotformClient.php index 3850eed..64ae9bd 100644 --- a/src/JotformClient.php +++ b/src/JotformClient.php @@ -26,6 +26,9 @@ class JotformClient /** @var bool */ private $debug; + /** @var JotformResponse */ + public $response; + public function __construct(string $apiKey, string $outputType = self::OUTPUT_JSON, bool $debug = false) { $this->apiKey = $apiKey; @@ -68,47 +71,47 @@ public function getDebugMode(): bool return $this->debugMode; } - public function get(string $path, array $params = []): JotformResponse + public function get(string $path, array $params = []): ?array { return $this->request('get', $path, $params); } - public function post(string $path, array $params = []): JotformResponse + public function post(string $path, array $params = []): ?array { return $this->request('post', $path, $params); } - public function put(string $path, array $params = []): JotformResponse + public function put(string $path, array $params = []): ?array { return $this->request('put', $path, $params); } - public function delete(string $path, array $params = []): JotformResponse + public function delete(string $path, array $params = []): ?array { return $this->request('delete', $path, $params); } - public function postJson(string $path, string $params = ''): JotformResponse + public function postJson(string $path, string $params = ''): ?array { return $this->requestJson('post', $path, $params); } - public function putJson(string $path, string $params = ''): JotformResponse + public function putJson(string $path, string $params = ''): ?array { return $this->requestJson('put', $path, $params); } - public function deleteJson(string $path, string $params = ''): JotformResponse + public function deleteJson(string $path, string $params = ''): ?array { return $this->requestJson('delete', $path, $params); } - protected function request(string $method, string $path, array $params = []): JotformResponse + protected function request(string $method, string $path, array $params = []): ?array { return $this->prepareAndSendRequest($method, $path, $params); } - protected function requestJson(string $method, string $path, string $params = ''): JotformResponse + protected function requestJson(string $method, string $path, string $params = ''): ?array { return $this->prepareAndSendRequest($method, $path, $params); } @@ -117,9 +120,9 @@ protected function requestJson(string $method, string $path, string $params = '' * @param string  $method Request Method * @param string $path Request Path/URL * @param array|string $params Data Array or JSON string - * @return JotformResponse + * @return array|null */ - protected function prepareAndSendRequest(string $method, string $path, $params = []): JotformResponse + protected function prepareAndSendRequest(string $method, string $path, $params = []): ?array { $method = strtoupper($method); $ch = curl_init(); @@ -182,7 +185,8 @@ protected function prepareAndSendRequest(string $method, string $path, $params = $response = $response['content'] ?? $response; } - return new JotformResponse($response, $statusCode, $response["message"] ?? null); + $this->response = new JotformResponse($response, $statusCode, $response["message"] ?? null); + return $response; } /** diff --git a/src/JotformResponse.php b/src/JotformResponse.php index a0b48dd..d01525a 100644 --- a/src/JotformResponse.php +++ b/src/JotformResponse.php @@ -15,11 +15,6 @@ public function __construct($content, int $statusCode, ?string $message) $this->message = $message; } - public function toArray(): ?array - { - return $this->content; - } - public function toJson(): ?string { return json_encode($this->content); diff --git a/src/Services/Folder.php b/src/Services/Folder.php index 9634ae6..294823d 100644 --- a/src/Services/Folder.php +++ b/src/Services/Folder.php @@ -24,7 +24,7 @@ public function id(): string return $this->folderId; } - public function get(): JotformResponse + public function get(): ?array { return $this->client->get("{$this->name}/{$this->folderId}"); } diff --git a/src/Services/Form.php b/src/Services/Form.php index 0e8ec7a..f9a3b68 100644 --- a/src/Services/Form.php +++ b/src/Services/Form.php @@ -27,7 +27,7 @@ public function id(): string return $this->formId; } - public function get(): JotformResponse + public function get(): ?array { return $this->client->get("{$this->name}/{$this->formId}"); } @@ -36,7 +36,7 @@ public function get(): JotformResponse * @param array|string $params Array or Json * @return JotformResponse */ - public function create($params): JotformResponse + public function create($params): ?array { if (is_string($params)) { return $this->client->putJson($this->name, $params); @@ -58,22 +58,22 @@ public function create($params): JotformResponse return $this->client->post($this->name, $form); } - public function delete(): JotformResponse + public function delete(): ?array { return $this->client->delete("{$this->name}/{$this->formId}"); } - public function clone(string $formId): JotformResponse + public function clone(string $formId): ?array { return $this->client->post("{$this->name}/{$formId}/clone"); } - public function questions(): JotformResponse + public function questions(): ?array { return $this->client->get("{$this->name}/{$this->formId}/questions", $this->getConditions()); } - public function question(string $questionId): JotformResponse + public function question(string $questionId): ?array { return $this->client->get("{$this->name}/{$this->formId}/questions/{$questionId}"); } @@ -82,7 +82,7 @@ public function question(string $questionId): JotformResponse * @param array|string $params Data Array or JSON String * @return JotformResponse */ - public function createQuestion($params): JotformResponse + public function createQuestion($params): ?array { $endpoint = "{$this->name}/{$this->formId}/questions"; @@ -93,7 +93,7 @@ public function createQuestion($params): JotformResponse return $this->client->post($endpoint, $this->prepareQuestionParams($params)); } - public function editQuestion(string $questionId, array $params): JotformResponse + public function editQuestion(string $questionId, array $params): ?array { return $this->client->post( "{$this->name}/{$this->formId}/question/{$questionId}", @@ -101,49 +101,49 @@ public function editQuestion(string $questionId, array $params): JotformResponse ); } - public function deleteQuestion(string $questionId): JotformResponse + public function deleteQuestion(string $questionId): ?array { return $this->client->delete("{$this->name}/{$this->formId}/question/{$questionId}"); } - public function submissions(): JotformResponse + public function submissions(): ?array { return $this->client->get("{$this->name}/{$this->formId}/submissions", $this->getConditions()); } - public function createSubmission(array $params): JotformResponse + public function createSubmission(array $params): ?array { return (new Submission($this->client, null))->create($this->formId, $params); } - public function files(): JotformResponse + public function files(): ?array { return $this->client->get("{$this->name}/{$this->formId}/files", $this->getConditions()); } - public function webhooks(): JotformResponse + public function webhooks(): ?array { return $this->client->get("{$this->name}/{$this->formId}/webhooks", $this->getConditions()); } - public function createWebhook(string $url): JotformResponse + public function createWebhook(string $url): ?array { return $this->client->post("{$this->name}/{$this->formId}/webhooks", [ 'webhookURL' => $url, ]); } - public function deleteWebhook(string $webhookId): JotformResponse + public function deleteWebhook(string $webhookId): ?array { return $this->client->delete("{$this->name}/{$this->formId}/webhooks/{$webhookId}"); } - public function properties(): JotformResponse + public function properties(): ?array { return $this->client->get("{$this->name}/{$this->formId}/properties"); } - public function property(string $key): JotformResponse + public function property(string $key): ?array { return $this->client->get("{$this->name}/{$this->formId}/properties/{$key}"); } @@ -152,7 +152,7 @@ public function property(string $key): JotformResponse * @param array|string $params Data Array or JSON String * @return JotformResponse */ - public function setProperties($params): JotformResponse + public function setProperties($params): ?array { $endpoint = "{$this->name}/{$this->formId}/properties"; @@ -168,12 +168,12 @@ public function setProperties($params): JotformResponse return $this->client->post($endpoint, $properties); } - public function reports(): JotformResponse + public function reports(): ?array { return $this->client->get("{$this->name}/{$this->formId}/reports", $this->getConditions()); } - public function createReport(array $params): JotformResponse + public function createReport(array $params): ?array { return $this->client->post("{$this->name}/{$this->formId}/reports", $params); } diff --git a/src/Services/Report.php b/src/Services/Report.php index 62b652e..85ff121 100644 --- a/src/Services/Report.php +++ b/src/Services/Report.php @@ -24,12 +24,12 @@ public function id(): string return $this->reportId; } - public function get(): JotformResponse + public function get(): ?array { return $this->client->get("{$this->name}/{$this->reportId}"); } - public function delete(): JotformResponse + public function delete(): ?array { return $this->client->delete("{$this->name}/{$this->reportId}"); } diff --git a/src/Services/Submission.php b/src/Services/Submission.php index a330765..57c4d1f 100644 --- a/src/Services/Submission.php +++ b/src/Services/Submission.php @@ -24,12 +24,12 @@ public function id(): string return $this->submissionId; } - public function get(): JotformResponse + public function get(): ?array { return $this->client->get("{$this->name}/{$this->submissionId}"); } - public function getAll(): JotformResponse + public function getAll(): ?array { return $this->client->get("{$this->name}/{$this->submissionId}"); } @@ -39,7 +39,7 @@ public function getAll(): JotformResponse * @param array|string $params Data Array or JSON String * @return JotformResponse */ - public function create(string $formId, $params): JotformResponse + public function create(string $formId, $params): ?array { $endpoint = "form/{$formId}/submissions"; @@ -50,12 +50,12 @@ public function create(string $formId, $params): JotformResponse return $this->client->post($endpoint, $this->prepareParams($params)); } - public function update(array $params): JotformResponse + public function update(array $params): ?array { return $this->client->post("{$this->name}/{$this->submissionId}", $this->prepareParams($params)); } - public function delete(): JotformResponse + public function delete(): ?array { return $this->client->delete("{$this->name}/{$this->submissionId}"); } diff --git a/src/Services/System.php b/src/Services/System.php index e2ab7be..82f4ebb 100644 --- a/src/Services/System.php +++ b/src/Services/System.php @@ -14,7 +14,7 @@ public function id(): string return $this->folderId; } - public function plan(string $name): JotformResponse + public function plan(string $name): ?array { return $this->client->get("{$this->name}/plan/" . strtoupper($name)); } diff --git a/src/Services/User.php b/src/Services/User.php index b6f7569..8850136 100644 --- a/src/Services/User.php +++ b/src/Services/User.php @@ -14,72 +14,72 @@ class User extends Service /** @var string */ protected $name = 'user'; - public function get(): JotformResponse + public function get(): ?array { return $this->client->get($this->name); } - public function register(array $user): JotformResponse + public function register(array $user): ?array { return $this->client->post("{$this->name}/register", $user); } - public function login(array $credentials): JotformResponse + public function login(array $credentials): ?array { return $this->client->post("{$this->name}/login", $credentials); } - public function logout(): JotformResponse + public function logout(): ?array { return $this->client->get("{$this->name}/logout"); } - public function usage(): JotformResponse + public function usage(): ?array { return $this->client->get("{$this->name}/usage"); } - public function forms(): JotformResponse + public function forms(): ?array { return $this->client->get("{$this->name}/forms", $this->getConditions()); } - public function createForm(array $params): JotformResponse + public function createForm(array $params): ?array { return (new Form($this->client, null))->create($params); } - public function submissions(): JotformResponse + public function submissions(): ?array { return $this->client->get("{$this->name}/submissions", $this->getConditions()); } - public function subUsers(): JotformResponse + public function subUsers(): ?array { return $this->client->get("{$this->name}/subusers"); } - public function folders(): JotformResponse + public function folders(): ?array { return $this->client->get("{$this->name}/folders"); } - public function reports(): JotformResponse + public function reports(): ?array { return $this->client->get('{$this->name}/reports'); } - public function settings(): JotformResponse + public function settings(): ?array { return $this->client->get("{$this->name}/settings"); } - public function updateSettings(array $params): JotformResponse + public function updateSettings(array $params): ?array { return $this->client->post("{$this->name}/settings", $params); } - public function history(): JotformResponse + public function history(): ?array { return $this->client->get("{$this->name}/history", $this->getQueries()); } diff --git a/tests/FolderTest.php b/tests/FolderTest.php index c039a63..83badcf 100644 --- a/tests/FolderTest.php +++ b/tests/FolderTest.php @@ -8,10 +8,9 @@ class FolderTest extends TestCase public function test_get_folder_with_invalid_id() { // [TODO] - $response = $this->jotform->folder("")->get(); - $folder = $response->toObject(); + $folder = $this->jotform->folder("")->get(); - $this->assertEquals(200, $response->getStatusCode()); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); $this->assertEmpty($folder); } } diff --git a/tests/ReportTest.php b/tests/ReportTest.php index 035a33f..4a3614e 100644 --- a/tests/ReportTest.php +++ b/tests/ReportTest.php @@ -10,11 +10,10 @@ class ReportTest extends TestCase public function test_get_report_with_invalid_id() { // [TODO] - // $this->expectException(JotformException::class); - $response = $this->jotform->report("")->get(); - $report = $response->toArray(); + $this->expectException(JotformException::class); + $report = $this->jotform->report("")->get(); - $this->assertEquals(200, $response->getStatusCode()); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); $this->assertEmpty($report); } } diff --git a/tests/SubmissionTest.php b/tests/SubmissionTest.php index 09feae3..fa3fcc3 100644 --- a/tests/SubmissionTest.php +++ b/tests/SubmissionTest.php @@ -7,20 +7,35 @@ class SubmissionTest extends TestCase { /** @test */ - public function test_get_submission_with_invalid_id() + // public function test_get_submission_with_invalid_id() + // { + // $this->expectException(JotformException::class); + // $submissions = $this->jotform->form('111222333444')->submissions(); + // $this->jotform->submission($submissions[0]['id'])->get(); + // } + + /** @test */ + public function test_get_submission_with_valid_id() { - // [TODO] - $this->expectException(JotformException::class); - $this->jotform->submission("")->get(); + $forms = $this->jotform->user()->forms(); + $forms = array_filter($forms, function ($form) { + return !is_null($form['last_submission']); + }); + $form = array_shift($forms); + $submissions = $this->jotform->form($form['id'])->submissions(); + $this->jotform->submission($submissions[0]['id'])->get(); + + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); } /** @test */ public function test_get_all_submissions_by_form_id() { // [TODO] - $response = $this->jotform->form("") - ->limit(100)->orderBy('created_at')->getSubmissions(); + $forms = $this->jotform->user()->forms(); + $response = $this->jotform->form($forms[0]['id']) + ->limit(100)->orderBy('created_at')->submissions(); - $this->assertEquals(200, $response->getStatusCode()); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); } } diff --git a/tests/SystemTest.php b/tests/SystemTest.php index 550c352..047729f 100644 --- a/tests/SystemTest.php +++ b/tests/SystemTest.php @@ -7,35 +7,35 @@ class SystemTest extends TestCase /** @test */ public function test_get_system_plan_for_free() { - $response = $this->jotform->system()->plan('free'); - $this->assertEquals(200, $response->getStatusCode()); + $this->jotform->system()->plan('free'); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); } /** @test */ public function test_get_system_plan_for_bronze() { - $response = $this->jotform->system()->plan('bronze'); - $this->assertEquals(200, $response->getStatusCode()); + $this->jotform->system()->plan('bronze'); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); } /** @test */ public function test_get_system_plan_for_silver() { - $response = $this->jotform->system()->plan('silver'); - $this->assertEquals(200, $response->getStatusCode()); + $this->jotform->system()->plan('silver'); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); } /** @test */ public function test_get_system_plan_for_gold() { - $response = $this->jotform->system()->plan('gold'); - $this->assertEquals(200, $response->getStatusCode()); + $this->jotform->system()->plan('gold'); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); } /** @test */ public function test_get_system_plan_for_platinum() { - $response = $this->jotform->system()->plan('platinum'); - $this->assertEquals(200, $response->getStatusCode()); + $this->jotform->system()->plan('platinum'); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); } } diff --git a/tests/TestCase.php b/tests/TestCase.php index bc6a87d..e76c597 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -16,8 +16,7 @@ abstract class TestCase extends BaseTestCase protected function setUp(): void { - // [TODO] - $this->client = new JotformClient($_ENV['API_KEY']); + $this->client = new JotformClient(getenv('JOTFORM_API_KEY')); $this->jotform = new Jotform($this->client); } } diff --git a/tests/UserTest.php b/tests/UserTest.php index 5f6e13c..3ab8f41 100644 --- a/tests/UserTest.php +++ b/tests/UserTest.php @@ -7,21 +7,21 @@ class UserTest extends TestCase /** @test */ public function test_get_user() { - $response = $this->jotform->user()->get(); - $this->assertEquals(200, $response->getStatusCode()); + $this->jotform->user()->get(); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); } /** @test */ public function test_get_user_usage() { - $response = $this->jotform->user()->usage(); - $this->assertEquals(200, $response->getStatusCode()); + $this->jotform->user()->usage(); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); } /** @test */ public function test_get_user_forms() { - $response = $this->jotform->user()->forms(); - $this->assertEquals(200, $response->getStatusCode()); + $this->jotform->user()->forms(); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); } } From 512f400b3c11f0de92e14d9df2f0e86707cbe22d Mon Sep 17 00:00:00 2001 From: burakdemirtas-jtf Date: Mon, 8 Nov 2021 07:23:37 +0000 Subject: [PATCH 17/22] Fix syntax styling --- src/JotformClient.php | 1 + src/Services/Folder.php | 1 - src/Services/Report.php | 1 - src/Services/System.php | 2 -- src/Services/User.php | 1 - 5 files changed, 1 insertion(+), 5 deletions(-) diff --git a/src/JotformClient.php b/src/JotformClient.php index 64ae9bd..7919c74 100644 --- a/src/JotformClient.php +++ b/src/JotformClient.php @@ -186,6 +186,7 @@ protected function prepareAndSendRequest(string $method, string $path, $params = } $this->response = new JotformResponse($response, $statusCode, $response["message"] ?? null); + return $response; } diff --git a/src/Services/Folder.php b/src/Services/Folder.php index 294823d..ec967a1 100644 --- a/src/Services/Folder.php +++ b/src/Services/Folder.php @@ -3,7 +3,6 @@ namespace Jotform\Services; use Jotform\JotformClient; -use Jotform\JotformResponse; class Folder extends Service { diff --git a/src/Services/Report.php b/src/Services/Report.php index 85ff121..9836549 100644 --- a/src/Services/Report.php +++ b/src/Services/Report.php @@ -3,7 +3,6 @@ namespace Jotform\Services; use Jotform\JotformClient; -use Jotform\JotformResponse; class Report extends Service { diff --git a/src/Services/System.php b/src/Services/System.php index 82f4ebb..fd09b8d 100644 --- a/src/Services/System.php +++ b/src/Services/System.php @@ -2,8 +2,6 @@ namespace Jotform\Services; -use Jotform\JotformResponse; - class System extends Service { /** @var string */ diff --git a/src/Services/User.php b/src/Services/User.php index 8850136..bceea34 100644 --- a/src/Services/User.php +++ b/src/Services/User.php @@ -2,7 +2,6 @@ namespace Jotform\Services; -use Jotform\JotformResponse; use Jotform\Traits\UseConditions; use Jotform\Traits\UseQuery; From 5004316e7a4f2486b8ea2ff3b0cf39bc0c41e148 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Demirta=C5=9F?= Date: Mon, 8 Nov 2021 10:27:52 +0300 Subject: [PATCH 18/22] Updated workflow --- .github/workflows/run-tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index e2b386d..f2b2318 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -10,7 +10,7 @@ jobs: matrix: os: [ubuntu-latest, windows-latest] php: [7.3, 8.0] - stability: [prefer-lowest, prefer-stable] + stability: [prefer-stable] name: P${{ matrix.php }} - ${{ matrix.stability }} - ${{ matrix.os }} From c022d9c77d19147b952214c2a975d0f3ebb2dfc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Demirta=C5=9F?= Date: Mon, 8 Nov 2021 10:31:41 +0300 Subject: [PATCH 19/22] Fixed Stringable::__toString() compatible. --- src/JotformResponse.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/JotformResponse.php b/src/JotformResponse.php index d01525a..92828f2 100644 --- a/src/JotformResponse.php +++ b/src/JotformResponse.php @@ -37,7 +37,7 @@ public function getMessage(): ?string return $this->message; } - public function __toString(): ?string + public function __toString(): string { return $this->toJson(); } From 95766b3b021e912a3c5742a331db2dce39179bb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Demirta=C5=9F?= Date: Mon, 8 Nov 2021 10:49:02 +0300 Subject: [PATCH 20/22] Update README --- README.md | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6e8f3dc..33633b1 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ $client = new JotformClient(''); $jotform = new Jotform($client); $forms = $jotform->user()->forms(); -foreach ($forms->toArray() as $form) { +foreach ($forms as $form) { echo $form['title'] . PHP_EOL; } ``` @@ -67,7 +67,7 @@ try { $client = new JotformClient(''); $jotform = new Jotform($client); - $forms = $jotform->user()->forms()->toArray(); + $forms = $jotform->user()->forms(); $latestForm = $forms[0]; $latestFormId = $latestForm['id']; @@ -142,7 +142,7 @@ try { $jotform = new Jotform($client); $submissions = $jotform->user()->limit(50)->orderBy('created_at')->submissions(); - foreach ($submissions->toArray() as $submission) { + foreach ($submissions as $submission) { $result = $jotform->submission($submission['id'])->delete(); echo $result . PHP_EOL; } @@ -151,5 +151,12 @@ catch (Exception $e) { var_dump($e->getMessage()); } ``` + +## Notes +- Condition methods: `filter`, `limit`, `offset`, `orderBy` +- Query methods: `action`, `sortBy`, `date`, `startDate`, `endDate` +- Limitation: *(for now)* + - **Condition methods** can be used with `Form` and `User` services. + - **Query methods** can be used with `User` service. --- Jotform From c9187673cade4cca8dd033d1801953d2ff861509 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Demirta=C5=9F?= Date: Fri, 12 Nov 2021 09:53:18 +0300 Subject: [PATCH 21/22] Fixed issue related with autoload class. --- Jotform.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Jotform.php b/Jotform.php index 4f733f7..dab5f53 100644 --- a/Jotform.php +++ b/Jotform.php @@ -9,6 +9,8 @@ */ spl_autoload_register(function ($class) { + $file = array_values(explode('\\', $class)); + $class = end($file); $paths = [ __DIR__ . '/src', __DIR__ . '/src/Services', @@ -17,7 +19,7 @@ ]; foreach ($paths as $path) { if (is_readable($file = "{$path}/{$class}.php")) { - include_once($file); + require_once($file); } } }); From b3582f571bff779e23fa94f3d3698c6f1c828399 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Demirta=C5=9F?= Date: Fri, 28 Jan 2022 12:30:34 +0300 Subject: [PATCH 22/22] Fixed some issues and updated readme. --- .github/FUNDING.yml | 1 - README.md | 2 +- src/JotformClient.php | 9 ++++----- src/Services/User.php | 2 +- 4 files changed, 6 insertions(+), 8 deletions(-) delete mode 100644 .github/FUNDING.yml diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml deleted file mode 100644 index fcd2991..0000000 --- a/.github/FUNDING.yml +++ /dev/null @@ -1 +0,0 @@ -github: :jotform-api-php diff --git a/README.md b/README.md index 33633b1..b045e1f 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ try { $latestForm = $forms[0]; $latestFormId = $latestForm['id']; - $submissions = $jotform->form($latestFormId)->getSubmissions(); + $submissions = $jotform->form($latestFormId)->submissions(); var_dump($submissions); } catch (Exception $e) { diff --git a/src/JotformClient.php b/src/JotformClient.php index 7919c74..32184a4 100644 --- a/src/JotformClient.php +++ b/src/JotformClient.php @@ -145,11 +145,10 @@ protected function prepareAndSendRequest(string $method, string $path, $params = curl_close($ch); if ($this->debug) { - // [TODO] - // var_dump([ - // 'parameters' => $params, - // 'info' => $info, - // ]); + print_r([ + 'parameters' => $params, + 'info' => $info, + ]); } if ($response == false) { diff --git a/src/Services/User.php b/src/Services/User.php index bceea34..7bbfce5 100644 --- a/src/Services/User.php +++ b/src/Services/User.php @@ -65,7 +65,7 @@ public function folders(): ?array public function reports(): ?array { - return $this->client->get('{$this->name}/reports'); + return $this->client->get("{$this->name}/reports"); } public function settings(): ?array