Support PHP 5.4

This commit is contained in:
Meritoo
2017-10-19 22:00:09 +02:00
parent 835c4325b8
commit bdbaebb5c0
81 changed files with 7268 additions and 135 deletions

View File

@@ -0,0 +1,64 @@
<?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
{
const className = 'Meritoo\LimeSurvey\ApiClient\Base\Result\BaseItem';
/**
* Class constructor
*
* @param array $data (optional) Data to set in properties of the item
*/
public function __construct(array $data = [])
{
$this->setValues($data);
}
/**
* 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);
/**
* Sets values in each property of the item
*
* @param array $data Data to set in properties of the item
* @return $this
*/
private function setValues(array $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;
}
}

View File

@@ -0,0 +1,162 @@
<?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
{
const className = 'Meritoo\LimeSurvey\ApiClient\Client\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.
* It's called in the JsonRpcClientManager::runMethod() too, but I want to verify it before getting session key.
*/
$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 one 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);
/*
* Raw data is unknown?
* Let's use an empty array instead
*
* Required to avoid bug:
* Argument 2 passed to Meritoo\LimeSurvey\ApiClient\Result\Result::__construct() must be of the type array,
* null given
*/
if (null === $rawData) {
$rawData = [];
}
return new Result($method, $rawData);
}
/**
* Returns configuration used while connecting to LimeSurvey's API
*
* @return ConnectionConfiguration
*/
public function getConfiguration()
{
return $this->configuration;
}
/**
* 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,199 @@
<?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
{
const className = 'Meritoo\LimeSurvey\ApiClient\Configuration\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;
/**
* If is set to true, the SSL certificate verification is turned on. Otherwise - turned off.
* It's useful while running application with custom, non-official SSL certificate, e.g. while development process.
*
* @var bool
*/
private $verifySslCertificate = true;
/**
* 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.
* @param bool $verifySslCertificate (optional) If is set to true, the SSL certificate verification is turned
* on. Otherwise - turned off.
*/
public function __construct($baseUrl, $username, $password, $debugMode = false, $verifySslCertificate = true)
{
$this->setBaseUrl($baseUrl);
$this->username = $username;
$this->password = $password;
$this->debugMode = $debugMode;
$this->verifySslCertificate = $verifySslCertificate;
}
/**
* Returns the base url, protocol & domain
*
* @return string
*/
public function getBaseUrl()
{
return $this->baseUrl;
}
/**
* 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;
}
/**
* Returns the password used to authenticate to LimeSurvey
*
* @return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Returns information if the "debug" mode is turned on
*
* @return bool
*/
public function isDebugModeOn()
{
return $this->debugMode;
}
/**
* Returns information if the SSL certificate verification is turned on
*
* @return bool
*/
public function isVerifySslCertificateOn()
{
return $this->verifySslCertificate;
}
/**
* 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);
}
/**
* Sets the base url, protocol & domain
*
* @param string $baseUrl The base url, protocol & domain
* @return $this
*
* @throws InvalidUrlException
*/
private 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;
}
}

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\Exception;
/**
* An exception used while raw data returned by the LimeSurvey's API cannot be processed
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class CannotProcessDataException extends \Exception
{
const className = 'Meritoo\LimeSurvey\ApiClient\Exception\CannotProcessDataException';
/**
* Reason why data cannot be processed, e.g. "Invalid user name or password"
*
* @var string
*/
private $reason;
/**
* Class constructor
*
* @param string $reason Reason why data cannot be processed, e.g. "Invalid user name or password"
*/
public function __construct($reason)
{
$this->reason = $reason;
$template = 'Raw data returned by the LimeSurvey\'s API cannot be processed. Reason: \'%s\'.';
$message = sprintf($template, $this->reason);
parent::__construct($message);
}
/**
* Returns reason why data cannot be processed, e.g. "Invalid user name or password"
*
* @return string
*/
public function getReason()
{
return $this->reason;
}
}

View File

