First, initial commit

This commit is contained in:
Meritoo
2017-09-19 20:46:11 +02:00
commit 08fd482dd9
42 changed files with 8956 additions and 0 deletions

129
.gitignore vendored Normal file
View File

@@ -0,0 +1,129 @@
# ----------------------------------------------------------------------------------------------------------------------
### Vendors
# ----------------------------------------------------------------------------------------------------------------------
/vendor/
# ----------------------------------------------------------------------------------------------------------------------
### Build
# ----------------------------------------------------------------------------------------------------------------------
/build/
# ----------------------------------------------------------------------------------------------------------------------
### Composer
# ----------------------------------------------------------------------------------------------------------------------
/composer.phar
# ----------------------------------------------------------------------------------------------------------------------
### Phing
# ----------------------------------------------------------------------------------------------------------------------
/phing/properties
# ----------------------------------------------------------------------------------------------------------------------
### PHPUnit
# ----------------------------------------------------------------------------------------------------------------------
/phpunit.xml
# ----------------------------------------------------------------------------------------------------------------------
### PHP Coding Standards Fixer generated files
# ----------------------------------------------------------------------------------------------------------------------
/.php_cs.cache
# ----------------------------------------------------------------------------------------------------------------------
### Generated databases
# ----------------------------------------------------------------------------------------------------------------------
/data/tmp
*.sql
*.sqlite
# ----------------------------------------------------------------------------------------------------------------------
### Compiled source
# ----------------------------------------------------------------------------------------------------------------------
*.com
*.class
*.dll
*.exe
*.o
*.so
# ----------------------------------------------------------------------------------------------------------------------
### Shell scripts
# ----------------------------------------------------------------------------------------------------------------------
/*.sh
# ----------------------------------------------------------------------------------------------------------------------
### Linux template
# ----------------------------------------------------------------------------------------------------------------------
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
# ----------------------------------------------------------------------------------------------------------------------
### JetBrains
# ----------------------------------------------------------------------------------------------------------------------
/.idea
# ----------------------------------------------------------------------------------------------------------------------
### Windows template
# ----------------------------------------------------------------------------------------------------------------------
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
# ----------------------------------------------------------------------------------------------------------------------
### macOS template
# ----------------------------------------------------------------------------------------------------------------------
# General
*.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

30
.php_cs.dist Normal file
View File

@@ -0,0 +1,30 @@
<?php
$finder = PhpCsFixer\Finder::create()
/*
* Do not verify:
* - all DependencyInjection/Configuration classes: the Configuration.php files
* - autoloader from /app directory: autoload.php
*/
->notPath('/DependencyInjection\/Configuration\.php/')
->notPath('/autoload\.php/')
->in([
__DIR__ . '/src',
__DIR__ . '/tests',
]);
return PhpCsFixer\Config::create()
->setRules([
'@Symfony' => true,
'phpdoc_summary' => false,
'phpdoc_separation' => false,
'phpdoc_align' => false,
'cast_spaces' => false,
'binary_operator_spaces' => [
'align_double_arrow' => true,
],
'concat_space' => [
'spacing' => 'one',
],
])
->setFinder($finder);

20
LICENSE Normal file
View File

@@ -0,0 +1,20 @@
MIT License
Copyright (c) Meritoo.pl, http://www.meritoo.pl
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

239
README.md Normal file
View File

