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..f2b2318 --- /dev/null +++ b/.github/workflows/run-tests.yml @@ -0,0 +1,39 @@ +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-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 + env: + JOTFORM_API_KEY: ${{ secrets.JOTFORM_API_KEY }} 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..f285388 --- /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' => false, + '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 deleted file mode 100644 index 836367a..0000000 --- a/JotForm.php +++ /dev/null @@ -1,657 +0,0 @@ -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; - } - 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/Jotform.php b/Jotform.php new file mode 100644 index 0000000..dab5f53 --- /dev/null +++ b/Jotform.php @@ -0,0 +1,25 @@ +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 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(); + $latestForm = $forms[0]; + $latestFormId = $latestForm['id']; - var_dump($submissions); - - } - catch (Exception $e) { - var_dump($e->getMessage()); - } - -?> + $submissions = $jotform->form($latestFormId)->submissions(); + 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 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()); +} +``` + +## 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 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..28fc43a --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,31 @@ + + + + + ./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(); + 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); + } + + public function response(): JotformResponse + { + return $this->client->response; + } +} diff --git a/src/JotformClient.php b/src/JotformClient.php new file mode 100644 index 0000000..32184a4 --- /dev/null +++ b/src/JotformClient.php @@ -0,0 +1,230 @@ +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 = []): ?array + { + return $this->request('get', $path, $params); + } + + public function post(string $path, array $params = []): ?array + { + return $this->request('post', $path, $params); + } + + public function put(string $path, array $params = []): ?array + { + return $this->request('put', $path, $params); + } + + public function delete(string $path, array $params = []): ?array + { + return $this->request('delete', $path, $params); + } + + public function postJson(string $path, string $params = ''): ?array + { + return $this->requestJson('post', $path, $params); + } + + public function putJson(string $path, string $params = ''): ?array + { + return $this->requestJson('put', $path, $params); + } + + public function deleteJson(string $path, string $params = ''): ?array + { + return $this->requestJson('delete', $path, $params); + } + + 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 = ''): ?array + { + 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 array|null + */ + protected function prepareAndSendRequest(string $method, string $path, $params = []): ?array + { + $method = strtoupper($method); + $ch = curl_init(); + 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)); + 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) { + print_r([ + '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; + } + + $this->response = new JotformResponse($response, $statusCode, $response["message"] ?? null); + + return $response; + } + + /** + * @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; + } + + /** + * @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, + $path . ($this->outputType === self::OUTPUT_JSON ? '' : '.xml'), + ]; + + $url = implode('/', $segments); + + return $method === 'GET' && is_array($params) && !empty($params) + ? "{$url}?" . http_build_query($params) + : $url; + } +} diff --git a/src/JotformResponse.php b/src/JotformResponse.php new file mode 100644 index 0000000..92828f2 --- /dev/null +++ b/src/JotformResponse.php @@ -0,0 +1,44 @@ +content = $content; + $this->statusCode = $statusCode; + $this->message = $message; + } + + 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..ec967a1 --- /dev/null +++ b/src/Services/Folder.php @@ -0,0 +1,30 @@ +folderId = $folderId; + } + + public function id(): string + { + return $this->folderId; + } + + public function get(): ?array + { + 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..f9a3b68 --- /dev/null +++ b/src/Services/Form.php @@ -0,0 +1,190 @@ +formId = $formId; + } + + public function id(): string + { + return $this->formId; + } + + public function get(): ?array + { + return $this->client->get("{$this->name}/{$this->formId}"); + } + + /** + * @param array|string $params Array or Json + * @return JotformResponse + */ + public function create($params): ?array + { + 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(): ?array + { + return $this->client->delete("{$this->name}/{$this->formId}"); + } + + public function clone(string $formId): ?array + { + return $this->client->post("{$this->name}/{$formId}/clone"); + } + + public function questions(): ?array + { + return $this->client->get("{$this->name}/{$this->formId}/questions", $this->getConditions()); + } + + public function question(string $questionId): ?array + { + 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): ?array + { + $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): ?array + { + return $this->client->post( + "{$this->name}/{$this->formId}/question/{$questionId}", + $this->prepareQuestionParams($params) + ); + } + + public function deleteQuestion(string $questionId): ?array + { + return $this->client->delete("{$this->name}/{$this->formId}/question/{$questionId}"); + } + + public function submissions(): ?array + { + return $this->client->get("{$this->name}/{$this->formId}/submissions", $this->getConditions()); + } + + public function createSubmission(array $params): ?array + { + return (new Submission($this->client, null))->create($this->formId, $params); + } + + public function files(): ?array + { + return $this->client->get("{$this->name}/{$this->formId}/files", $this->getConditions()); + } + + public function webhooks(): ?array + { + return $this->client->get("{$this->name}/{$this->formId}/webhooks", $this->getConditions()); + } + + public function createWebhook(string $url): ?array + { + return $this->client->post("{$this->name}/{$this->formId}/webhooks", [ + 'webhookURL' => $url, + ]); + } + + public function deleteWebhook(string $webhookId): ?array + { + return $this->client->delete("{$this->name}/{$this->formId}/webhooks/{$webhookId}"); + } + + public function properties(): ?array + { + return $this->client->get("{$this->name}/{$this->formId}/properties"); + } + + public function property(string $key): ?array + { + 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): ?array + { + $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(): ?array + { + return $this->client->get("{$this->name}/{$this->formId}/reports", $this->getConditions()); + } + + public function createReport(array $params): ?array + { + 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..9836549 --- /dev/null +++ b/src/Services/Report.php @@ -0,0 +1,35 @@ +reportId = $reportId; + } + + public function id(): string + { + return $this->reportId; + } + + public function get(): ?array + { + return $this->client->get("{$this->name}/{$this->reportId}"); + } + + public function delete(): ?array + { + 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..57c4d1f --- /dev/null +++ b/src/Services/Submission.php @@ -0,0 +1,78 @@ +submissionId = $submissionId; + } + + public function id(): string + { + return $this->submissionId; + } + + public function get(): ?array + { + return $this->client->get("{$this->name}/{$this->submissionId}"); + } + + public function getAll(): ?array + { + 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): ?array + { + $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): ?array + { + return $this->client->post("{$this->name}/{$this->submissionId}", $this->prepareParams($params)); + } + + public function delete(): ?array + { + 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..fd09b8d --- /dev/null +++ b/src/Services/System.php @@ -0,0 +1,19 @@ +folderId; + } + + 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 new file mode 100644 index 0000000..7bbfce5 --- /dev/null +++ b/src/Services/User.php @@ -0,0 +1,85 @@ +client->get($this->name); + } + + public function register(array $user): ?array + { + return $this->client->post("{$this->name}/register", $user); + } + + public function login(array $credentials): ?array + { + return $this->client->post("{$this->name}/login", $credentials); + } + + public function logout(): ?array + { + return $this->client->get("{$this->name}/logout"); + } + + public function usage(): ?array + { + return $this->client->get("{$this->name}/usage"); + } + + public function forms(): ?array + { + return $this->client->get("{$this->name}/forms", $this->getConditions()); + } + + public function createForm(array $params): ?array + { + return (new Form($this->client, null))->create($params); + } + + public function submissions(): ?array + { + return $this->client->get("{$this->name}/submissions", $this->getConditions()); + } + + public function subUsers(): ?array + { + return $this->client->get("{$this->name}/subusers"); + } + + public function folders(): ?array + { + return $this->client->get("{$this->name}/folders"); + } + + public function reports(): ?array + { + return $this->client->get("{$this->name}/reports"); + } + + public function settings(): ?array + { + return $this->client->get("{$this->name}/settings"); + } + + public function updateSettings(array $params): ?array + { + return $this->client->post("{$this->name}/settings", $params); + } + + public function history(): ?array + { + 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..a7ecaf5 --- /dev/null +++ b/src/Traits/UseConditions.php @@ -0,0 +1,69 @@ +offset = $offset; + + return $this; + } + + public function limit(int $limit): self + { + $this->limit = $limit; + + return $this; + } + + public function filter(array $filter): self + { + $this->filter = $filter; + + return $this; + } + + public function orderBy(string $orderBy): self + { + $this->orderBy = $orderBy; + + return $this; + } + + 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 new file mode 100644 index 0000000..e0b765c --- /dev/null +++ b/src/Traits/UseQuery.php @@ -0,0 +1,83 @@ +action = $action; + + return $this; + } + + public function date(string $date): self + { + $this->date = $date; + + return $this; + } + + public function sortBy(string $sortBy): self + { + $this->sortBy = $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 = []; + + 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; + } +} diff --git a/tests/FolderTest.php b/tests/FolderTest.php new file mode 100644 index 0000000..83badcf --- /dev/null +++ b/tests/FolderTest.php @@ -0,0 +1,16 @@ +jotform->folder("")->get(); + + $this->assertEquals(200, $this->jotform->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..4a3614e --- /dev/null +++ b/tests/ReportTest.php @@ -0,0 +1,19 @@ +expectException(JotformException::class); + $report = $this->jotform->report("")->get(); + + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); + $this->assertEmpty($report); + } +} diff --git a/tests/SubmissionTest.php b/tests/SubmissionTest.php new file mode 100644 index 0000000..fa3fcc3 --- /dev/null +++ b/tests/SubmissionTest.php @@ -0,0 +1,41 @@ +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() + { + $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] + $forms = $this->jotform->user()->forms(); + $response = $this->jotform->form($forms[0]['id']) + ->limit(100)->orderBy('created_at')->submissions(); + + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); + } +} diff --git a/tests/SystemTest.php b/tests/SystemTest.php new file mode 100644 index 0000000..047729f --- /dev/null +++ b/tests/SystemTest.php @@ -0,0 +1,41 @@ +jotform->system()->plan('free'); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); + } + + /** @test */ + public function test_get_system_plan_for_bronze() + { + $this->jotform->system()->plan('bronze'); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); + } + + /** @test */ + public function test_get_system_plan_for_silver() + { + $this->jotform->system()->plan('silver'); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); + } + + /** @test */ + public function test_get_system_plan_for_gold() + { + $this->jotform->system()->plan('gold'); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); + } + + /** @test */ + public function test_get_system_plan_for_platinum() + { + $this->jotform->system()->plan('platinum'); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); + } +} diff --git a/tests/TestCase.php b/tests/TestCase.php new file mode 100644 index 0000000..e76c597 --- /dev/null +++ b/tests/TestCase.php @@ -0,0 +1,22 @@ +client = new JotformClient(getenv('JOTFORM_API_KEY')); + $this->jotform = new Jotform($this->client); + } +} diff --git a/tests/UserTest.php b/tests/UserTest.php new file mode 100644 index 0000000..3ab8f41 --- /dev/null +++ b/tests/UserTest.php @@ -0,0 +1,27 @@ +jotform->user()->get(); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); + } + + /** @test */ + public function test_get_user_usage() + { + $this->jotform->user()->usage(); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); + } + + /** @test */ + public function test_get_user_forms() + { + $this->jotform->user()->forms(); + $this->assertEquals(200, $this->jotform->response()->getStatusCode()); + } +}