@@ -0,0 +1,38 @@
<?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
{
const className = 'Meritoo\LimeSurvey\ApiClient\Exception\CreateSessionKeyFailedException';
/**
* 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,37 @@
<?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\LimeSurvey\ApiClient\Base\Result\BaseItem;
/**
* An exception used while class used to create instance of one item of the result, with data fetched from the
* LimeSurvey's API, is incorrect
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class IncorrectClassOfResultItemException extends \Exception
{
const className = 'Meritoo\LimeSurvey\ApiClient\Exception\IncorrectClassOfResultItemException';
/**
* Class constructor
*
* @param string $className Incorrect class name used to create instance of one item
*/
public function __construct($className)
{
$template = 'Class %s used to create instance of one item of the result should extend %s, but it does not. Did'
. ' you forget to use proper base class?';
$message = sprintf($template, $className, BaseItem::className);
parent::__construct($message);
}
}

View File

@@ -0,0 +1,47 @@
<?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;
use Meritoo\Common\Utilities\Arrays;
/**
* An exception used when an error occurred while running method
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class InvalidResultOfMethodRunException extends Exception
{
const className = 'Meritoo\LimeSurvey\ApiClient\Exception\InvalidResultOfMethodRunException';
/**
* Class constructor
*
* @param Exception $previousException The previous exception, source of an error
* @param string $methodName Name of called method
* @param array $methodArguments (optional) Arguments of the called method
*/
public function __construct(Exception $previousException, $methodName, array $methodArguments = [])
{
$template = "Oops, an error occurred while running method. Is there everything ok? Details:\n"
. "- error: %s,\n"
. "- method: %s,\n"
. '- arguments: %s.';
if (empty($methodArguments)) {
$methodArguments = '(no arguments)';
} else {
$methodArguments = Arrays::valuesKeys2string($methodArguments, ', ', '=', '"');
}
$message = sprintf($template, $previousException->getMessage(), $methodName, $methodArguments);
parent::__construct($message, $previousException->getCode());
}
}

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\Exception;
/**
* An exception used when participant of survey is missing
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class MissingParticipantOfSurveyException extends \Exception
{
const className = 'Meritoo\LimeSurvey\ApiClient\Exception\MissingParticipantOfSurveyException';
/**
* Class constructor
*
* @param int $surveyId ID of survey
* @param string $email E-mail address of the participant
*/
public function __construct($surveyId, $email)
{
$template = 'Participant with e-mail %s of survey with ID %s is missing. Maybe was not added to the survey?';
$message = sprintf($template, $email, $surveyId);
parent::__construct($message);
}
}

View File

@@ -0,0 +1,39 @@
<?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;
use Meritoo\LimeSurvey\ApiClient\Result\Processor\ResultProcessor;
/**
* An exception used while class name used to create instance of one item of the 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
{
const className = 'Meritoo\LimeSurvey\ApiClient\Exception\UnknownInstanceOfResultItem';
/**
* 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 = 'Class name used to create 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::className, 'getItemClassName');
parent::__construct($message);
}
}

View File

@@ -0,0 +1,31 @@
<?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
{
const className = 'Meritoo\LimeSurvey\ApiClient\Exception\UnknownMethodException';
/**
* {@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,109 @@
<?php
namespace Meritoo\LimeSurvey\ApiClient\Manager;
use JsonRPC\Client as RpcClient;
use JsonRPC\Exception\InvalidJsonFormatException;
use Meritoo\LimeSurvey\ApiClient\Configuration\ConnectionConfiguration;
use Meritoo\LimeSurvey\ApiClient\Exception\InvalidResultOfMethodRunException;
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
{
const className = 'Meritoo\LimeSurvey\ApiClient\Manager\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
* @throws InvalidResultOfMethodRunException
*/
public function runMethod($method, $arguments = [])
{
$result = null;
$method = MethodType::getValidatedMethod($method);
try {
$result = $this
->getRpcClient()
->execute($method, $arguments);
} catch (InvalidJsonFormatException $exception) {
throw new InvalidResultOfMethodRunException($exception, $method);
}
return $result;
}
/**
* 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();
}
/*
* The SSL certificate verification is turned off?
*/
if (!$this->connectionConfiguration->isVerifySslCertificateOn()) {
$this
->rpcClient
->getHttpClient()
->withoutSslVerification();
}
}
return $this->rpcClient;
}
}

View File