@@ -0,0 +1,239 @@
# Meritoo LimeSurvey API Client
Client of the [LimeSurvey's API](https://manual.limesurvey.org/RemoteControl_2_API).
## Installation
Run [Composer](https://getcomposer.org) to install this package in your project:
```bash
$ composer require meritoo/limesurvey-api-client
```
> How to install Composer: https://getcomposer.org/download
## Usage
1. First of all you have to prepare configuration of connection and create instance of a client:
```php
use Meritoo\LimeSurvey\ApiClient\Client\Client;
use Meritoo\LimeSurvey\ApiClient\Configuration\ConnectionConfiguration;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
/*
* Prepare configuration of connection and client of the API
*/
$configuration = new ConnectionConfiguration('http://test.com', 'test', 'test');
$client = new Client($configuration);
```
2. Next run the method which you would like:
```php
/*
* Run required method
*/
$result = $client->run(MethodType::LIST_SURVEYS);
```
3. Finally grab data from result of called method:
```php
/*
* ...and grab data from the result
*/
$data = $result->getData();
```
Full code of this example:
```php
use Meritoo\LimeSurvey\ApiClient\Client\Client;
use Meritoo\LimeSurvey\ApiClient\Configuration\ConnectionConfiguration;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
/*
* Prepare configuration of connection and client of the API
*/
$configuration = new ConnectionConfiguration('http://test.com', 'test', 'test');
$client = new Client($configuration);
/*
* Run required method and grab data from the result
*/
$result = $client->run(MethodType::LIST_SURVEYS);
$data = $result->getData();
```
## Available methods
All available methods provides `Meritoo\LimeSurvey\ApiClient\Type\MethodType` class as constants of the class. Examples:
```php
// Add a response to the survey responses collection
MethodType::ADD_RESPONSE;
// The IDs and properties of token/participants of a survey
MethodType::LIST_PARTICIPANTS;
// List the surveys belonging to a user
MethodType::LIST_SURVEYS;
```
Name of the method, actually constant of the `MethodType` class, you should pass as 1st argument of `\Meritoo\LimeSurvey\ApiClient\Client\Client::run()` method. Example:
```php
$client->run(MethodType::GET_PARTICIPANT_PROPERTIES);
```
## Debug mode
In some cases more information may be required to fix bugs. The "debug" mode will help you do this. You can turn it on while preparing configuration of connection by passing `true` as 4th argument of constructor:
```php
use Meritoo\LimeSurvey\ApiClient\Configuration\ConnectionConfiguration;
$configuration = new ConnectionConfiguration('http://test.com', 'test', 'test', true);
```
The "debug" mode can be turned on if the instance of configuration exists by using the `\Meritoo\LimeSurvey\ApiClient\Configuration\ConnectionConfiguration::setDebugMode()` method:
```php
$configuration->setDebugMode(true);
```
If you want to verify if if the "debug" mode is turned on simply call the `\Meritoo\LimeSurvey\ApiClient\Configuration\ConnectionConfiguration::isDebugModeOn()` method:
```php
$debugMode = $configuration->isDebugModeOn();
```
## Getting data from result
#### Verify if the result is empty
First of all you have to call required method to get result - instance of `\Meritoo\LimeSurvey\ApiClient\Result\Result` class. The result allows you to get information if there is any data by calling the `\Meritoo\LimeSurvey\ApiClient\Result\Result::isEmpty()` method:
```php
use Meritoo\LimeSurvey\ApiClient\Result\Result;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
$result = new Result(MethodType::LIST_SURVEYS, []);
$isEmpty = $result->isEmpty();
var_dump($isEmpty); // bool(true)
```
#### Prepared/processed vs raw data
Result allows you to get data, the essence of calling API's method by calling the `\Meritoo\LimeSurvey\ApiClient\Result\Result::getData()` method. This method accepts 1 bool argument:
- `false` - (default) prepared/processed data provided will be returned
- `true` - raw data will be returned
Prepared/processed data means instances of classes from `Meritoo\LimeSurvey\ApiClient\Result\Item\*` namespace.
> Attention.
> 1. The above is true, if result provided by the API *is iterable*. Otherwise - instance of single item is returned.
> 2. Methods that provides iterable result:
>
> - MethodType::LIST_PARTICIPANTS
> - MethodType::LIST_QUESTIONS
> - MethodType::LIST_SURVEYS
> - MethodType::LIST_USERS
>
> They are defined in `Meritoo\LimeSurvey\ApiClient\Type\MethodType::isResultIterable()` method.
#### Prepared/processed data
All instances are returned as elements of collection (instance of `Meritoo\Common\Collection\Collection` class). Example:
```php
class Meritoo\Common\Collection\Collection#565 (1) {
private $elements =>
array(2) {
[0] =>
class Meritoo\LimeSurvey\ApiClient\Result\Item\Survey#564 (5) {
private $id =>
int(456)
private $title =>
string(12) "Another Test"
private $expiresAt =>
NULL
private $active =>
bool(true)
}
[1] =>
class Meritoo\LimeSurvey\ApiClient\Result\Item\Survey#564 (5) {
private $id =>
int(456)
private $title =>
string(12) "Another Test"
private $expiresAt =>
NULL
private $active =>
bool(true)
}
}
}
```
If result provided by the API *is not iterable*, as mentioned above, instance of single item is returned. Example:
```php
class Meritoo\LimeSurvey\ApiClient\Result\Item\Participant#701 (17) {
private $id =>
int(123)
private $participantId =>
int(456)
private $mpId =>
NULL
private $firstName =>
string(5) "Lorem"
private $lastName =>
string(5) "Ipsum"
(...)
}
```
#### Raw data
An array with scalars or other arrays. Example:
```php
array(2) {
[0] =>
array(5) {
'sid' =>
string(3) "123"
'surveyls_title' =>
string(4) "Test"
'startdate' =>
NULL
'expires' =>
string(19) "2017-09-19 13:02:41"
'active' =>
string(1) "N"
}
[1] =>
array(5) {
'sid' =>
string(3) "456"
'surveyls_title' =>
string(12) "Another Test"
'startdate' =>
string(19) "2017-09-19 13:02:41"
'expires' =>
NULL
'active' =>
string(1) "Y"
}
}
```
## Links
- LimeSurvey:
https://www.limesurvey.org
- Composer:
https://getcomposer.org
Enjoy!

46
build.xml Normal file
View File

@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="Meritoo Package" basedir="." default="build:main" phingVersion="2.14.0">
<!-- Properties -->
<if>
<available file="phing/properties" property="custom.properties.available"/>
<then>
<property file="phing/properties" />
</then>
<else>
<property file="phing/properties.dist" />
</else>
</if>
<!-- Default / main target -->
<target name="build:main"
depends="build:app, build:tests"
description="Builds everything and runs all tests" />
<!-- Build app -->
<target name="build:app" description="Prepares app to build and tests">
<phing phingfile="phing/app.xml" haltonfailure="true" />
</target>
<!-- Build tests -->
<target name="build:tests" description="Runs all tests, checks and creates docs">
<phing phingfile="phing/tests.xml" haltonfailure="true" />
<!--
Conditional running of tests.
Disabled, because not required.
Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
2017-02-22
<if>
<equals arg1="${env}" arg2="test" />
<then>
<phing phingfile="phing/tests.xml" haltonfailure="true" />
</then>
<else>
<echo message="[Skipped] Running tests, checks and creating docs, because it's a not 'test' environment..." />
</else>
</if>
-->
</target>
</project>

32
composer.json Normal file
View File

@@ -0,0 +1,32 @@
{
"name": "meritoo/limesurvey-api-client",
"description": "Client of LimeSurvey API",
"type": "library",
"license": "MIT",
"version": "0.0.1",
"authors": [
{
"name": "Meritoo",
"email": "github@meritoo.pl"
}
],
"require": {
"fguillot/json-rpc": "^1.2",
"meritoo/common-library": "~0.0.1"
},
"require-dev": {
"phpunit/phpunit": "^4.8.35 || ^5.4.3",
"squizlabs/php_codesniffer": "^2.8",
"phpmd/phpmd": "^2.6",
"sebastian/phpcpd": "^3.0",
"pdepend/pdepend": "^2.5",
"phploc/phploc": "^4.0",
"friendsofphp/php-cs-fixer": "^2.5"
},
"autoload": {
"psr-4": {
"Meritoo\\LimeSurvey\\": "src/Meritoo/LimeSurvey/",
"Meritoo\\LimeSurvey\\Test\\": "tests/Meritoo/LimeSurvey/Test/"
}
}
}

3581
composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

89
phing/app.xml Normal file
View File

@@ -0,0 +1,89 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="Meritoo Package" basedir="." default="build:main" phingVersion="2.14.0">
<!-- Properties -->
<if>
<available file="phing/properties" property="custom.properties.available"/>
<then>
<property file="phing/properties" />
</then>
<else>
<property file="phing/properties.dist" />
</else>
</if>
<!-- Default / main target -->
<target name="build:main"
depends="build:app"
description="Builds the application" />
<!-- App target -->
<target name="build:app"
depends="app:composer, app:vendors, app:checkout"
description="Prepares app to build." />
<!-- Check / update composer -->
<target name="app:composer" description="Checks / updates composer">
<echo msg="Checking / updating composer..." />
<if>
<available file="composer.phar" />
<then>
<echo msg="[Skipped] Downloading of Composer skipped, because exist in the project..." />
</then>
<else>
<if>
<os family="windows" />
<then>
<fail message="Composer not found! Go to http://getcomposer.org/download and download the Composer." />
</then>
<else>
<exec command="${composer.download_command}" checkreturn="true" />
</else>
</if>
</else>
</if>
<composer command="selfupdate" />
</target>
<!-- Project Install/update vendors -->
<target name="app:vendors" description="Installs / updates vendors">
<echo msg="Installing / updating vendors..." />
<if>
<istrue value="${composer.self-update}"/>
<then>
<composer php="${composer.php}" composer="${composer.path}" command="self-update"/>
</then>
</if>
<if>
<istrue value="${composer.validate}"/>
<then>
<composer php="${composer.php}" composer="${composer.path}" command="validate"/>
</then>
</if>
<if>
<equals arg1="${env}" arg2="prod" />
<then>
<composer php="${composer.php}" composer="${composer.path}" command="install">
<arg value="--optimize-autoloader" />
</composer>
</then>
<else>
<composer php="${composer.php}" composer="${composer.path}" command="install" />
</else>
</if>
</target>
<!-- Checkout and finalization -->
<target name="app:checkout">
<tstamp>
<format property="date_end" pattern="%Y-%m-%d %H:%M" />
</tstamp>
<echo msg="------------------------------------" />
<echo msg="Build finished at: ${date_end}" />
<echo msg="------------------------------------" />
</target>
</project>

125
phing/properties.dist Normal file
View File

@@ -0,0 +1,125 @@
# --------------------------------------------------------------------------------
# Information
# --------------------------------------------------------------------------------
# Property files contain key/value pairs
# key = value
#
# Property keys may contain alphanumeric chars and colons, but
# not special chars. This way you can create pseudo-namespaces
#
# You can refer to values of other properties by enclosing their keys in "${}".
# Example: dir.js = ${dir.web}/js
#
# Everything behind the equal sign is the value, you do
# not have to enclose strings: text=This is some text, Your OS is ${php.os}
# --------------------------------------------------------------------------------
# Common, e.g. default environment
# --------------------------------------------------------------------------------
# Default environment
#
env = dev
# Install assets using symlinks
#
assets.installWithSymlink = true
# Clear cache with the "warmup" option
#
cache.clearWithWarmup = true
# --------------------------------------------------------------------------------
# Composer
# --------------------------------------------------------------------------------
composer.download_command = php -r "eval('?>'.file_get_contents('https://getcomposer.org/installer'));"
# Path to composer executable or composer.phar file
#
composer.path = composer.phar
#composer.path = /usr/local/bin/composer
# Path to php executable used by composer
#
composer.php = php
# Self update of the composer
#
composer.self-update = false
# Validate the composer.json file
#
composer.validate = false
# --------------------------------------------------------------------------------
# Directories
# --------------------------------------------------------------------------------
# System directories
#
dir.data = ${project.basedir}/data
dir.src = ${project.basedir}/src
dir.tests = ${project.basedir}/tests
# --------------------------------------------------------------------------------
# Build directories
# --------------------------------------------------------------------------------
dir.build = ${project.basedir}/build
dir.reports = ${dir.build}/logs
dir.reports.pdepend = ${dir.reports}/pdepend
dir.reports.coverage = ${dir.reports}/phpunit_coverage
#
# Disabled, because unnecessary right now
# phpdocumentor/phpdocumentor cannot be installed via Composer
#
# Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
# 2017-02-22
#
#dir.docs = ${dir.build}/docs
#dir.docs.phpdoc2 = ${dir.docs}/phpdoc2
# --------------------------------------------------------------------------------
# Data directories
# --------------------------------------------------------------------------------
dir.data.tests = ${dir.data}/tests
dir.data.temporary = ${dir.data}/tmp
# --------------------------------------------------------------------------------
# Testing
# --------------------------------------------------------------------------------
# Test database path
#
tests.database = ${dir.data.temporary}/database.sqlite
#
# Disabled, because unnecessary right now
# PHPUnit is installed and loaded by Composer
#
# Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
# 2017-02-22
#
# Run PHPUnit using exec task instead of phpunitTask
#phpunit.useExec = false
#
# Disabled, because unnecessary right now
# We want generate code coverage always
#
# Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
# 2017-02-22
#
# Collect coverage data during tests
#phpunit.withCoverage = true
# Path of the PHPUnit (https://phpunit.de)
#
phpUnit.path = ./vendor/bin/phpunit
# Path of the PHP Coding Standards Fixer (http://cs.sensiolabs.org)
#
phpCsFixer.path = ./vendor/bin/php-cs-fixer

315
phing/tests.xml Normal file
View File

@@ -0,0 +1,315 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="Meritoo Package" basedir="." default="build:main" phingVersion="2.14.0">
<!--
The AutoloaderTask is required to load binaries installed by Composer.
The "autoloaderpath" attribute of this task is not required, because it's default value is: vendor/autoload.php.
Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
2017-02-23
-->
<autoloader />
<!-- Properties -->
<if>
<available file="phing/properties" property="custom.properties.available"/>
<then>
<property file="phing/properties" />
</then>
<else>
<property file="phing/properties.dist" />
</else>
</if>
<!-- Filesets -->
<fileset id="sourcecode" dir="${dir.src}">
<include name="**/*.php" />
<exclude name="*Test.php" />
<exclude name="**/*Test.php" />
<exclude name="**/Resources/**" />
<exclude name="**/DataFixtures/**" />
<exclude name="**/Tests/**" />
</fileset>
<fileset id="tests" dir="${dir.tests}">
<include name="**/*Test*.php" />
</fileset>
<!-- Default / main target -->
<target name="build:main"
depends="build:fix-coding-standards, build:clean, build:prepare, build:check, build:test, app:checkout"
description="Runs all tests and builds everything" />
<!--
Before:
depends="build:fix-coding-standards, build:clean, build:prepare, build:check, build:test, build:doc, app:checkout"
After:
depends="build:fix-coding-standards, build:clean, build:prepare, build:check, build:test, app:checkout"
The "build:doc" task is disabled, because it cannot be installed via Composer:
a) phpdocumentor/phpdocumentor v2.9.0 requires symfony/validator ~2.2
b) symfony/validator ~2.2 causes to remove symfony/symfony 3.*
Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
2017-02-22
-->
<!-- Fixing coding standards using the PHP Coding Standards Fixer (http://cs.sensiolabs.org) -->
<target name="build:fix-coding-standards" description="Fixes coding standards using the PHP Coding Standards Fixer">
<echo msg="Fixing coding standards using the PHP Coding Standards Fixer (http://cs.sensiolabs.org)..." />
<!--
Attention.
Rules for formatting are defined in /.php_cs.dist file.
-->
<exec
passthru="true"
command="${phpCsFixer.path} fix --verbose"
/>
</target>
<!-- Doc target -->
<!--
Disabled, because it cannot be installed via Composer:
a) phpdocumentor/phpdocumentor v2.9.0 requires symfony/validator ~2.2
b) symfony/validator ~2.2 causes to remove symfony/symfony 3.*
Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
2017-02-22
-->
<!--<target name="build:doc"-->
<!--depends="build:prepare, doc:phpdoc2"-->
<!--description="Generates API documentation" />-->
<!-- Check target -->
<target name="build:check"
depends="check:cs, check:md, check:cpd, check:depend, check:loc"
description="Analyzes code" />
<!-- Test target -->
<target name="build:test"
depends="test:phpunit"
description="Executes all tests" />
<!-- Project build clean -->
<target name="build:clean" description="Cleans up build directories">
<echo msg="Cleaning docs and reports directories..." />
<!--<delete dir="${dir.docs}" />-->
<delete dir="${dir.reports}" />
</target>
<!-- Project build prepare -->
<target name="build:prepare" description="Create build directories">
<echo msg="Creating build directories..." />
<!--<mkdir dir="${dir.docs}" />-->
<!--<mkdir dir="${dir.docs.phpdoc2}" />-->
<mkdir dir="${dir.reports}" />
<mkdir dir="${dir.reports.coverage}" />
<mkdir dir="${dir.reports.pdepend}" />
</target>
<!-- PHPDocumentor2 API documentation target -->
<!--
Disabled, because it cannot be installed via Composer:
a) phpdocumentor/phpdocumentor v2.9.0 requires symfony/validator ~2.2
b) symfony/validator ~2.2 causes to remove symfony/symfony 3.*
Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
2017-02-22
<target name="doc:phpdoc2" description="Generates API documentations">
<echo msg="Generating API Documentation with phpDocumentor 2..." />
<phpdoc2 title="${phing.project.name}"
destdir="${dir.docs.phpdoc2}"
template="responsive">
<fileset refid="sourcecode" />
</phpdoc2>
</target>
-->
<!-- Symfony2 code sniffer -->
<!--
Attention 1.
To use Symfony2 standards to check coding you have to:
copy, symlink or check out repo to a folder called Symfony2 inside the phpcs Standards directory.
Example:
$ pear config-show | grep php_dir
$ cd /path/to/pear/PHP/CodeSniffer/Standards
$ git clone git://github.com/opensky/Symfony2-coding-standard.git Symfony2
Attention 2.
PSR2 standard is used instead of Symfony2 standard, because after installation squizlabs/php_codesniffer package
via Composer the Symfony2 standard is not included / available in this package. In this case the PHP Coding
Standards Fixer (http://cs.sensiolabs.org) is used.
Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
2017-02-22
-->
<target name="check:cs" description="Checks coding standard">
<echo msg="Checking coding standard..." />
<phpcodesniffer standard="PSR2" showWarnings="true">
<fileset refid="sourcecode" />
<formatter type="checkstyle" outfile="${dir.reports}/checkstyle.xml" />
<formatter type="csv" outfile="${dir.reports}/checkstyle.csv" />
<formatter type="summary" outfile="${dir.reports}/checkstyle_summary.txt" />
</phpcodesniffer>
</target>
<!-- copy/paste detector -->
<target name="check:cpd" description="Checks similar code blocks.">
<echo msg="Checking similar code blocks..." />
<phpcpd>
<fileset refid="sourcecode" />
<formatter type="pmd" outfile="${dir.reports}/pmd-cpd.xml" />
</phpcpd>
<!--
Previous / old version
Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
2017-02-22
<exec command="phpcpd \-\-log-pmd=${dir.reports}/pmd-cpd.xml ${dir.src}" />
-->
</target>
<!-- Mess detector -->
<target name="check:md" description="Generate code metrics">
<echo msg="Generating code metrics..." />
<phpmd rulesets="codesize,controversial,design,naming,unusedcode">
<fileset refid="sourcecode" />
<formatter type="html" outfile="${dir.reports}/phpmd.html" />
<formatter type="text" outfile="${dir.reports}/phpmd.txt" />
</phpmd>
</target>
<!-- Code dependency -->
<target name="check:depend" description="Checks coupling and dependency">
<echo msg="Checking coupling and dependency..." />
<phpdepend>
<fileset refid="sourcecode" />
<logger type="jdepend-xml" outfile="${dir.reports.pdepend}/jdepend.xml" />
<logger type="jdepend-chart" outfile="${dir.reports.pdepend}/dependencies.svg" />
<logger type="overview-pyramid" outfile="${dir.reports.pdepend}/overview-pyramid.svg" />
</phpdepend>
</target>
<!-- Measure the size and analyzing the structure of a project -->
<target name="check:loc" description="Measures the size and analyzes the structure of a project">
<echo msg="Measuring the size and analyzing the structure of a project..." />
<phploc reportType="txt" reportName="phploc" reportDirectory="${dir.reports}">
<fileset refid="sourcecode" />
</phploc>
<!--
Previous / old version
Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
2017-02-22
<exec command="phploc \-\-log-csv=${dir.reports}/phploc.csv ${dir.src}" />
-->
</target>
<!-- Unit tests -->
<target name="test:phpunit" description="Executes PHPUnit tests">
<!-- Check test database -->
<if>
<not>
<available file="${dir.data.tests}" type="dir" property="dir.data.tests.available" />
</not>
<then>
<mkdir dir="${dir.data.tests}" />
</then>
</if>
<if>
<not>
<available file="${tests.database}" property="tests.database.available" />
</not>
<then>
<touch file="${tests.database}" />
</then>
</if>
<echo msg="Running unit tests..." />
<coverage-setup database="${dir.reports.coverage}/coverage.db">
<fileset refid="sourcecode" />
</coverage-setup>
<exec command="${phpUnit.path} --verbose --configuration ${project.basedir}/phpunit.xml.dist" passthru="true" />
<!--
I have to use ExecTask to run PHPUnit instead of PHPUnitTask, because tests are not running if PHPUnitTask is
used (don't know why):
Total tests run: 0, Failures: 0, Errors: 0, Incomplete: 0, Skipped: 0
Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
2017-02-23
<phpunit configuration="${project.basedir}/phpunit.xml.dist" printsummary="true">
<formatter type="xml" todir="${dir.reports}" outfile="phpunit.xml" />
<formatter type="plain" todir="${dir.reports}" outfile="phpunit.txt" />
<formatter type="clover" todir="${dir.reports.coverage}" />
<formatter type="summary" todir="${dir.reports}" outfile="phpunit_summary.txt" />
</phpunit>
-->
<!--
Previous / old version
Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
2017-02-22
<if>
<istrue value="${phpunit.useExec}" />
<then>
<if>
<istrue value="${phpunit.withCoverage}" />
<then>
<echo message="Running tests with code coverage..." />
<exec command="phpunit \-\-log-junit ${dir.reports}/phpunit.xml \-\-coverage-clover ${dir.reports.coverage}/clover-coverage.xml \-\-coverage-crap4j ${dir.reports.coverage}/crap4j-coverage.xml \-\-coverage-html ${dir.reports.coverage}/ -c ${project.basedir} \-\-colors" passthru="true" checkreturn="true" />
</then>
<else>
<echo message="Running tests without code coverage..." />
<exec command="phpunit \-\-log-junit ${dir.reports}/phpunit.xml -c ${project.basedir} \-\-colors" passthru="true" checkreturn="true" />
</else>
</if>
</then>
<else>
<if>
<istrue value="${phpunit.withCoverage}" />
<then>
<echo message="Running tests with code coverage..." />
<coverage-setup database="${dir.reports.coverage}/coverage.db">
<fileset refid="sourcecode" />
</coverage-setup>
<phpunit printsummary="true" codecoverage="true">
<formatter type="xml" todir="${dir.reports}" outfile="phpunit.xml" />
<formatter type="plain" todir="${dir.reports}" outfile="phpunit.txt" />
<formatter type="clover" todir="${dir.reports.coverage}" />
<formatter type="summary" todir="${dir.reports}" outfile="phpunit_summary.txt" />
</phpunit>
</then>
<else>
<echo message="Running tests without code coverage..." />
<phpunit printsummary="true">
<formatter todir="${dir.reports}" type="xml" outfile="phpunit.xml" />
<batchtest>
<fileset refid="tests" />
</batchtest>
</phpunit>
</else>
</if>
</else>
</if>
-->
</target>
<!-- Checkout and finalization -->
<target name="app:checkout">
<tstamp>
<format property="date_end" pattern="%Y-%m-%d %H:%M" />
</tstamp>
<echo msg="--------------------------------------------" />
<echo msg="Build tests finished at: ${date_end}" />
<echo msg="--------------------------------------------" />
</target>
</project>

35
phpunit.xml.dist Normal file
View File

@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="true"
bootstrap="./vendor/autoload.php"
>
<testsuites>
<testsuite name="Meritoo Package - Main Test Suite">
<directory>./tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory>./src/</directory>
</whitelist>
</filter>
<groups>
<exclude>
<group>performance</group>
</exclude>
</groups>
<logging>
<log type="coverage-html" target="./build/logs/phpunit_coverage/html" />
</logging>
</phpunit>

View File

@@ -0,0 +1,52 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\ApiClient\Base\Result;
/**
* Base class for one item of result/data fetched while talking to the LimeSurvey's API
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
abstract class BaseItem
{
/**
* Sets values in each property of the item
*
* @param array $data Data to set in properties of the item
* @return $this
*/
public function setValues($data)
{
/*
* Oops, no data
*/
if (empty($data)) {
return $this;
}
/*
* Let's iterate through each property
*/
foreach ($data as $property => $value) {
$this->setValue($property, $value);
}
return $this;
}
/**
* Sets given value in given property
*
* @param string $property Name of property to set the value
* @param mixed $value Value to set in property
* @return mixed
*/
abstract public function setValue($property, $value);
}

View File

@@ -0,0 +1,137 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\ApiClient\Client;
use Meritoo\LimeSurvey\ApiClient\Configuration\ConnectionConfiguration;
use Meritoo\LimeSurvey\ApiClient\Exception\UnknownInstanceOfResultItem;
use Meritoo\LimeSurvey\ApiClient\Exception\UnknownMethodException;
use Meritoo\LimeSurvey\ApiClient\Manager\JsonRpcClientManager;
use Meritoo\LimeSurvey\ApiClient\Manager\SessionManager;
use Meritoo\LimeSurvey\ApiClient\Result\Result;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
/**
* Client of the LimeSurvey's API
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class Client
{
/**
* Configuration used while connecting to LimeSurvey's API
*
* @var ConnectionConfiguration
*/
private $configuration;
/**
* Manager of the JsonRPC client used while connecting to LimeSurvey's API
*
* @var JsonRpcClientManager
*/
private $rpcClientManager;
/**
* Manager of session started while connecting to LimeSurvey's API
*
* @var SessionManager
*/
private $sessionManager;
/**
* Class constructor
*
* @param ConnectionConfiguration $configuration Configuration used while connecting to LimeSurvey's API
* @param JsonRpcClientManager $rpcClientManager (optional) Manager of the JsonRPC client used while
* connecting to LimeSurvey's API
* @param SessionManager $sessionManager (optional) Manager of session started while connecting to
* LimeSurvey's API
*/
public function __construct(
ConnectionConfiguration $configuration,
JsonRpcClientManager $rpcClientManager = null,
SessionManager $sessionManager = null
) {
$this->configuration = $configuration;
$this->rpcClientManager = $rpcClientManager;
$this->sessionManager = $sessionManager;
}
/**
* Runs method with given name, arguments and returns result
*
* @param string $method Name of method to call. One of the MethodType class constants.
* @param array $arguments (optional) Arguments of the method to call
* @return Result
*
* @throws UnknownMethodException
* @throws UnknownInstanceOfResultItem
*/
public function run($method, $arguments = [])
{
/*
* Let's validate method
*/
$method = MethodType::getValidatedMethod($method);
/*
* Prepare key of session
*/
$username = $this->configuration->getUsername();
$password = $this->configuration->getPassword();
$sessionKey = $this
->getSessionManager()
->getSessionKey($username, $password);
/*
* Use the session's key as of the method's arguments
*/
array_unshift($arguments, $sessionKey);
/*
* Run the method, fetch raw data and finally prepare result
*/
$rawData = $this
->getRpcClientManager()
->runMethod($method, $arguments);
return new Result($method, $rawData);
}
/**
* Returns manager of the JsonRPC client used while connecting to LimeSurvey's API
*
* @return JsonRpcClientManager
*/
private function getRpcClientManager()
{
if (null === $this->rpcClientManager) {
$this->rpcClientManager = new JsonRpcClientManager($this->configuration);
}
return $this->rpcClientManager;
}
/**
* Returns manager of session started while connecting to LimeSurvey's API
*
* @return SessionManager
*/
private function getSessionManager()
{
if (null === $this->sessionManager) {
$rpcClientManager = $this->getRpcClientManager();
$this->sessionManager = new SessionManager($rpcClientManager);
}
return $this->sessionManager;
}
}

View File

@@ -0,0 +1,220 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\ApiClient\Configuration;
use Meritoo\Common\Exception\Regex\InvalidUrlException;
use Meritoo\Common\Utilities\Regex;
/**
* Configuration used while connecting to LimeSurvey's API
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class ConnectionConfiguration
{
/**
* Base url.
* Protocol & domain.
*
* Example:
* http://my-domain.com
*
* @var string
*/
private $baseUrl;
/**
* Url of the LimeSurvey's remote control (without starting slash)
*
* @var string
*/
private $remoteControlUrl = 'admin/remotecontrol';
/**
* Name of user used to authenticate to LimeSurvey
*
* @var string
*/
private $username;
/**
* Password used to authenticate to LimeSurvey
*
* @var string
*/
private $password;
/**
* If is set to true, the "debug" mode is turned on. Otherwise - turned off.
* If turned on, more information is displayed.
*
* @var bool
*/
private $debugMode = false;
/**
* Class constructor
*
* @param string $baseUrl Base url. Protocol & domain.
* @param string $username Name of user used to authenticate to LimeSurvey
* @param string $password Password used to authenticate to LimeSurvey
* @param bool $debugMode (optional) If is set to true, the "debug" mode is turned on. Otherwise - turned off.
*/
public function __construct($baseUrl, $username, $password, $debugMode = false)
{
$this
->setBaseUrl($baseUrl)
->setUsername($username)
->setPassword($password)
->setDebugMode($debugMode);
}
/**
* Returns the base url, protocol & domain
*
* @return string
*/
public function getBaseUrl()
{
return $this->baseUrl;
}
/**
* Sets the base url, protocol & domain
*
* @param string $baseUrl The base url, protocol & domain
* @return $this
*
* @throws InvalidUrlException
*/
public function setBaseUrl($baseUrl)
{
if (!Regex::isValidUrl($baseUrl)) {
throw new InvalidUrlException($baseUrl);
}
if (Regex::endsWith($baseUrl, '/')) {
$baseUrl = substr($baseUrl, 0, strlen($baseUrl) - 1);
}
$this->baseUrl = $baseUrl;
return $this;
}
/**
* Returns the url of the LimeSurvey's remote control
*
* @return string
*/
public function getRemoteControlUrl()
{
return $this->remoteControlUrl;
}
/**
* Sets the url of the LimeSurvey's remote control
*
* @param string $remoteControlUrl Url of the LimeSurvey's remote control
* @return $this
*/
public function setRemoteControlUrl($remoteControlUrl)
{
$this->remoteControlUrl = $remoteControlUrl;
return $this;
}
/**
* Returns the name of user used to authenticate to LimeSurvey
*
* @return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Sets the name of user used to authenticate to LimeSurvey
*
* @param string $username The name of user used to authenticate to LimeSurvey
* @return $this
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Returns the password used to authenticate to LimeSurvey
*
* @return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Sets the password used to authenticate to LimeSurvey
*
* @param string $password The password used to authenticate to LimeSurvey
* @return $this
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Returns information if the "debug" mode is turned on
*
* @return bool
*/
public function isDebugModeOn()
{
return $this->debugMode;
}
/**
* Sets information if the "debug" mode is turned on
*
* @param bool $debugMode (optional) If is set to true, the "debug" mode is turned on. Otherwise - turned off.
* @return $this
*/
public function setDebugMode($debugMode = false)
{
$this->debugMode = $debugMode;
return $this;
}
/*
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* Additional / extra methods (neither getters, nor setters)
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/
/**
* Returns full url of the LimeSurvey's API.
* It's a base url with part related to remote control.
*
* @return string
*/
public function getFullUrl()
{
return sprintf('%s/%s', $this->baseUrl, $this->remoteControlUrl);
}
}

View File

@@ -0,0 +1,36 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\ApiClient\Exception;
use Exception;
/**
* An exception used while create of the session key has failed
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class CreateSessionKeyFailedException extends Exception
{
/**
* Class constructor
*
* @param string $reason (optional) Reason of failure, e.g. "Invalid user name or password"
*/
public function __construct($reason = '')
{
$message = 'Create of the session key has failed';
if (!empty($reason)) {
$message = sprintf('%s. Reason: \'%s\'.', $message, $reason);
}
parent::__construct($message);
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace Meritoo\LimeSurvey\ApiClient\Exception;
use Exception;
use Meritoo\LimeSurvey\ApiClient\Result\Processor\ResultProcessor;
/**
* An exception used while instance of one item used by result, with data fetched from the LimeSurvey's API, is unknown
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class UnknownInstanceOfResultItem extends Exception
{
/**
* Class constructor
*
* @param string $method Name of called method while talking to the LimeSurvey's API. One of the MethodType class
* constants.
*/
public function __construct($method)
{
$template = 'Instance of one item used by result the of \'%s\' LimeSurvey API\'s method is unknown. Proper'
. ' class is not mapped in %s::%s() method. Did you forget about this?';
$message = sprintf($template, $method, ResultProcessor::class, 'getItemInstance');
parent::__construct($message);
}
}

View File

@@ -0,0 +1,29 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\ApiClient\Exception;
use Meritoo\Common\Exception\Base\UnknownTypeException;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
/**
* An exception used while name of method used while talking to the LimeSurvey's API is unknown
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class UnknownMethodException extends UnknownTypeException
{
/**
* {@inheritdoc}
*/
public function __construct($unknownType)
{
parent::__construct($unknownType, new MethodType(), 'name of method used while talking to the LimeSurvey\'s API');
}
}

View File

@@ -0,0 +1,84 @@
<?php
namespace Meritoo\LimeSurvey\ApiClient\Manager;
use JsonRPC\Client as RpcClient;
use Meritoo\LimeSurvey\ApiClient\Configuration\ConnectionConfiguration;
use Meritoo\LimeSurvey\ApiClient\Exception\UnknownMethodException;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
/**
* Manager of the JsonRPC client used while connecting to LimeSurvey's API
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class JsonRpcClientManager
{
/**
* Configuration used while connecting to LimeSurvey's API
*
* @var ConnectionConfiguration
*/
private $connectionConfiguration;
/**
* The JsonRPC client used while connecting to LimeSurvey's API
*
* @var RpcClient
*/
private $rpcClient;
/**
* Class constructor
*
* @param ConnectionConfiguration $configuration Configuration used while connecting to LimeSurvey's API
*/
public function __construct(ConnectionConfiguration $configuration)
{
$this->connectionConfiguration = $configuration;
}
/**
* Runs given method with given arguments and returns raw data
*
* @param string $method Name of method to call. One of the MethodType class constants.
* @param array $arguments (optional) Arguments of the method to call
* @return mixed
*
* @throws UnknownMethodException
*/
public function runMethod($method, $arguments = [])
{
$method = MethodType::getValidatedMethod($method);
return $this
->getRpcClient()
->execute($method, $arguments);
}
/**
* Returns the JsonRPC client used while connecting to LimeSurvey's API
*
* @return RpcClient
*/
protected function getRpcClient()
{
if (null === $this->rpcClient) {
/*
* Let's prepare the JsonRPC Client
*/
$url = $this->connectionConfiguration->getFullUrl();
$this->rpcClient = new RpcClient($url);
/*
* The "debug" mode is turned on?
*/
if ($this->connectionConfiguration->isDebugModeOn()) {
$this->rpcClient->getHttpClient()->withDebug();
}
}
return $this->rpcClient;
}
}

View File

@@ -0,0 +1,115 @@
<?php
namespace Meritoo\LimeSurvey\ApiClient\Manager;
use Meritoo\LimeSurvey\ApiClient\Exception\CreateSessionKeyFailedException;
use Meritoo\LimeSurvey\ApiClient\Type\SystemMethodType;
/**
* Manager of session started while connecting to LimeSurvey's API
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class SessionManager
{
/**
* The session key.
* Used to authenticate user while connecting to LimeSurvey's API.
*
* @var string
*/
private $sessionKey;
/**
* Manager of the JsonRPC client used while connecting to LimeSurvey's API
*
* @var JsonRpcClientManager
*/
private $rpcClientManager;
/**
* Class constructor
*
* @param JsonRpcClientManager $rpcClientManager Manager of the JsonRPC client used while connecting to
* LimeSurvey's API
*/
public function __construct(JsonRpcClientManager $rpcClientManager)
{
$this->rpcClientManager = $rpcClientManager;
}
/**
* Class destructor
*/
public function __destruct()
{
$this->releaseSessionKey();
}
/**
* Returns key/id of session used while connecting to LimeSurvey's API
*
* @param string $username Name of user used to authenticate to LimeSurvey
* @param string $password Password used to authenticate to LimeSurvey
* @return string
*
* @throws CreateSessionKeyFailedException
*/
public function getSessionKey($username, $password)
{
if (null === $this->sessionKey) {
$arguments = [
$username,
$password,
];
/*
* Let's fetch the key/id of session
*/
$this->sessionKey = $this
->rpcClientManager
->runMethod(SystemMethodType::GET_SESSION_KEY, $arguments);
/*
* Oops, something is broken
*/
if (is_array($this->sessionKey)) {
$reason = '';
/*
* The "status" is provided?
* It's a reason of failure
*/
if (isset($this->sessionKey['status'])) {
$reason = $this->sessionKey['status'];
}
throw new CreateSessionKeyFailedException($reason);
}
}
return $this->sessionKey;
}
/**
* Releases key/id of session and closes the RPC session
*
* @return $this
*/
public function releaseSessionKey()
{
$arguments = [
$this->sessionKey,
];
/*
* Let's release the key/id of session
*/
$this
->rpcClientManager
->runMethod(SystemMethodType::RELEASE_SESSION_KEY, $arguments);
return $this;
}
}