@@ -0,0 +1,117 @@
<?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
{
const className = 'Meritoo\LimeSurvey\ApiClient\Manager\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,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\Collection;
use Meritoo\Common\Collection\Collection;
use Meritoo\Common\Exception\Method\DisabledMethodException;
use Meritoo\LimeSurvey\ApiClient\Result\Item\ParticipantShort;
/**
* Collection of participants (of surveys).
* All participants grouped per survey.
*
* It's a collection of participants' collections.
* The survey ID is used as an index per each collection of participants, so they are grouped by survey.
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class Participants extends Collection
{
const className = 'Meritoo\LimeSurvey\ApiClient\Result\Collection\Participants';
/**
* {@inheritdoc}
*/
public function add($element, $index = null)
{
throw new DisabledMethodException(__METHOD__, 'addParticipants');
}
/**
* {@inheritdoc}
*/
public function addMultiple($elements, $useIndexes = false)
{
throw new DisabledMethodException(__METHOD__, 'addParticipants');
}
/**
* {@inheritdoc}
*/
public function has($element)
{
throw new DisabledMethodException(__METHOD__, 'hasParticipantsOfSurvey');
}
/**
* Adds participants of given survey
*
* @param Collection $participants Participants to add. Collection of ParticipantShort classes.
* @param int $surveyId ID of survey
* @return $this
*/
public function addParticipants(Collection $participants, $surveyId)
{
/*
* No participants?
* Nothing to do
*/
if ($participants->isEmpty()) {
return $this;
}
$this
->getBySurvey($surveyId)
->addMultiple($participants);
return $this;
}
/**
* Adds participant of given survey
*
* @param ParticipantShort $participant Participant to add
* @param int $surveyId ID of survey
* @return $this
*/
public function addParticipant(ParticipantShort $participant, $surveyId)
{
$this
->getBySurvey($surveyId)
->add($participant);
return $this;
}
/**
* Returns information if there are participants of given survey
*
* @param int $surveyId ID of survey
* @return bool
*/
public function hasParticipantsOfSurvey($surveyId)
{
return false === $this
->getBySurvey($surveyId)
->isEmpty();
}
/**
* Returns participants of given survey
*
* If there are no participants of given survey, adds an empty collection who will store participants.
* So, this method will return collection always.
*
* @param int $surveyId ID of survey
* @return Collection
*/
public function getBySurvey($surveyId)
{
/*
* There are no participants of given survey?
* Let's add an empty collection who will store participants
*/
if (!isset($this[$surveyId])) {
$this[$surveyId] = new Collection();
}
return $this[$surveyId];
}
/**
* Returns participant of given survey
*
* @param int $surveyId ID of survey
* @param string $participantEmail E-mail of searched participant
* @return ParticipantShort|null
*/
public function getParticipantOfSurvey($surveyId, $participantEmail)
{
/* @var Collection $participants */
$participants = $this->getBySurvey($surveyId);
if ($participants->isEmpty()) {
return null;
}
/* @var ParticipantShort $participant */
foreach ($participants as $participant) {
if ($participant->getEmail() == $participantEmail) {
return $participant;
}
}
return null;
}
}

View File

@@ -0,0 +1,60 @@
<?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\Collection;
use Meritoo\Common\Collection\Collection;
use Meritoo\LimeSurvey\ApiClient\Result\Item\Survey;
/**
* Collection of surveys (the Survey class instances)
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class Surveys extends Collection
{
const className = 'Meritoo\LimeSurvey\ApiClient\Result\Collection\Surveys';
/**
* {@inheritdoc}
*/
public function add($element, $index = null)
{
if (null === $index) {
/* @var Survey $element */
$index = $element->getId();
}
return parent::add($element, $index);
}
/**
* Returns all or active only surveys
*
* @param bool $onlyActive (optional) If is set to true, active surveys are returned only. Otherwise - all.
* @return $this
*/
public function getAll($onlyActive = false)
{
if ($this->isEmpty() || !$onlyActive) {
return $this;
}
$all = new static();
/* @var Survey $survey */
foreach ($this as $survey) {
if ($survey->isActive()) {
$all->add($survey);
}
}
return $all;
}
}

View File