View File

@@ -0,0 +1,397 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\ApiClient\Result\Item;
use DateTime;
use Meritoo\Common\Utilities\Date;
use Meritoo\LimeSurvey\ApiClient\Base\Result\BaseItem;
/**
* One item of the result/data: full data of participant
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class Participant extends BaseItem
{
/**
* ID of the participant
*
* @var int
*/
private $id;
/**
* Another ID of the participant?
* Don't know where it is used.
*
* @var int
*/
private $participantId;
/**
* MP ID
*
* @var int
*/
private $mpId;
/**
* First name of the participant
*
* @var string
*/
private $firstName;
/**
* Last name of the participant
*
* @var string
*/
private $lastName;
/**
* E-mail of the participant
*
* @var string
*/
private $email;
/**
* Status of the e-mail
*
* @var string
*/
private $emailStatus;
/**
* Token of the participant
*
* @var string
*/
private $token;
/**
* Language of the participant
*
* @var string
*/
private $language;
/**
* Information if participant is blacklisted
*
* @var bool
*/
private $blacklisted;
/**
* Information if token was sent to participant/user
*
* @var bool
*/
private $sent;
/**
* Information if reminder about token was sent to participant/user
*
* @var bool
*/
private $reminderSent;
/**
* Count of sent reminders to participant/user
*
* @var int
*/
private $reminderCount;
/**
* Information if the participant has completed the survey
*
* @var bool
*/
private $completed;
/**
* Count of left uses of the token
*
* @var int
*/
private $usesLeft;
/**
* Information from which day the token is valid
*
* @var DateTime
*/
private $validFrom;
/**
* Information until which day the token is valid
*
* @var DateTime
*/
private $validUntil;
/**
* {@inheritdoc}
*/
public function setValue($property, $value)
{
switch ($property) {
case 'tid':
$this->id = (int)$value;
break;
case 'participant_id':
$this->participantId = (int)$value;
break;
case 'mpid':
$this->mpId = (int)$value;
break;
case 'firstname':
$this->firstName = trim($value);
break;
case 'lastname':
$this->lastName = trim($value);
break;
case 'email':
$this->email = trim($value);
break;
case 'emailstatus':
$this->emailStatus = trim($value);
break;
case 'token':
$this->token = trim($value);
break;
case 'language':
$this->language = trim($value);
break;
case 'blacklisted':
$this->blacklisted = 'Y' === trim($value);
break;
case 'sent':
$this->sent = 'Y' === trim($value);
break;
case 'remindersent':
$this->reminderSent = 'Y' === trim($value);
break;
case 'remindercount':
$this->reminderCount = (int)$value;
break;
case 'completed':
$this->completed = 'Y' === trim($value);
break;
case 'usesleft':
$this->usesLeft = (int)$value;
break;
case 'validfrom':
if (null === $value) {
break;
}
$this->validFrom = Date::getDateTime($value, false, 'Y-m-d H:i:s');
break;
case 'validuntil':
if (null === $value) {
break;
}
$this->validUntil = Date::getDateTime($value, false, 'Y-m-d H:i:s');
break;
}
}
/**
* Returns ID of the participant
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Returns another ID of the participant?
* Don't know where it is used.
*
* @return int
*/
public function getParticipantId()
{
return $this->participantId;
}
/**
* Returns MP ID
*
* @return int
*/
public function getMpId()
{
return $this->mpId;
}
/**
* Returns first name of the participant
*
* @return string
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* Returns last name of the participant
*
* @return string
*/
public function getLastName()
{
return $this->lastName;
}
/**
* Returns e-mail of the participant
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Returns status of the e-mail
*
* @return string
*/
public function getEmailStatus()
{
return $this->emailStatus;
}
/**
* Returns token of the participant
*
* @return string
*/
public function getToken()
{
return $this->token;
}
/**
* Returns language of the participant
*
* @return string
*/
public function getLanguage()
{
return $this->language;
}
/**
* Returns information if participant is blacklisted
*
* @return bool
*/
public function isBlacklisted()
{
return $this->blacklisted;
}
/**
* Returns information if token was sent to participant/user
*
* @return bool
*/
public function isSent()
{
return $this->sent;
}
/**
* Returns information if reminder about token was sent to participant/user
*
* @return bool
*/
public function isReminderSent()
{
return $this->reminderSent;
}
/**
* Returns count of sent reminders to participant/user
*
* @return int
*/
public function getReminderCount()
{
return $this->reminderCount;
}
/**
* Returns information if the participant has completed the survey
*
* @return bool
*/
public function isCompleted()
{
return $this->completed;
}
/**
* Returns count of left uses of the token
*
* @return int
*/
public function getUsesLeft()
{
return $this->usesLeft;
}
/**
* Returns information from which day the token is valid
*
* @return DateTime
*/
public function getValidFrom()
{
return $this->validFrom;
}
/**
* Returns information until which day the token is valid
*
* @return DateTime
*/
public function getValidUntil()
{
return $this->validUntil;
}
}

View File

@@ -0,0 +1,106 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\ApiClient\Result\Item;
use Meritoo\LimeSurvey\ApiClient\Base\Result\BaseItem;
/**
* One item of the result/data: short data of one participant
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class ParticipantShort extends BaseItem
{
/**
* ID of the participant
*
* @var int
*/
private $id;
/**
* First name of the participant
*
* @var string
*/
private $firstName;
/**
* Last name of the participant
*
* @var string
*/
private $lastName;
/**
* E-mail of the participant
*
* @var string
*/
private $email;
/**
* {@inheritdoc}
*/
public function setValue($property, $value)
{
switch ($property) {
case 'tid':
$this->id = (int)$value;
break;
case 'participant_info':
$this->firstName = trim($value['firstname']);
$this->lastName = trim($value['lastname']);
$this->email = trim($value['email']);
break;
}
}
/**
* Returns ID of the participant
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Returns first name of the participant
*
* @return string
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* Returns last name of the participant
*
* @return string
*/
public function getLastName()
{
return $this->lastName;
}
/**
* Returns e-mail of the participant
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
}

View File

@@ -0,0 +1,153 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\ApiClient\Result\Item;
/**
* One item of the result/data: full data of one question of survey
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class Question extends QuestionShort
{
/**
* Available answers
*
* @var array
*/
private $availableAnswers;
/**
* Sub-questions
* @var array
*/
private $subQuestions;
/**
* Attributes
*
* @var array
*/
private $attributes;
/**
* Attributes in languages
*
* @var array
*/
private $attributesLanguages;
/**
* Answer's options
*
* @var array
*/
private $answerOptions;
/**
* Default value
*
* @var string
*/
private $defaultValue;
/**
* {@inheritdoc}
*/
public function setValue($property, $value)
{
parent::setValue($property, $value);
switch ($property) {
case 'available_answers':
$this->availableAnswers = $value;
break;
case 'subquestions':
$this->subQuestions = $value;
break;
case 'attributes':
$this->attributes = $value;
break;
case 'attributes_lang':
$this->attributesLanguages = $value;
break;
case 'answeroptions':
$this->answerOptions = $value;
break;
case 'defaultvalue':
$this->defaultValue = $value;
break;
}
}
/**
* Returns available answers
*
* @return array
*/
public function getAvailableAnswers()
{
return $this->availableAnswers;
}
/**
* Returns sub-questions
*
* @return array
*/
public function getSubQuestions()
{
return $this->subQuestions;
}
/**
* Returns attributes
*
* @return array
*/
public function getAttributes()
{
return $this->attributes;
}
/**
* Returns attributes in languages
*
* @return array
*/
public function getAttributesLanguages()
{
return $this->attributesLanguages;
}
/**
* Returns answer's options
*
* @return array
*/
public function getAnswerOptions()
{
return $this->answerOptions;
}
/**
* Returns default value
*
* @return string
*/
public function getDefaultValue()
{
return $this->defaultValue;
}
}

View File

@@ -0,0 +1,398 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\ApiClient\Result\Item;
use Meritoo\LimeSurvey\ApiClient\Base\Result\BaseItem;
/**
* One item of the result/data: short data of one question of survey
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class QuestionShort extends BaseItem
{
/**
* ID of the question
*
* @var int
*/
private $id;
/**
* ID of the parent question
*
* @var int
*/
private $parentId;
/**
* ID of the survey
*
* @var int
*/
private $surveyId;
/**
* ID of the group of questions
*
* @var int
*/
private $groupId;
/**
* ID of the scale
* (what does it mean?)
*
* @var int
*/
private $scaleId;
/**
* Type of the question
*
* @var string
*/
private $type;
/**
* Title of the question
*
* @var string
*/
private $title;
/**
* Content of the question
*
* @var string
*/
private $content;
/**
* Explanation of the question
*
* @var string
*/
private $contentHelp;
/**
* Regular expression
* (what does it mean? used to validate answer?)
*
* @var string
*/
private $regularExpression;
/**
* Information if type of question is other
* (what does it mean?)
*
* @var bool
*/
private $other;
/**
* Information if the question mandatory
*
* @var bool
*/
private $mandatory;
/**
* Position/Order of the question
*
* @var int
*/
private $position;
/**
* Language of the question
*
* @var string
*/
private $language;
/**
* Same as default
* (what does it mean?)
*
* @var int
*/
private $sameDefault;
/**
* Relevant equation
*
* @var string
*/
private $relevance;
/**
* Name of module
* (what does it mean?)
*
* @var string
*/
private $moduleName;
/**
* {@inheritdoc}
*/
public function setValue($property, $value)
{
switch ($property) {
case 'qid':
$this->id = (int)$value;
break;
case 'parent_qid':
$this->parentId = (int)$value;
break;
case 'sid':
$this->surveyId = (int)$value;
break;
case 'gid':
$this->groupId = (int)$value;
break;
case 'scale_id':
$this->scaleId = (int)$value;
break;
case 'type':
$this->type = trim($value);
break;
case 'title':
$this->title = trim($value);
break;
case 'question':
$this->content = trim($value);
break;
case 'help':
$this->contentHelp = trim($value);
break;
case 'preg':
if (null === $value) {
break;
}
$this->regularExpression = trim($value);
break;
case 'other':
$this->other = 'Y' === trim($value);
break;
case 'mandatory':
$this->mandatory = 'Y' === trim($value);
break;
case 'question_order':
$this->position = (int)$value;
break;
case 'language':
$this->language = trim($value);
break;
case 'same_default':
$this->sameDefault = (int)$value;
break;
case 'relevance':
$this->relevance = trim($value);
break;
case 'modulename':
if (null === $value) {
break;
}
$this->moduleName = trim($value);
break;
}
}
/**
* Returns ID of the question
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Returns ID of the parent question
*
* @return int
*/
public function getParentId()
{
return $this->parentId;
}
/**
* Returns ID of the survey
*
* @return int
*/
public function getSurveyId()
{
return $this->surveyId;
}
/**
* Returns ID of the group of questions
*
* @return int
*/
public function getGroupId()
{
return $this->groupId;
}
/**
* Returns ID of the scale
*
* @return int
*/
public function getScaleId()
{
return $this->scaleId;
}
/**
* Returns type of the question
*
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* Returns title of the question
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Returns content of the question
*
* @return string
*/
public function getContent()
{
return $this->content;
}
/**
* Returns explanation of the question
*
* @return string
*/
public function getContentHelp()
{
return $this->contentHelp;
}
/**
* Returns regular expression
*
* @return string
*/
public function getRegularExpression()
{
return $this->regularExpression;
}
/**
* Returns information if type of question is other
*
* @return bool
*/
public function isOther()
{
return $this->other;
}
/**
* Returns information if the question mandatory
*
* @return bool
*/
public function isMandatory()
{
return $this->mandatory;
}
/**
* Returns position/Order of the question
*
* @return int
*/
public function getPosition()
{
return $this->position;
}
/**
* Returns language of the question
*
* @return string
*/
public function getLanguage()
{
return $this->language;
}
/**
* Returns information related to same as default
*
* @return int
*/
public function getSameDefault()
{
return $this->sameDefault;
}
/**
* Returns relevant equation
*
* @return string
*/
public function getRelevance()
{
return $this->relevance;
}
/**
* Returns name of module
*
* @return string
*/
public function getModuleName()
{
return $this->moduleName;
}
}

View File

@@ -0,0 +1,143 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\ApiClient\Result\Item;
use DateTime;
use Meritoo\Common\Utilities\Date;
use Meritoo\LimeSurvey\ApiClient\Base\Result\BaseItem;
/**
* One item of the result/data: survey
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class Survey extends BaseItem
{
/**
* ID of the survey
*
* @var int
*/
private $id;
/**
* Title of the survey
*
* @var string
*/
private $title;
/**
* Date when the survey starts
*
* @var DateTime
*/
private $startsAt;
/**
* Date when the survey expires
*
* @var DateTime
*/
private $expiresAt;
/**
* Information if the survey is active
*
* @var bool
*/
private $active = false;
/**
* {@inheritdoc}
*/
public function setValue($property, $value)
{
switch ($property) {
case 'sid':
$this->id = (int)$value;
break;
case 'surveyls_title':
$this->title = trim($value);
break;
case 'startdate':
if (null === $value) {
break;
}
$this->startsAt = Date::getDateTime($value, false, 'Y-m-d H:i:s');
break;
case 'expires':
if (null === $value) {
break;
}
$this->expiresAt = Date::getDateTime($value, false, 'Y-m-d H:i:s');
break;
case 'active':
$this->active = 'Y' === trim($value);
break;
}
}
/**
* Returns ID of the survey
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Returns title of the survey
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Returns date when the survey starts
*
* @return DateTime|null
*/
public function getStartsAt()
{
return $this->startsAt;
}
/**
* Returns date when the survey expires
*
* @return DateTime|null
*/
public function getExpiresAt()
{
return $this->expiresAt;
}
/**
* Returns information if the survey is active
*
* @return bool
*/
public function isActive()
{
return $this->active;
}
}