@@ -0,0 +1,399 @@
<?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 one participant
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class Participant extends BaseItem
{
const className = 'Meritoo\LimeSurvey\ApiClient\Result\Item\Participant';
/**
* 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(strtoupper($value));
break;
case 'sent':
$this->sent = 'Y' === trim(strtoupper($value));
break;
case 'remindersent':
$this->reminderSent = 'Y' === trim(strtoupper($value));
break;
case 'remindercount':
$this->reminderCount = (int)$value;
break;
case 'completed':
$this->completed = 'Y' === trim(strtoupper($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,130 @@
<?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
{
const className = 'Meritoo\LimeSurvey\ApiClient\Result\Item\ParticipantShort';
/**
* 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;
}
/**
* Returns short data of participant created from full data of participant
*
* @param Participant $participant Full data of participant
* @return $this
*/
public static function fromParticipant(Participant $participant)
{
$info = [
'firstname' => $participant->getFirstName(),
'lastname' => $participant->getLastName(),
'email' => $participant->getEmail(),
];
$data = [
'tid' => $participant->getId(),
'participant_info' => $info,
];
return new self($data);
}
}

View File

@@ -0,0 +1,155 @@
<?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
{
const className = 'Meritoo\LimeSurvey\ApiClient\Result\Item\Question';
/**
* 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,400 @@
<?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
{
const className = 'Meritoo\LimeSurvey\ApiClient\Result\Item\QuestionShort';
/**
* 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(strtoupper($value));
break;
case 'mandatory':
$this->mandatory = 'Y' === trim(strtoupper($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,145 @@
<?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
{
const className = 'Meritoo\LimeSurvey\ApiClient\Result\Item\Survey';
/**
* 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(strtoupper($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,133 @@
<?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\Common\Utilities\Reflection;
use Meritoo\LimeSurvey\ApiClient\Base\Result\BaseItem;
use Meritoo\LimeSurvey\ApiClient\Exception\IncorrectClassOfResultItemException;
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
{
const className = 'Meritoo\LimeSurvey\ApiClient\Result\Processor\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 array|BaseItem|null
*
* @throws IncorrectClassOfResultItemException
*/
public function process($method, array $rawData)
{
$method = MethodType::getValidatedMethod($method);
/*
* No data?
* Nothing to do
*/
if (empty($rawData)) {
return null;
}
/*
* Prepare class name for instance of one item
*/
$itemClassName = $this->getItemClassName($method);
/*
* The raw data is or, actually, should be iterable?
*/
if (MethodType::isResultIterable($method)) {
$items = [];
foreach ($rawData as $itemData) {
$items[] = new $itemClassName($itemData);
}
return $items;
}
return new $itemClassName($rawData);
}
/**
* Returns class name used to create 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 string
*
* @throws IncorrectClassOfResultItemException
* @throws UnknownInstanceOfResultItem
*/
private function getItemClassName($method)
{
$className = null;
$method = MethodType::getValidatedMethod($method);
switch ($method) {
case MethodType::ADD_PARTICIPANTS:
case MethodType::GET_PARTICIPANT_PROPERTIES:
$className = Participant::className;
break;
case MethodType::GET_QUESTION_PROPERTIES:
$className = Question::className;
break;
case MethodType::LIST_PARTICIPANTS:
$className = ParticipantShort::className;
break;
case MethodType::LIST_QUESTIONS:
$className = QuestionShort::className;
break;
case MethodType::LIST_SURVEYS:
$className = Survey::className;
break;
/*
* todo: Use other types of methods and create proper classes (used to get instances of one item)
*/
}
/*
* Oops, class name for instance of the item is unknown
*/
if (null === $className) {
throw new UnknownInstanceOfResultItem($method);
}
if (Reflection::isChildOfClass($className, BaseItem::className)) {
return $className;
}
/*
* Oops, class is incorrect (should extend BaseItem)
*/
throw new IncorrectClassOfResultItemException($className);
}
}

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\ApiClient\Result;
use Meritoo\Common\Collection\Collection;
use Meritoo\LimeSurvey\ApiClient\Base\Result\BaseItem;
use Meritoo\LimeSurvey\ApiClient\Exception\CannotProcessDataException;
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
{
const className = 'Meritoo\LimeSurvey\ApiClient\Result\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;
/**
* Status, information returned instead of usual/normal result
*
* @var string
*/
private $status;
/**
* 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->setRawDataAndStatus($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
* @throws CannotProcessDataException
*/
public function getData($raw = false)
{
/*
* Raw data should be returned only?
* Let's do it
*/
if ($raw) {
return $this->rawData;
}
/*
* Status is unknown?
* Let's process the raw data
*/
if (empty($this->status)) {
return $this->getProcessedData($this->rawData);
}
/*
* Oops, the raw data returned by the LimeSurvey's API cannot be processed, because status was provided.
* Well, probably something is broken and... there is no data.
*/
throw new CannotProcessDataException($this->status);
}
/**
* Returns status, information returned instead of usual/normal result
*
* @return string
*/
public function getStatus()
{
return $this->status;
}
/**
* 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);
/*
* Result is unknown and it should be iterable the result is an array?
* Let's prepare and return collection
*/
if ((null === $processed && MethodType::isResultIterable($this->method)) || 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;
}
/**
* Sets status, information returned instead of usual/normal result and raw data returned by the LimeSurvey's API
*
* @param array $rawData Raw data returned by the LimeSurvey's API
*/
private function setRawDataAndStatus(array $rawData)
{
/*
* Status was provided?
* Well, probably something is broken and... there is no data
*/
if (isset($rawData['status'])) {
$this->status = trim($rawData['status']);
$rawData = [];
}
$this->rawData = $rawData;
}
}