View File

@@ -0,0 +1,118 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\ApiClient\Result\Processor;
use Meritoo\LimeSurvey\ApiClient\Base\Result\BaseItem;
use Meritoo\LimeSurvey\ApiClient\Exception\UnknownInstanceOfResultItem;
use Meritoo\LimeSurvey\ApiClient\Result\Item\Participant;
use Meritoo\LimeSurvey\ApiClient\Result\Item\ParticipantShort;
use Meritoo\LimeSurvey\ApiClient\Result\Item\Question;
use Meritoo\LimeSurvey\ApiClient\Result\Item\QuestionShort;
use Meritoo\LimeSurvey\ApiClient\Result\Item\Survey;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
/**
* Processor of the raw data fetched while talking to the LimeSurvey's API
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class ResultProcessor
{
/**
* Returns processed data based on the raw data returned by the LimeSurvey's API
*
* @param string $method Name of called method while talking to the LimeSurvey's API. One of the MethodType
* class constants.
* @param array $rawData Data returned by the LimeSurvey's API
* @return null|BaseItem|array
*/
public function process($method, array $rawData)
{
$method = MethodType::getValidatedMethod($method);
/*
* No data?
* Nothing to do
*/
if (empty($rawData)) {
return null;
}
/*
* Prepare instance of one item
*/
$item = $this->getItemInstance($method);
/*
* The raw data is or, actually, should be iterable?
*/
if (MethodType::isResultIterable($method)) {
$items = [];
$emptyItem = clone $item;
foreach ($rawData as $itemData) {
$items[] = $emptyItem->setValues($itemData);
}
return $items;
}
return $item->setValues($rawData);
}
/**
* Returns instance of one item of the result
*
* @param string $method Name of called method while talking to the LimeSurvey's API. One of the MethodType
* class constants.
* @return BaseItem
* @throws UnknownInstanceOfResultItem
*/
private function getItemInstance($method)
{
$item = null;
$method = MethodType::getValidatedMethod($method);
switch ($method) {
case MethodType::GET_PARTICIPANT_PROPERTIES:
$item = new Participant();
break;
case MethodType::GET_QUESTION_PROPERTIES:
$item = new Question();
break;
case MethodType::LIST_PARTICIPANTS:
$item = new ParticipantShort();
break;
case MethodType::LIST_QUESTIONS:
$item = new QuestionShort();
break;
case MethodType::LIST_SURVEYS:
$item = new Survey();
break;
/*
* todo: Use other types of methods and create proper classes (used to get instances of one item)
*/
}
/*
* Instance of the item is unknown?
*/
if (null === $item) {
throw new UnknownInstanceOfResultItem($method);
}
return $item;
}
}

View File

@@ -0,0 +1,122 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\ApiClient\Result;
use Meritoo\Common\Collection\Collection;
use Meritoo\LimeSurvey\ApiClient\Base\Result\BaseItem;
use Meritoo\LimeSurvey\ApiClient\Result\Processor\ResultProcessor;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
/**
* Result with data fetched while talking to the LimeSurvey's API
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class Result
{
/**
* Name of called method while talking to the LimeSurvey's API. One of the MethodType class constants.
*
* @var string
*/
private $method;
/**
* Raw data returned by the LimeSurvey's API
*
* @var array
*/
private $rawData;
/**
* Processor of the raw data fetched while talking to the LimeSurvey's API
*
* @var ResultProcessor
*/
private $resultProcessor;
/**
* Class constructor
*
* @param string $method Name of called method while talking to the LimeSurvey's API. One of the MethodType
* class constants.
* @param array $rawData Raw data returned by the LimeSurvey's API
*/
public function __construct($method, array $rawData)
{
$this->method = MethodType::getValidatedMethod($method);
$this->rawData = $rawData;
}
/**
* Returns information if the result contains any data
*
* @return bool
*/
public function isEmpty()
{
return empty($this->rawData);
}
/**
* Returns data returned by the LimeSurvey's API
*
* @param bool $raw (optional) If is set to true, raw data provided by the LimeSurvey's API will be returned.
* Otherwise - prepared/processed.
* @return array|Collection|BaseItem
*/
public function getData($raw = false)
{
if ($raw) {
return $this->rawData;
}
return $this->getProcessedData($this->rawData);
}
/**
* Returns processed data based on the raw data returned by the LimeSurvey's API
*
* @param array $rawData Raw data returned by the LimeSurvey's API
* @return Collection|BaseItem
*/
private function getProcessedData(array $rawData)
{
$processed = $this
->getResultProcessor()
->process($this->method, $rawData);
if (null === $processed || is_array($processed)) {
$collection = new Collection();
if (is_array($processed)) {
$collection->addMultiple($processed);
}
return $collection;
}
return $processed;
}
/**
* Returns processor of the raw data fetched while talking to the LimeSurvey's API
*
* @return ResultProcessor
*/
private function getResultProcessor()
{
if (null === $this->resultProcessor) {
$this->resultProcessor = new ResultProcessor();
}
return $this->resultProcessor;
}
}

View File

@@ -0,0 +1,113 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\ApiClient\Type;
use Meritoo\Common\Type\Base\BaseType;
use Meritoo\LimeSurvey\ApiClient\Exception\UnknownMethodException;
/**
* Type of method used while talking with LimeSurvey's API
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class MethodType extends BaseType
{
/**
* Add a response to the survey responses collection.
* Returns the id of the inserted survey response.
*
* @var string
*/
const ADD_RESPONSE = 'add_response';
/**
* Export statistics of a survey to a user
*
* @var string
*/
const EXPORT_STATISTICS = 'export_statistics';
/**
* Get settings of a token/participant of a survey
*
* @var string
*/
const GET_PARTICIPANT_PROPERTIES = 'get_participant_properties';
/**
* Get properties of a question in a survey
*
* @var string
*/
const GET_QUESTION_PROPERTIES = 'get_question_properties';
/**
* Return the IDs and properties of token/participants of a survey
*
* @var string
*/
const LIST_PARTICIPANTS = 'list_participants';
/**
* Return the ids and info of (sub-)questions of a survey/group
*
* @var string
*/
const LIST_QUESTIONS = 'list_questions';
/**
* List the surveys belonging to a user
*
* @var string
*/
const LIST_SURVEYS = 'list_surveys';
/**
* Get list the ids and info of users
*
* @var string
*/
const LIST_USERS = 'list_users';
/**
* Returns validated name of method to call or throws an exception (if method is incorrect)
*
* @param string $method Name of method to call. One of this class constants.
* @return string
*
* @throws UnknownMethodException
*/
public static function getValidatedMethod($method)
{
if ((new static())->isCorrectType($method)) {
return $method;
}
throw new UnknownMethodException($method);
}
/**
* Returns information if result provided by the API is iterable
*
* @param string $method Name of called method while talking to the LimeSurvey's API. One of this class constants.
* @return bool
*/
public static function isResultIterable($method)
{
$method = static::getValidatedMethod($method);
return in_array($method, [
static::LIST_PARTICIPANTS,
static::LIST_QUESTIONS,
static::LIST_SURVEYS,
static::LIST_USERS,
]);
}
}

View File

@@ -0,0 +1,34 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\ApiClient\Type;
use Meritoo\Common\Type\Base\BaseType;
/**
* Type of system-related method used while talking with LimeSurvey's API
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class SystemMethodType extends BaseType
{
/**
* Create and return a session key
*
* @var string
*/
const GET_SESSION_KEY = 'get_session_key';
/**
* Close the RPC session
*
* @var string
*/
const RELEASE_SESSION_KEY = 'release_session_key';
}

View File

@@ -0,0 +1,55 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\Test\ApiClient\Base\Result;
use Meritoo\LimeSurvey\ApiClient\Base\Result\BaseItem;
use PHPUnit_Framework_TestCase;
use ReflectionClass;
/**
* Test case of the base class for one item of result/data fetched while talking to the LimeSurvey's API
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class BaseItemTest extends PHPUnit_Framework_TestCase
{
public function testConstructorVisibilityAndArguments()
{
$reflection = new ReflectionClass(BaseItem::class);
$constructor = $reflection->getConstructor();
static::assertNull($constructor);
}
public function testSetValues()
{
$mock = $this->getBaseItemMock();
static::assertInstanceOf(BaseItem::class, $mock->setValues([]));
static::assertInstanceOf(BaseItem::class, $mock->setValues(['lorem']));
}
/**
* Returns mock of the tested class
*
* @return BaseItem
*/
private function getBaseItemMock()
{
$mock = $this->getMockForAbstractClass(BaseItem::class);
$mock
->expects(static::any())
->method('setValue')
->willReturn(null);
return $mock;
}
}

View File

@@ -0,0 +1,140 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\Test\ApiClient\Client;
use Generator;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
use Meritoo\LimeSurvey\ApiClient\Client\Client;
use Meritoo\LimeSurvey\ApiClient\Configuration\ConnectionConfiguration;
use Meritoo\LimeSurvey\ApiClient\Exception\UnknownMethodException;
use Meritoo\LimeSurvey\ApiClient\Manager\JsonRpcClientManager;
use Meritoo\LimeSurvey\ApiClient\Manager\SessionManager;
use Meritoo\LimeSurvey\ApiClient\Result\Result;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
/**
* Test case of the client of the LimeSurvey's API
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class ClientTest extends BaseTestCase
{
/**
* Configuration used while connecting to LimeSurvey's API
*
* @var ConnectionConfiguration
*/
private $configuration;
/**
* @param string $incorrectMethod Incorrect name of method to call
* @dataProvider provideIncorrectMethod
*/
public function testRunWithIncorrectMethod($incorrectMethod)
{
$this->expectException(UnknownMethodException::class);
$client = new Client($this->configuration);
$client->run($incorrectMethod);
}
/**
* @param string $method Name of method to call
* @param array $arguments Arguments of the method to call
* @param bool $debugMode If is set to true, the "debug" mode is turned on. Otherwise - turned off.
*
* @dataProvider provideMethod
*/
public function testRun($method, $arguments, $debugMode)
{
$sessionManager = $this->createMock(SessionManager::class);
$rpcClientManager = $this->createMock(JsonRpcClientManager::class);
$rpcClientManager
->expects(static::any())
->method('runMethod')
->willReturn([]);
$this->configuration->setDebugMode($debugMode);
$client = new Client($this->configuration, $rpcClientManager, $sessionManager);
static::assertInstanceOf(Result::class, $client->run($method, $arguments));
}
public function testGetRpcClientManagerVisibilityAndArguments()
{
$this->verifyMethodVisibilityAndArguments(Client::class, 'getRpcClientManager', OopVisibilityType::IS_PRIVATE);
}
public function testGetSessionManagerVisibilityAndArguments()
{
$this->verifyMethodVisibilityAndArguments(Client::class, 'getRpcClientManager', OopVisibilityType::IS_PRIVATE);
}
/**
* Provides incorrect name of method
*
* @return Generator
*/
public function provideIncorrectMethod()
{
yield[
'lorem',
];
yield[
'ipsum',
];
yield[
'',
];
}
/**
* Provides correct name of method
*
* @return Generator
*/
public function provideMethod()
{
yield[
MethodType::GET_PARTICIPANT_PROPERTIES,
[],
true,
];
yield[
MethodType::LIST_SURVEYS,
[],
false,
];
yield[
MethodType::LIST_PARTICIPANTS,
[],
false,
];
/*
* todo: Use/Verify other types of methods
*/
}
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->configuration = new ConnectionConfiguration('http://test.com', 'test', 'test');
}
}

View File

@@ -0,0 +1,146 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\Test\ApiClient\Configuration;
use Generator;
use Meritoo\Common\Exception\Regex\InvalidUrlException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\LimeSurvey\ApiClient\Configuration\ConnectionConfiguration;
/**
* Test case of the configuration used while connecting to LimeSurvey's API
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class ConnectionConfigurationTest extends BaseTestCase
{
/**
* @param mixed $emptyBaseUrl Empty base url
* @dataProvider provideEmptyBaseUrl
*/
public function testConstructorWithEmptyBaseUrl($emptyBaseUrl)
{
$this->expectException(InvalidUrlException::class);
new ConnectionConfiguration($emptyBaseUrl, '', '');
}
/**
* @param string $invalidBaseUrl Invalid base url
* @dataProvider provideInvalidBaseUrl
*/
public function testConstructorWithInvalidBaseUrl($invalidBaseUrl)
{
$this->expectException(InvalidUrlException::class);
new ConnectionConfiguration($invalidBaseUrl, '', '');
}
public function testConstructor()
{
$configuration = new ConnectionConfiguration('http://test.com', 'test1', 'test2');
static::assertEquals('http://test.com', $configuration->getBaseUrl());
static::assertEquals('test1', $configuration->getUsername());
static::assertEquals('test2', $configuration->getPassword());
static::assertFalse($configuration->isDebugModeOn());
}
public function testSetBaseUrl()
{
$configuration = new ConnectionConfiguration('http://test.com', 'test1', 'test2');
$configuration->setBaseUrl('http://lorem.ipsum');
static::assertEquals('http://lorem.ipsum', $configuration->getBaseUrl());
$configuration->setBaseUrl('http://lorem.ipsum/');
static::assertEquals('http://lorem.ipsum', $configuration->getBaseUrl());
}
public function testSetRemoteControlUrl()
{
$configuration = new ConnectionConfiguration('http://test.com', 'test1', 'test2');
$configuration->setRemoteControlUrl('/lorem/ipsum');
static::assertEquals('/lorem/ipsum', $configuration->getRemoteControlUrl());
}
public function testSetUsername()
{
$configuration = new ConnectionConfiguration('http://test.com', 'test1', 'test2');
$configuration->setUsername('lorem');
static::assertEquals('lorem', $configuration->getUsername());
}
public function testSetPassword()
{
$configuration = new ConnectionConfiguration('http://test.com', 'test1', 'test2');
$configuration->setPassword('ipsum');
static::assertEquals('ipsum', $configuration->getPassword());
}
public function testSetDebugMode()
{
$configuration = new ConnectionConfiguration('http://test.com', 'test1', 'test2');
$configuration->setDebugMode();
static::assertFalse($configuration->isDebugModeOn());
$configuration->setDebugMode(false);
static::assertFalse($configuration->isDebugModeOn());
$configuration->setDebugMode(true);
static::assertTrue($configuration->isDebugModeOn());
}
public function testGetFullUrl()
{
$configuration = new ConnectionConfiguration('http://test.com', 'test1', 'test2');
$configuration->setRemoteControlUrl('lorem/ipsum');
static::assertEquals('http://test.com/lorem/ipsum', $configuration->getFullUrl());
}
/**
* Provides empty base url
*
* @return Generator
*/
public function provideEmptyBaseUrl()
{
yield[
'',
];
yield[
null,
];
}
/**
* Provides invalid base url
*
* @return Generator
*/
public function provideInvalidBaseUrl()
{
yield[
'lorem',
];
yield[
'ipsum',
];
yield[
'htp:/dolor.com',
];
}
}

View File

@@ -0,0 +1,99 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\Test\ApiClient\Manager;
use JsonRPC\Client as RpcClient;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
use Meritoo\LimeSurvey\ApiClient\Configuration\ConnectionConfiguration;
use Meritoo\LimeSurvey\ApiClient\Manager\JsonRpcClientManager;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
use Meritoo\LimeSurvey\Test\ApiClient\Result\Item\SurveyTest;
/**
* Test case of the manager of the JsonRPC client used while connecting to LimeSurvey's API
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class JsonRpcClientManagerTest extends BaseTestCase
{
/**
* Configuration used while connecting to LimeSurvey's API
*
* @var ConnectionConfiguration
*/
private $configuration;
public function testConstructorVisibilityAndArguments()
{
$this->verifyConstructorVisibilityAndArguments(JsonRpcClientManager::class, OopVisibilityType::IS_PUBLIC, 1, 1);
}
public function testRunMethod()
{
$rpcClient = $this->createMock(RpcClient::class);
$manager = $this
->getMockBuilder(JsonRpcClientManager::class)
->setConstructorArgs([
$this->configuration,
])
->setMethods([
'getRpcClient',
])
->getMock();
$rpcClient
->expects(static::any())
->method('execute')
->willReturn([]);
$manager
->expects(static::any())
->method('getRpcClient')
->willReturn($rpcClient);
/* @var JsonRpcClientManager $manager */
static::assertEquals([], $manager->runMethod(MethodType::LIST_SURVEYS));
}
public function testRunMethodWithMockedRpcClient()
{
$rpcClient = $this->createMock(RpcClient::class);
$manager = $this->createPartialMock(JsonRpcClientManager::class, ['getRpcClient']);
$rpcClient
->expects(static::any())
->method('execute')
->willReturn(SurveyTest::getSurveysRawData());
$manager
->expects(static::any())
->method('getRpcClient')
->willReturn($rpcClient);
/* @var JsonRpcClientManager $manager */
static::assertEquals(SurveyTest::getSurveysRawData(), $manager->runMethod(MethodType::LIST_SURVEYS));
}
public function testGetRpcClientVisibilityAndArguments()
{
$this->verifyMethodVisibilityAndArguments(JsonRpcClientManager::class, 'getRpcClient', OopVisibilityType::IS_PROTECTED);
}
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->configuration = new ConnectionConfiguration('http://test.com', 'test', 'test');
}
}

View File

@@ -0,0 +1,89 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\Test\ApiClient\Manager;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
use Meritoo\LimeSurvey\ApiClient\Exception\CreateSessionKeyFailedException;
use Meritoo\LimeSurvey\ApiClient\Manager\JsonRpcClientManager;
use Meritoo\LimeSurvey\ApiClient\Manager\SessionManager;
/**
* Test case of the manager of session started while connecting to LimeSurvey's API
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class SessionManagerTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
$this->verifyConstructorVisibilityAndArguments(SessionManager::class, OopVisibilityType::IS_PUBLIC, 1, 1);
}
public function testGetSessionKeyWhenFailedWithoutReason()
{
$this->expectException(CreateSessionKeyFailedException::class);
$this->expectExceptionMessage('Create of the session key has failed');
$clientManager = $this->createMock(JsonRpcClientManager::class);
$clientManager
->expects(static::any())
->method('runMethod')
->willReturn([]);
(new SessionManager($clientManager))->getSessionKey('lorem', 'ipsum');
}
public function testGetSessionKeyWhenFailedWithReason()
{
$reason = 'Invalid credentials';
$this->expectException(CreateSessionKeyFailedException::class);
$this->expectExceptionMessage(sprintf('Create of the session key has failed. Reason: \'%s\'.', $reason));
$clientManager = $this->createMock(JsonRpcClientManager::class);
$clientManager
->expects(static::any())
->method('runMethod')
->willReturn([
'status' => $reason,
]);
(new SessionManager($clientManager))->getSessionKey('lorem', 'ipsum');
}
public function testGetSessionKey()
{
$clientManager = $this->createMock(JsonRpcClientManager::class);
$clientManager
->expects(static::any())
->method('runMethod')
->willReturn('12345');
$sessionManager = new SessionManager($clientManager);
static::assertEquals('12345', $sessionManager->getSessionKey('lorem', 'ipsum'));
}
public function testReleaseSessionKey()
{
$clientManager = $this->createMock(JsonRpcClientManager::class);
$clientManager
->expects(static::any())
->method('runMethod')
->willReturn([]);
$sessionManager = new SessionManager($clientManager);
static::assertInstanceOf(SessionManager::class, $sessionManager->releaseSessionKey());
}
}

View File

@@ -0,0 +1,117 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\Test\ApiClient\Result\Item;
use Meritoo\LimeSurvey\ApiClient\Result\Item\ParticipantShort;
use Meritoo\LimeSurvey\ApiClient\Result\Processor\ResultProcessor;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
use PHPUnit_Framework_TestCase;
/**
* Test case of the one item of the result/data: short data of participant
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class ParticipantShortTest extends PHPUnit_Framework_TestCase
{
/**
* Raw data of participants
*
* @var array
*/
private $rawData;
/**
* 1st instance of the participant created using the raw data
*
* @var ParticipantShort
*/
private $participant1stInstance;
/**
* 2nd instance of the participant created using the raw data
*
* @var ParticipantShort
*/
private $participant2ndInstance;
public function testCreateOfTheParticipant()
{
$processor = new ResultProcessor();
$processed = $processor->process(MethodType::LIST_PARTICIPANTS, $this->rawData);
static::assertCount(2, $processed);
}
public function testGetId()
{
static::assertEquals(123, $this->participant1stInstance->getId());
static::assertEquals(456, $this->participant2ndInstance->getId());
}
public function testGetFirstName()
{
static::assertEquals('Lorem', $this->participant1stInstance->getFirstName());
static::assertEquals('Dolor', $this->participant2ndInstance->getFirstName());
}
public function testGetLastName()
{
static::assertEquals('Ipsum', $this->participant1stInstance->getLastName());
static::assertEquals('Sit', $this->participant2ndInstance->getLastName());
}
public function testGetEmail()
{
static::assertEquals('lorem@ipsum.com', $this->participant1stInstance->getEmail());
static::assertEquals('dolor@sit.com', $this->participant2ndInstance->getEmail());
}
/**
* Returns raw data of participants
*
* @return array
*/
public static function getParticipantsRawData()
{
return [
[
'tid' => '123',
'token' => uniqid(),
'participant_info' => [
'firstname' => 'Lorem',
'lastname' => 'Ipsum',
'email' => 'lorem@ipsum.com',
],
],
[
'tid' => '456',
'token' => uniqid(),
'participant_info' => [
'firstname' => 'Dolor',
'lastname' => 'Sit',
'email' => 'dolor@sit.com',
],
],
];
}
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->rawData = static::getParticipantsRawData();
$this->participant1stInstance = (new ParticipantShort())->setValues($this->rawData[0]);
$this->participant2ndInstance = (new ParticipantShort())->setValues($this->rawData[1]);
}
}

View File

@@ -0,0 +1,216 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\Test\ApiClient\Result\Item;
use DateTime;
use Meritoo\LimeSurvey\ApiClient\Result\Item\Participant;
use Meritoo\LimeSurvey\ApiClient\Result\Processor\ResultProcessor;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
use PHPUnit_Framework_TestCase;
/**
* Test case of the one item of the result/data: full data of participant
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class ParticipantTest extends PHPUnit_Framework_TestCase
{
/**
* Raw data of participants
*
* @var array
*/
private $rawData;
/**
* 1st instance of the participant created using the raw data
*
* @var Participant
*/
private $participant1stInstance;
/**
* 2nd instance of the participant created using the raw data
*
* @var Participant
*/
private $participant2ndInstance;
public function testCreateOfTheParticipant()
{
$processor = new ResultProcessor();
$processed = $processor->process(MethodType::GET_PARTICIPANT_PROPERTIES, $this->rawData[0]);
static::assertInstanceOf(Participant::class, $processed);
}
public function testGetId()
{
static::assertEquals(123, $this->participant1stInstance->getId());
static::assertEquals(456, $this->participant2ndInstance->getId());
}
public function testGetParticipantId()
{
static::assertEquals(0, $this->participant1stInstance->getParticipantId());
static::assertEquals(789, $this->participant2ndInstance->getParticipantId());
}
public function testGetMpId()
{
static::assertEquals(0, $this->participant1stInstance->getMpId());
static::assertEquals(1, $this->participant2ndInstance->getMpId());
}
public function testGetFirstName()
{
static::assertEquals('Lorem', $this->participant1stInstance->getFirstName());
static::assertEquals('Dolor', $this->participant2ndInstance->getFirstName());
}
public function testGetLastName()
{
static::assertEquals('Ipsum', $this->participant1stInstance->getLastName());
static::assertEquals('Sit', $this->participant2ndInstance->getLastName());
}
public function testGetEmail()
{
static::assertEquals('lorem@ipsum.com', $this->participant1stInstance->getEmail());
static::assertEquals('dolor@sit.com', $this->participant2ndInstance->getEmail());
}
public function testGetEmailStatus()
{
static::assertEquals('OK', $this->participant1stInstance->getEmailStatus());
static::assertEquals('OK', $this->participant2ndInstance->getEmailStatus());
}
public function testGetToken()
{
static::assertEquals($this->rawData[0]['token'], $this->participant1stInstance->getToken());
static::assertEquals($this->rawData[1]['token'], $this->participant2ndInstance->getToken());
}
public function testGetLanguage()
{
static::assertEquals('pl', $this->participant1stInstance->getLanguage());
static::assertEquals('en', $this->participant2ndInstance->getLanguage());
}
public function testIsBlacklisted()
{
static::assertFalse($this->participant1stInstance->isBlacklisted());
static::assertTrue($this->participant2ndInstance->isBlacklisted());
}
public function testIsSent()
{
static::assertTrue($this->participant1stInstance->isSent());
static::assertTrue($this->participant2ndInstance->isSent());
}
public function testIsReminderSent()
{
static::assertFalse($this->participant1stInstance->isReminderSent());
static::assertFalse($this->participant2ndInstance->isReminderSent());
}
public function testGetReminderCount()
{
static::assertEquals(0, $this->participant1stInstance->getReminderCount());
static::assertEquals(1, $this->participant2ndInstance->getReminderCount());
}
public function testIsCompleted()
{
static::assertFalse($this->participant1stInstance->isCompleted());
static::assertTrue($this->participant2ndInstance->isCompleted());
}
public function testGetUsesLeft()
{
static::assertEquals(10, $this->participant1stInstance->getUsesLeft());
static::assertEquals(5, $this->participant2ndInstance->getUsesLeft());
}
public function testGetValidFrom()
{
static::assertNull($this->participant1stInstance->getValidFrom());
static::assertEquals(new DateTime($this->rawData[1]['validfrom']), $this->participant2ndInstance->getValidFrom());
}
public function testGetValidUntil()
{
static::assertEquals(new DateTime($this->rawData[0]['validuntil']), $this->participant1stInstance->getValidUntil());
static::assertNull($this->participant2ndInstance->getValidUntil());
}
/**
* Returns raw data of participants
*
* @return array
*/
public static function getParticipantsRawData()
{
return [
[
'tid' => '123',
'participant_id' => null,
'mpid' => null,
'firstname' => 'Lorem',
'lastname' => 'Ipsum',
'email' => 'lorem@ipsum.com',
'emailstatus' => 'OK',
'token' => uniqid(),
'language' => 'pl',
'blacklisted' => 'N',
'sent' => 'Y',
'remindersent' => 'N',
'remindercount' => 0,
'completed' => 'N',
'usesleft' => 10,
'validfrom' => null,
'validuntil' => (new DateTime())->format('Y-m-d H:i:s'),
],
[
'tid' => '456',
'participant_id' => '789',
'mpid' => '001',
'firstname' => 'Dolor',
'lastname' => 'Sit',
'email' => 'dolor@sit.com',
'emailstatus' => 'OK',
'token' => uniqid(),
'language' => 'en',
'blacklisted' => 'Y',
'sent' => 'Y',
'remindersent' => 'N',
'remindercount' => 1,
'completed' => 'Y',
'usesleft' => 5,
'validfrom' => (new DateTime())->format('Y-m-d H:i:s'),
'validuntil' => null,
],
];
}
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->rawData = static::getParticipantsRawData();
$this->participant1stInstance = (new Participant())->setValues($this->rawData[0]);
$this->participant2ndInstance = (new Participant())->setValues($this->rawData[1]);
}
}