View File

@@ -0,0 +1,257 @@
<?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\Service;
use Meritoo\Common\Collection\Collection;
use Meritoo\LimeSurvey\ApiClient\Client\Client;
use Meritoo\LimeSurvey\ApiClient\Exception\CannotProcessDataException;
use Meritoo\LimeSurvey\ApiClient\Exception\MissingParticipantOfSurveyException;
use Meritoo\LimeSurvey\ApiClient\Result\Collection\Participants;
use Meritoo\LimeSurvey\ApiClient\Result\Item\Participant;
use Meritoo\LimeSurvey\ApiClient\Result\Item\ParticipantShort;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
use Meritoo\LimeSurvey\ApiClient\Type\ReasonType;
/**
* Service that serves participants
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class ParticipantService
{
const className = 'Meritoo\LimeSurvey\ApiClient\Service\ParticipantService';
/**
* Client of the LimeSurvey's API
*
* @var Client
*/
private $client;
/**
* Collection of participants (of surveys).
* All participants grouped per survey.
*
* @var Participants
*/
private $allParticipants;
/**
* Class constructor
*
* @param Client $client Client of the LimeSurvey's API
* @param Participants $allParticipants (optional) Collection of participants (of surveys). All participants
* grouped per survey.
*/
public function __construct(Client $client, Participants $allParticipants = null)
{
if (null === $allParticipants) {
$allParticipants = new Participants();
}
$this->client = $client;
$this->allParticipants = $allParticipants;
}
/**
* Returns client of the LimeSurvey's API
*
* @return Client
*/
public function getClient()
{
return $this->client;
}
/**
* Returns participants of given survey
*
* @param int $surveyId ID of survey
* @return Collection
*
* @throws CannotProcessDataException
*/
public function getSurveyParticipants($surveyId)
{
$hasSurvey = $this
->allParticipants
->hasParticipantsOfSurvey($surveyId);
if (!$hasSurvey) {
$arguments = [
$surveyId,
];
try {
$participants = $this
->client
->run(MethodType::LIST_PARTICIPANTS, $arguments)
->getData();
} catch (CannotProcessDataException $exception) {
$reason = $exception->getReason();
/*
* Reason of the exception is different than "Oops, there is no participants. Everything else is fine."?
* Let's throw the exception
*/
if (ReasonType::NO_PARTICIPANTS_FOUND !== $reason) {
throw $exception;
}
$participants = new Collection();
}
$this
->allParticipants
->addParticipants($participants, $surveyId);
}
return $this
->allParticipants
->getBySurvey($surveyId);
}
/**
* Returns information if given survey has participant with given e-mail
*
* @param int $surveyId ID of survey
* @param string $email E-mail address of the participant
* @return bool
*/
public function hasParticipant($surveyId, $email)
{
/*
* I have to get all participants of survey to avoid problem when participants exist but are not loaded
*/
$this->getSurveyParticipants($surveyId);
return null !== $this
->allParticipants
->getParticipantOfSurvey($surveyId, $email);
}
/**
* Adds participant with given data to survey with given ID
*
* @param int $surveyId ID of survey
* @param string $firstName First name of the participant to add
* @param string $lastName Last ame of the participant to add
* @param string $email E-mail address of the participant to add
* @return Participant
*/
public function addParticipant($surveyId, $firstName, $lastName, $email)
{
$participantsData = [
[
'firstname' => $firstName,
'lastname' => $lastName,
'email' => $email,
],
];
$arguments = [
$surveyId,
$participantsData,
];
$participantCollection = $this
->client
->run(MethodType::ADD_PARTICIPANTS, $arguments)
->getData();
/* @var Participant $addedParticipant */
$addedParticipant = $participantCollection->getFirst();
$participants = new Collection([
ParticipantShort::fromParticipant($addedParticipant),
]);
$this
->allParticipants
->addParticipants($participants, $surveyId);
return $participantCollection->getFirst();
}
/**
* Returns short data of one participant with given e-mail of given survey
*
* @param int $surveyId ID of survey
* @param string $email E-mail address of the participant
* @return ParticipantShort|null
*/
public function getParticipant($surveyId, $email)
{
/*
* I have to get all participants of survey to avoid problem when participants exist but are not loaded
*/
$this->getSurveyParticipants($surveyId);
return $this
->allParticipants
->getParticipantOfSurvey($surveyId, $email);
}
/**
* Returns full data of participant with given e-mail of given survey
*
* @param int $surveyId ID of survey
* @param string $email E-mail address of the participant
* @return Participant|null
*/
public function getParticipantDetails($surveyId, $email)
{
$arguments = [
$surveyId,
[
'email' => $email,
],
];
$participant = $this
->client
->run(MethodType::GET_PARTICIPANT_PROPERTIES, $arguments)
->getData();
/* @var Participant $participant */
return $participant;
}
/**
* Returns information if participant with given e-mail has filled given survey
*
* @param int $surveyId ID of survey
* @param string $email E-mail address of the participant
* @return bool
*
* @throws MissingParticipantOfSurveyException
*/
public function hasParticipantFilledSurvey($surveyId, $email)
{
if ($this->hasParticipant($surveyId, $email)) {
$arguments = [
$surveyId,
[
'email' => $email,
],
];
/* @var Participant $participant */
$participant = $this
->client
->run(MethodType::GET_PARTICIPANT_PROPERTIES, $arguments)
->getData();
return true === $participant->isCompleted();
}
throw new MissingParticipantOfSurveyException($surveyId, $email);
}
}