View File

@@ -0,0 +1,223 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\Test\ApiClient\Result\Item;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\LimeSurvey\ApiClient\Result\Item\QuestionShort;
use Meritoo\LimeSurvey\ApiClient\Result\Processor\ResultProcessor;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
/**
* Test case of the one item of the result/data: short data of one question of survey
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class QuestionShortTest extends BaseTestCase
{
/**
* Raw data of questions
*
* @var array
*/
private $rawData;
/**
* 1st instance of the question created using the raw data
*
* @var QuestionShort
*/
private $question1stInstance;
/**
* 2nd instance of the question created using the raw data
*
* @var QuestionShort
*/
private $question2ndInstance;
public function testCreateOfTheQuestionShort()
{
$processor = new ResultProcessor();
$processed = $processor->process(MethodType::LIST_QUESTIONS, $this->rawData);
static::assertCount(2, $processed);
}
public function testGetId()
{
static::assertEquals(123, $this->question1stInstance->getId());
static::assertEquals(456, $this->question2ndInstance->getId());
}
public function testGetParentId()
{
static::assertEquals(0, $this->question1stInstance->getParentId());
static::assertEquals(789, $this->question2ndInstance->getParentId());
}
public function testGetSurveyId()
{
static::assertEquals(0, $this->question1stInstance->getSurveyId());
static::assertEquals(1020, $this->question2ndInstance->getSurveyId());
}
public function testGetGroupId()
{
static::assertEquals(0, $this->question1stInstance->getGroupId());
static::assertEquals(3040, $this->question2ndInstance->getGroupId());
}
public function testGetScaleId()
{
static::assertEquals(0, $this->question1stInstance->getScaleId());
static::assertEquals(5060, $this->question2ndInstance->getScaleId());
}
public function testGetType()
{
static::assertEquals('T', $this->question1stInstance->getType());
static::assertEquals('N', $this->question2ndInstance->getType());
}
public function testGetTitle()
{
static::assertEquals('Test', $this->question1stInstance->getTitle());
static::assertEquals('Another Test', $this->question2ndInstance->getTitle());
}
public function testGetContent()
{
static::assertEquals('Donec ullamcorper nulla non metus auctor fringilla?', $this->question1stInstance->getContent());
static::assertEquals('Maecenas sed diam eget risus varius blandit sit amet non magna?', $this->question2ndInstance->getContent());
}
public function testGetContentHelp()
{
static::assertEquals('Maecenas sed diam eget risus varius blandit sit amet non magna.', $this->question1stInstance->getContentHelp());
static::assertEquals('Donec id elit non mi porta gravida at eget metus.', $this->question2ndInstance->getContentHelp());
}
public function testGetRegularExpression()
{
static::assertNull($this->question1stInstance->getRegularExpression());
static::assertEquals('\d+', $this->question2ndInstance->getRegularExpression());
}
public function testIsOther()
{
static::assertFalse($this->question1stInstance->isOther());
static::assertFalse($this->question2ndInstance->isOther());
}
public function testIsMandatory()
{
static::assertTrue($this->question1stInstance->isMandatory());
static::assertTrue($this->question2ndInstance->isMandatory());
}
public function testGetPosition()
{
static::assertEquals(1, $this->question1stInstance->getPosition());
static::assertEquals(2, $this->question2ndInstance->getPosition());
}
public function testGetLanguage()
{
static::assertEquals('pl', $this->question1stInstance->getLanguage());
static::assertEquals('pl', $this->question2ndInstance->getLanguage());
}
public function testGetSameDefault()
{
static::assertEquals(0, $this->question1stInstance->getSameDefault());
static::assertEquals(0, $this->question2ndInstance->getSameDefault());
}
public function testGetRelevance()
{
static::assertEquals('', $this->question1stInstance->getRelevance());
static::assertEquals('1', $this->question2ndInstance->getRelevance());
}
public function testGetModuleName()
{
static::assertNull($this->question1stInstance->getModuleName());
static::assertEquals('HR', $this->question2ndInstance->getModuleName());
}
/**
* Returns raw data of questions
*
* @return array
*/
public static function getQuestionsRawData()
{
return [
[
'id' => [
'qid' => '123',
'language' => 'pl',
],
'qid' => '123',
'parent_qid' => null,
'sid' => null,
'gid' => null,
'scale_id' => null,
'type' => 'T',
'title' => 'Test',
'question' => 'Donec ullamcorper nulla non metus auctor fringilla?',
'help' => 'Maecenas sed diam eget risus varius blandit sit amet non magna.',
'preg' => null,
'other' => 'N',
'mandatory' => 'Y',
'question_order' => '1',
'language' => 'pl',
'same_default' => '0',
'relevance' => null,
'modulename' => null,
],
[
'id' => [
'qid' => '456',
'language' => 'pl',
],
'qid' => '456',
'parent_qid' => '789',
'sid' => '1020',
'gid' => '3040',
'scale_id' => '5060',
'type' => 'N',
'title' => 'Another Test',
'question' => 'Maecenas sed diam eget risus varius blandit sit amet non magna?',
'help' => 'Donec id elit non mi porta gravida at eget metus.',
'preg' => '\d+',
'other' => 'N',
'mandatory' => 'Y',
'question_order' => '2',
'language' => 'pl',
'same_default' => '0',
'relevance' => '1',
'modulename' => 'HR',
],
];
}
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->rawData = static::getQuestionsRawData();
$this->question1stInstance = (new QuestionShort())->setValues($this->rawData[0]);
$this->question2ndInstance = (new QuestionShort())->setValues($this->rawData[1]);
}
}

View File

@@ -0,0 +1,285 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\Test\ApiClient\Result\Item;
use Meritoo\LimeSurvey\ApiClient\Result\Item\Question;
use Meritoo\LimeSurvey\ApiClient\Result\Processor\ResultProcessor;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
use PHPUnit_Framework_TestCase;
/**
* Test case of the one item of the result/data: full data of one question of survey
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class QuestionTest extends PHPUnit_Framework_TestCase
{
/**
* Raw data of questions
*
* @var array
*/
private $rawData;
/**
* 1st instance of the question created using the raw data
*
* @var Question
*/
private $question1stInstance;
/**
* 2nd instance of the question created using the raw data
*
* @var Question
*/
private $question2ndInstance;
public function testCreateOfTheQuestionShort()
{
$processor = new ResultProcessor();
$processed = $processor->process(MethodType::GET_QUESTION_PROPERTIES, $this->rawData);
static::assertInstanceOf(Question::class, $processed);
}
public function testGetId()
{
static::assertEquals(123, $this->question1stInstance->getId());
static::assertEquals(456, $this->question2ndInstance->getId());
}
public function testGetParentId()
{
static::assertEquals(0, $this->question1stInstance->getParentId());
static::assertEquals(789, $this->question2ndInstance->getParentId());
}
public function testGetSurveyId()
{
static::assertEquals(0, $this->question1stInstance->getSurveyId());
static::assertEquals(1020, $this->question2ndInstance->getSurveyId());
}
public function testGetGroupId()
{
static::assertEquals(0, $this->question1stInstance->getGroupId());
static::assertEquals(3040, $this->question2ndInstance->getGroupId());
}
public function testGetScaleId()
{
static::assertEquals(0, $this->question1stInstance->getScaleId());
static::assertEquals(5060, $this->question2ndInstance->getScaleId());
}
public function testGetType()
{
static::assertEquals('T', $this->question1stInstance->getType());
static::assertEquals('M', $this->question2ndInstance->getType());
}
public function testGetTitle()
{
static::assertEquals('Test', $this->question1stInstance->getTitle());
static::assertEquals('Another Test', $this->question2ndInstance->getTitle());
}
public function testGetContent()
{
static::assertEquals('Donec ullamcorper nulla non metus auctor fringilla?', $this->question1stInstance->getContent());
static::assertEquals('Maecenas sed diam eget risus varius blandit sit amet non magna?', $this->question2ndInstance->getContent());
}
public function testGetContentHelp()
{
static::assertEquals('Maecenas sed diam eget risus varius blandit sit amet non magna.', $this->question1stInstance->getContentHelp());
static::assertEquals('Donec id elit non mi porta gravida at eget metus.', $this->question2ndInstance->getContentHelp());
}
public function testGetRegularExpression()
{
static::assertNull($this->question1stInstance->getRegularExpression());
static::assertEquals('\d+', $this->question2ndInstance->getRegularExpression());
}
public function testIsOther()
{
static::assertFalse($this->question1stInstance->isOther());
static::assertFalse($this->question2ndInstance->isOther());
}
public function testIsMandatory()
{
static::assertTrue($this->question1stInstance->isMandatory());
static::assertTrue($this->question2ndInstance->isMandatory());
}
public function testGetPosition()
{
static::assertEquals(1, $this->question1stInstance->getPosition());
static::assertEquals(2, $this->question2ndInstance->getPosition());
}
public function testGetLanguage()
{
static::assertEquals('pl', $this->question1stInstance->getLanguage());
static::assertEquals('pl', $this->question2ndInstance->getLanguage());
}
public function testGetSameDefault()
{
static::assertEquals(0, $this->question1stInstance->getSameDefault());
static::assertEquals(0, $this->question2ndInstance->getSameDefault());
}
public function testGetRelevance()
{
static::assertEquals('', $this->question1stInstance->getRelevance());
static::assertEquals('1', $this->question2ndInstance->getRelevance());
}
public function testGetModuleName()
{
static::assertNull($this->question1stInstance->getModuleName());
static::assertEquals('HR', $this->question2ndInstance->getModuleName());
}
public function testGetAvailableAnswers()
{
static::assertEquals('No available answers', $this->question1stInstance->getAvailableAnswers());
static::assertEquals($this->rawData[1]['available_answers'], $this->question2ndInstance->getAvailableAnswers());
}
public function testGetSubQuestions()
{
static::assertEquals('No available subquestions', $this->question1stInstance->getSubQuestions());
static::assertEquals($this->rawData[1]['subquestions'], $this->question2ndInstance->getSubQuestions());
}
public function testGetAttributes()
{
static::assertEquals('No available attributes', $this->question1stInstance->getAttributes());
static::assertEquals('No available attributes', $this->question2ndInstance->getAttributes());
}
public function testGetAttributesLanguages()
{
static::assertEquals('No available attributes', $this->question1stInstance->getAttributesLanguages());
static::assertEquals('No available attributes', $this->question2ndInstance->getAttributesLanguages());
}
public function testGetAnswerOptions()
{
static::assertEquals('No available answer options', $this->question1stInstance->getAnswerOptions());
static::assertEquals('No available answer options', $this->question2ndInstance->getAnswerOptions());
}
public function testGetDefaultValue()
{
static::assertNull($this->question1stInstance->getDefaultValue());
static::assertNull($this->question2ndInstance->getDefaultValue());
}
/**
* Returns raw data of questions
*
* @return array
*/
public static function getQuestionsRawData()
{
return [
[
'id' => [
'qid' => '123',
'language' => 'pl',
],
'qid' => '123',
'parent_qid' => null,
'sid' => null,
'gid' => null,
'scale_id' => null,
'type' => 'T',
'title' => 'Test',
'question' => 'Donec ullamcorper nulla non metus auctor fringilla?',
'help' => 'Maecenas sed diam eget risus varius blandit sit amet non magna.',
'preg' => null,
'other' => 'N',
'mandatory' => 'Y',
'question_order' => '1',
'language' => 'pl',
'same_default' => '0',
'relevance' => null,
'modulename' => null,
'available_answers' => 'No available answers',
'subquestions' => 'No available subquestions',
'attributes' => 'No available attributes',
'attributes_lang' => 'No available attributes',
'answeroptions' => 'No available answer options',
'defaultvalue' => null,
],
[
'id' => [
'qid' => '456',
'language' => 'pl',
],
'qid' => '456',
'parent_qid' => '789',
'sid' => '1020',
'gid' => '3040',
'scale_id' => '5060',
'type' => 'M',
'title' => 'Another Test',
'question' => 'Maecenas sed diam eget risus varius blandit sit amet non magna?',
'help' => 'Donec id elit non mi porta gravida at eget metus.',
'preg' => '\d+',
'other' => 'N',
'mandatory' => 'Y',
'question_order' => '2',
'language' => 'pl',
'same_default' => '0',
'relevance' => '1',
'modulename' => 'HR',
'available_answers' => [
'SQ001' => 'Sed posuere consectetur est at lobortis?',
'SQ002' => 'Cum sociis natoque penatibus et magnis?',
],
'subquestions' => [
1 => [
'title' => 'SQ001',
'question' => 'Cum sociis natoque penatibus et magnis?',
'scale_id' => '0',
],
2 => [
'title' => 'SQ002',
'question' => 'Sed posuere consectetur est at lobortis?',
'scale_id' => '0',
],
],
'attributes' => 'No available attributes',
'attributes_lang' => 'No available attributes',
'answeroptions' => 'No available answer options',
'defaultvalue' => null,
],
];
}
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->rawData = static::getQuestionsRawData();
$this->question1stInstance = (new Question())->setValues($this->rawData[0]);
$this->question2ndInstance = (new Question())->setValues($this->rawData[1]);
}
}

View File