View File

@@ -0,0 +1,170 @@
<?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\Service;
use Meritoo\Common\Collection\Collection;
use Meritoo\LimeSurvey\ApiClient\Client\Client;
use Meritoo\LimeSurvey\ApiClient\Exception\CannotProcessDataException;
use Meritoo\LimeSurvey\ApiClient\Result\Collection\Surveys;
use Meritoo\LimeSurvey\ApiClient\Result\Item\Participant;
use Meritoo\LimeSurvey\ApiClient\Result\Item\Survey;
use Meritoo\LimeSurvey\ApiClient\Type\MethodType;
use Meritoo\LimeSurvey\ApiClient\Type\ReasonType;
/**
* Service that serves surveys
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class SurveyService
{
const className = 'Meritoo\LimeSurvey\ApiClient\Service\SurveyService';
/**
* Client of the LimeSurvey's API
*
* @var Client
*/
private $client;
/**
* All surveys.
* Collection of surveys (the Survey class instances).
*
* @var Surveys
*/
private $allSurveys;
/**
* Template of the url used to start survey
*
* Example:
* - url: https://your.limesurvey.instance/12345?token=q1w2e3r4t5y6
* - LimeSurvey frontend: https://your.limesurvey.instance
* - survey ID: 12345
* - token: q1w2e3r4t5y6
*
* @var string
*/
private $startSurveyUrlTemplate = '%s/%d?token=%s';
/**
* Class constructor
*
* @param Client $client Client of the LimeSurvey's API
* @param Surveys $allSurveys (optional) All surveys. Collection of surveys (the Survey class instances).
*/
public function __construct(Client $client, Surveys $allSurveys = null)
{
if (null === $allSurveys) {
$allSurveys = new Surveys();
}
$this->client = $client;
$this->allSurveys = $allSurveys;
}
/**
* Returns client of the LimeSurvey's API
*
* @return Client
*/
public function getClient()
{
return $this->client;
}
/**
* Returns all surveys
*
* @param bool $onlyActive (optional) If is set to true, active surveys are returned only. Otherwise - all.
* @return Surveys
*
* @throws CannotProcessDataException
*/
public function getAllSurveys($onlyActive = false)
{
if ($this->allSurveys->isEmpty()) {
$surveys = new Surveys();
try {
$surveys = $this
->client
->run(MethodType::LIST_SURVEYS)
->getData();
} catch (CannotProcessDataException $exception) {
$reason = $exception->getReason();
/*
* Reason of the exception is different than "Oops, there is no surveys. Everything else is fine."?
* Let's throw the exception
*/
if (ReasonType::NO_SURVEYS_FOUND !== $reason) {
throw $exception;
}
}
if (null !== $surveys && $surveys instanceof Collection) {
$this->allSurveys = new Surveys($surveys->toArray());
}
}
return $this->allSurveys->getAll($onlyActive);
}
/**
* Returns information if survey with given ID exists
*
* @param int $surveyId ID of survey to verify
* @param bool $shouldBeActive (optional) If is set to true, survey should be active. If it's not, it shouldn't
* be returned, even if exists. Otherwise - it doesn't matter.
* @return bool
*/
public function isExistingSurvey($surveyId, $shouldBeActive = false)
{
$allSurveys = $this->getAllSurveys($shouldBeActive);
/*
* No surveys?
* Nothing to do
*/
if ($allSurveys->isEmpty()) {
return false;
}
$surveyId = (int)$surveyId;
/* @var Survey $survey */
foreach ($allSurveys as $survey) {
if ($survey->getId() == $surveyId) {
return true;
}
}
return false;
}
/**
* Returns url used to start survey for given survey and participant
*
* @param int $surveyId ID of survey to start
* @param Participant $participant Participant who would like to start survey
* @return string
*/
public function getStartSurveyUrl($surveyId, Participant $participant)
{
$baseUrl = $this
->client
->getConfiguration()
->getBaseUrl();
return sprintf($this->startSurveyUrlTemplate, $baseUrl, $surveyId, $participant->getToken());
}
}