@@ -0,0 +1,120 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\Test\ApiClient\Result\Item;
use DateTime;
use Meritoo\LimeSurvey\ApiClient\Result\Item\Survey;
use Meritoo\LimeSurvey\ApiClient\Result\Processor\ResultProcessor;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
use PHPUnit_Framework_TestCase;
/**
* Test case of the one item of the result/data: survey
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class SurveyTest extends PHPUnit_Framework_TestCase
{
/**
* Raw data of surveys
*
* @var array
*/
private $rawData;
/**
* 1st instance of the survey created using the raw data
*
* @var Survey
*/
private $survey1stInstance;
/**
* 2nd instance of the survey created using the raw data
*
* @var Survey
*/
private $survey2ndInstance;
public function testCreateOfTheSurvey()
{
$processor = new ResultProcessor();
$processed = $processor->process(MethodType::LIST_SURVEYS, $this->rawData);
static::assertCount(2, $processed);
}
public function testGetId()
{
static::assertEquals(123, $this->survey1stInstance->getId());
static::assertEquals(456, $this->survey2ndInstance->getId());
}
public function testGetTitle()
{
static::assertEquals('Test', $this->survey1stInstance->getTitle());
static::assertEquals('Another Test', $this->survey2ndInstance->getTitle());
}
public function testGetStartsAt()
{
static::assertNull($this->survey1stInstance->getStartsAt());
static::assertEquals(new DateTime($this->rawData[1]['startdate']), $this->survey2ndInstance->getStartsAt());
}
public function testGetExpiresAt()
{
static::assertEquals(new DateTime($this->rawData[0]['expires']), $this->survey1stInstance->getExpiresAt());
static::assertNull($this->survey2ndInstance->getExpiresAt());
}
public function testIsActive()
{
static::assertFalse($this->survey1stInstance->isActive());
static::assertTrue($this->survey2ndInstance->isActive());
}
/**
* Returns raw data of surveys
*
* @return array
*/
public static function getSurveysRawData()
{
return [
[
'sid' => '123',
'surveyls_title' => 'Test',
'startdate' => null,
'expires' => (new DateTime())->format('Y-m-d H:i:s'),
'active' => 'N',
],
[
'sid' => '456',
'surveyls_title' => 'Another Test',
'startdate' => (new DateTime())->format('Y-m-d H:i:s'),
'expires' => null,
'active' => 'Y',
],
];
}
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->rawData = static::getSurveysRawData();
$this->survey1stInstance = (new Survey())->setValues($this->rawData[0]);
$this->survey2ndInstance = (new Survey())->setValues($this->rawData[1]);
}
}

View File

@@ -0,0 +1,86 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\Test\ApiClient\Result\Processor;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
use Meritoo\LimeSurvey\ApiClient\Base\Result\BaseItem;
use Meritoo\LimeSurvey\ApiClient\Exception\UnknownInstanceOfResultItem;
use Meritoo\LimeSurvey\ApiClient\Result\Processor\ResultProcessor;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
use Meritoo\LimeSurvey\Test\ApiClient\Result\Item\SurveyTest;
use ReflectionClass;
/**
* Test case of the processor of the raw data fetched while talking to the LimeSurvey's API
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class ResultProcessorTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
$reflection = new ReflectionClass(ResultProcessor::class);
$constructor = $reflection->getConstructor();
static::assertNull($constructor);
}
public function testProcessWithEmptyRawData()
{
$rawData = [];
$processor = new ResultProcessor();
static::assertNull($processor->process(MethodType::LIST_SURVEYS, $rawData));
}
public function testProcessWithIterableData()
{
$processor = new ResultProcessor();
$processed = $processor->process(MethodType::LIST_SURVEYS, SurveyTest::getSurveysRawData());
static::assertNotEmpty($processed);
static::assertTrue(is_array($processed));
static::assertCount(2, $processed);
}
public function testProcessWithNotIterableData()
{
$rawData = [
'lorem' => 'ipsum',
'dolor' => 'sit',
];
$processor = new ResultProcessor();
$processed = $processor->process(MethodType::GET_PARTICIPANT_PROPERTIES, $rawData);
static::assertNotEmpty($processed);
static::assertFalse(is_array($processed));
static::assertInstanceOf(BaseItem::class, $processed);
}
public function testGetItemInstanceVisibilityAndArguments()
{
$this->verifyMethodVisibilityAndArguments(ResultProcessor::class, 'getItemInstance', OopVisibilityType::IS_PRIVATE, 1, 1);
}
public function testRunWithUnknownResultClass()
{
$this->expectException(UnknownInstanceOfResultItem::class);
$rawData = [
'lorem' => 'ipsum',
'dolor' => 'sit',
];
$processor = new ResultProcessor();
$processor->process(MethodType::LIST_USERS, $rawData);
}
}

View File

@@ -0,0 +1,182 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\Test\ApiClient\Result\Result;
use DateTime;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
use Meritoo\LimeSurvey\ApiClient\Base\Result\BaseItem;
use Meritoo\LimeSurvey\ApiClient\Result\Result;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
use PHPUnit_Framework_MockObject_MockObject;
/**
* Test case of the result with data fetched while talking to the LimeSurvey's API
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class ResultTest extends BaseTestCase
{
/**
* Empty data returned by the LimeSurvey's API
*
* @var array
*/
private $emptyData;
/**
* Iterable, not empty data returned by the LimeSurvey's API
*
* @var array
*/
private $iterableData;
/**
* Not iterable, not empty data returned by the LimeSurvey's API
*
* @var array
*/
private $notIterableData;
/**
* Mock of the tested class.
* With empty data returned by the LimeSurvey's API.
*
* @var PHPUnit_Framework_MockObject_MockObject
*/
private $emptyDataMock;
/**
* Mock of the tested class.
* With iterable, not empty data.
*
* @var PHPUnit_Framework_MockObject_MockObject
*/
private $iterableDataMock;
/**
* Mock of the tested class.
* With not iterable, not empty data.
*
* @var PHPUnit_Framework_MockObject_MockObject
*/
private $notIterableDataMock;
public function testConstructorVisibilityAndArguments()
{
$this->verifyConstructorVisibilityAndArguments(Result::class, OopVisibilityType::IS_PUBLIC, 2, 2);
}
public function testIsEmpty()
{
static::assertTrue($this->emptyDataMock->isEmpty());
static::assertFalse($this->iterableDataMock->isEmpty());
}
public function testGetDataUsingProcessedData()
{
$emptyData = $this->emptyDataMock->getData();
$iterableData = $this->iterableDataMock->getData();
$notIterableData = $this->notIterableDataMock->getData();
static::assertEmpty($emptyData);
static::assertNotEmpty($iterableData);
static::assertNotEmpty($notIterableData);
static::assertCount(count($this->emptyData), $emptyData);
static::assertCount(count($this->iterableData), $iterableData);
static::assertInstanceOf(BaseItem::class, $notIterableData);
}
public function testGetDataUsingRawData()
{
$emptyData = $this->emptyDataMock->getData(true);
$iterableData = $this->iterableDataMock->getData(true);
static::assertEmpty($emptyData);
static::assertNotEmpty($iterableData);
static::assertCount(count($this->emptyData), $emptyData);
static::assertCount(count($this->iterableData), $iterableData);
static::assertEquals($this->emptyData, $emptyData);
static::assertEquals($this->iterableData, $iterableData);
}
public function testGetProcessedDataVisibilityAndArguments()
{
$this->verifyMethodVisibilityAndArguments(Result::class, 'getProcessedData', OopVisibilityType::IS_PRIVATE, 1, 1);
}
public function testGetResultProcessorVisibilityAndArguments()
{
$this->verifyMethodVisibilityAndArguments(Result::class, 'getResultProcessor', OopVisibilityType::IS_PRIVATE);
}
/**
* {@inheritdoc{
*/
protected function setUp()
{
parent::setUp();
$this->emptyData = [];
$this->notIterableData = [
'result' => base64_encode('lorem-ipsum'),
];
$this->iterableData = [
[
'sid' => '123',
'surveyls_title' => 'Test',
'startdate' => null,
'expires' => null,
'active' => 'N',
],
[
'sid' => '456',
'surveyls_title' => 'Another Test',
'startdate' => (new DateTime())->format('Y-m-d H:i:s'),
'expires' => null,
'active' => 'Y',
],
];
$emptyDataArguments = [
MethodType::LIST_SURVEYS,
$this->emptyData,
];
$iterableDataArguments = [
MethodType::LIST_SURVEYS,
$this->iterableData,
];
$notIterableDataArguments = [
MethodType::GET_PARTICIPANT_PROPERTIES,
$this->notIterableData,
];
$this->emptyDataMock = $this->getResultMock($emptyDataArguments);
$this->iterableDataMock = $this->getResultMock($iterableDataArguments);
$this->notIterableDataMock = $this->getResultMock($notIterableDataArguments);
}
/**
* Returns mock of the tested class
*
* @param array $constructorArguments Arguments of constructor for prepared mock
* @return Result
*/
private function getResultMock($constructorArguments)
{
return $this->getMockForAbstractClass(Result::class, $constructorArguments);
}
}

View File

@@ -0,0 +1,204 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\Test\ApiClient\Type;
use Generator;
use Meritoo\Common\Test\Base\BaseTypeTestCase;
use Meritoo\LimeSurvey\ApiClient\Exception\UnknownMethodException;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
/**
* Test case of the type of method used while talking with LimeSurvey's API
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class MethodTypeTest extends BaseTypeTestCase
{
/**
* @param string $incorrectMethod Type of method to verify
* @dataProvider provideIncorrectMethod
*/
public function testGetValidatedMethodWithIncorrectMethod($incorrectMethod)
{
$this->expectException(UnknownMethodException::class);
MethodType::getValidatedMethod($incorrectMethod);
}
/**
* @param string $method Type of method to verify
* @dataProvider provideMethod
*/
public function testGetValidatedMethod($method)
{
static::assertEquals($method, MethodType::getValidatedMethod($method));
}
/**
* @param string $incorrectMethod Type of incorrectMethod to verify
* @dataProvider provideIncorrectMethod
*/
public function testIsResultIterableWithIncorrectMethod($incorrectMethod)
{
$this->expectException(UnknownMethodException::class);
MethodType::isResultIterable($incorrectMethod);
}
/**
* @param string $method Type of method to verify
* @param bool $expected Information if result provided by the API is iterable
*
* @dataProvider provideIterableType
*/
public function testIsResultIterable($method, $expected)
{
static::assertEquals($expected, MethodType::isResultIterable($method));
}
/**
* Provides correct type of method
*
* @return Generator
*/
public function provideMethod()
{
yield[
MethodType::ADD_RESPONSE,
];
yield[
MethodType::EXPORT_STATISTICS,
];
yield[
MethodType::GET_PARTICIPANT_PROPERTIES,
];
yield[
MethodType::LIST_SURVEYS,
];
}
/**
* Provides incorrect type of method
*
* @return Generator
*/
public function provideIncorrectMethod()
{
yield[
'',
];
yield[
null,
];
yield[
true,
];
yield[
false,
];
yield[
'lorem',
];
}
/**
* Provides type of method who result provided by the API is iterable and information if it's iterable
*
* @return Generator
*/
public function provideIterableType()
{
yield[
MethodType::ADD_RESPONSE,
false,
];
yield[
MethodType::GET_PARTICIPANT_PROPERTIES,
false,
];
yield[
MethodType::LIST_PARTICIPANTS,
true,
];
yield[
MethodType::LIST_QUESTIONS,
true,
];
yield[
MethodType::LIST_SURVEYS,
true,
];
yield[
MethodType::LIST_USERS,
true,
];
}
/**
* {@inheritdoc}
*/
protected function getAllExpectedTypes()
{
return [
'ADD_RESPONSE' => MethodType::ADD_RESPONSE,
'EXPORT_STATISTICS' => MethodType::EXPORT_STATISTICS,
'GET_PARTICIPANT_PROPERTIES' => MethodType::GET_PARTICIPANT_PROPERTIES,
'GET_QUESTION_PROPERTIES' => MethodType::GET_QUESTION_PROPERTIES,
'LIST_PARTICIPANTS' => MethodType::LIST_PARTICIPANTS,
'LIST_QUESTIONS' => MethodType::LIST_QUESTIONS,
'LIST_SURVEYS' => MethodType::LIST_SURVEYS,
'LIST_USERS' => MethodType::LIST_USERS,
];
}
/**
* {@inheritdoc}
*/
protected function getTestedTypeInstance()
{
return new MethodType();
}
/**
* {@inheritdoc}
*/
public function provideTypeToVerify()
{
yield[
'',
false,
];
yield[
'lorem',
false,
];
yield[
MethodType::ADD_RESPONSE,
true,
];
yield[
MethodType::GET_PARTICIPANT_PROPERTIES,
true,
];
}
}

View File

@@ -0,0 +1,66 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\LimeSurvey\Test\ApiClient\Type;
use Meritoo\Common\Test\Base\BaseTypeTestCase;
use Meritoo\LimeSurvey\ApiClient\Type\SystemMethodType;
/**
* Test case of the type of system-related method used while talking with LimeSurvey's API
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class SystemMethodTypeTest extends BaseTypeTestCase
{
/**
* {@inheritdoc}
*/
protected function getAllExpectedTypes()
{
return [
'GET_SESSION_KEY' => SystemMethodType::GET_SESSION_KEY,
'RELEASE_SESSION_KEY' => SystemMethodType::RELEASE_SESSION_KEY,
];
}
/**
* {@inheritdoc}
*/
protected function getTestedTypeInstance()
{
return new SystemMethodType();
}
/**
* {@inheritdoc}
*/
public function provideTypeToVerify()
{
yield[
'',
false,
];
yield[
'lorem',
false,
];
yield[
SystemMethodType::GET_SESSION_KEY,
true,
];
yield[
SystemMethodType::RELEASE_SESSION_KEY,
true,
];
}
}