View File

@@ -0,0 +1,126 @@
<?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
{
const className = 'Meritoo\LimeSurvey\ApiClient\Type\MethodType';
/**
* Add participants to the tokens collection of the survey
*
* Returns the inserted data including additional new information like the Token entry ID and the token string.
* In case of errors in some data, return it in errors.
*
* @var string
*/
const ADD_PARTICIPANTS = 'add_participants';
/**
* 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) || (new SystemMethodType())->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::ADD_PARTICIPANTS,
static::LIST_PARTICIPANTS,
static::LIST_QUESTIONS,
static::LIST_SURVEYS,
static::LIST_USERS,
]);
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace Meritoo\LimeSurvey\ApiClient\Type;
use Meritoo\Common\Type\Base\BaseType;
/**
* Type of reason used by LimeSurvey's exception
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class ReasonType extends BaseType
{
const className = 'Meritoo\LimeSurvey\ApiClient\Type\ReasonType';
/**
* Reason of exception when there is no survey with given ID
*
* @var string
*/
const NOT_EXISTING_SURVEY_ID = 'Error: Invalid survey ID';
/**
* Reason of exception when there is no participants of survey
*
* @var string
*/
const NO_PARTICIPANTS_FOUND = 'No survey participants found.';
/**
* Reason of exception when there is no surveys
*
* @var string
*/
const NO_SURVEYS_FOUND = 'No surveys found';
/**
* Reason of exception when there is no table with tokens/participants of survey
*
* @var string
*/
const NO_TOKEN_TABLE = 'Error: No token table';
}

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\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
{
const className = 'Meritoo\LimeSurvey\ApiClient\Type\SystemMethodType';
/**
* 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';
}