Jump to content

pulling data from a web service - not coming into database - PHP


yiantheo

Recommended Posts

i am trying to pull some XML data (SMS messages) from a web service, the SOAP server connects successfully but for some reason data are not coming in, i am using XAMPP to test the application, connections to the database are ok, i thing something must be going wrong on the primary key validation.

This is my database wrapper:

<?php

require_once __DIR__ . '/../../models/helpers/CircuitBoardInformation.php';
require_once __DIR__ . '/../../models/helpers/CircuitBoardStatus.php';
require_once __DIR__ . '/../../models/helpers/UserAccount.php';

/**
 * Holds a database instance and provides utility methods for the database.
 */
final class DatabaseWrapper
{

    private $database;

    /**
     * Attempts to connect to the RDBMS.
     * @param $database string The database to use.
     */
    public function connect($database)
    {
        $dsn = RDBMS . ':host=' . DB_HOST . ';port=' . DB_PORT . ';dbname=' . $database;

        $options = array(
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, // throw exceptions when encountering an error, these will be chained upwards to the error handler in Router
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        );

        $this->database = new PDO($dsn, DB_USERNAME, DB_PASSWORD, $options);
    }

    /**
     * Queries the database for board information.
     * @return CircuitBoardInformation[] A collection of circuit board information
     * @throws ExecuteStatementException If the statement fails to execute.
     * @throws FetchStatementException If the statement fails to fetch a result.
     * @throws PrepareStatementException If the statement fails to prepare.
     */
    public function queryAllBoardInformation()
    {
        $statement = $this->database->prepare('SELECT * FROM board_info' );

        if ($statement === false) {
            throw new PrepareStatementException(__FUNCTION__);
        }

        if ($statement->execute() == false) {
            throw new ExecuteStatementException(__FUNCTION__);
        }

        $boards = array();

        foreach ($statement as $boardInformation) {
            $msisdn = $boardInformation['msisdn'];
            $name = $boardInformation['name'];
            $information = new CircuitBoardInformation($msisdn, $name);

            array_push($boards, $information);
        }

        return $boards;
    }

    /**
     * Queries the database for a specific board's information.
     * @param $msisdn int The board's msisdn.
     * @return CircuitBoardInformation The board information.
     * @throws ExecuteStatementException If the statement fails to execute.
     * @throws FetchStatementException If the statement fails to fetch a result.
     * @throws PrepareStatementException If the statement fails to prepare.
     */
    public function queryBoardInformation($msisdn)
    {
        $statement = $this->database->prepare('SELECT * FROM board_info WHERE msisdn = :msisdn');

        if ($statement === false) {
            throw new PrepareStatementException(__FUNCTION__);
        }

        $statement->bindParam(':msisdn', $msisdn, PDO::PARAM_INT);

        if ($statement->execute() == false) {
            throw new ExecuteStatementException(__FUNCTION__);
        }

        $result = $statement->fetch(PDO::FETCH_ASSOC);

        if ($result === false) {
            throw new FetchStatementException(__FUNCTION__);
        }

        $msisdn = (int)$result['msisdn'];
        $name = $result['name'];
        $information = new CircuitBoardInformation($msisdn, $name);

        return $information;
        }

    /**
     * Queries the database for a specific board's status.
     * @param $msisdn int The board's msisdn.
     * @return CircuitBoardStatus The board status.
     * @throws ExecuteStatementException If the statement fails to execute.
     * @throws FetchStatementException If the statement fails to fetch a result.
     * @throws PrepareStatementException If the statement fails to prepare.
     */
    public function queryBoardStatus($msisdn)
    {
        $statement = $this->database->prepare('SELECT * FROM board_status WHERE 
    msisdn = :msisdn');

        if ($statement === false) {
            throw new PrepareStatementException(__FUNCTION__);
        }

        $statement->bindParam(':msisdn', $msisdn, PDO::PARAM_INT);

        if ($statement->execute() == false) {
            throw new ExecuteStatementException(__FUNCTION__);
        }

        $result = $statement->fetch(PDO::FETCH_ASSOC);

        if ($result === false) {
            throw new FetchStatementException(__FUNCTION__);
        }

        $date = DateTime::createFromFormat(DB_DATE_FORMAT, $result['date']);
        $switchOne = $result['switchOne'];
        $switchTwo = $result['switchTwo'];
        $switchThree = $result['switchThree'];
        $switchFour = $result['switchFour'];
        $fan = $result['fan'];
        $temperature = (int)$result['temperature'];
        $keypad = (int)$result['keypad'];

        $status = new CircuitBoardStatus($date,
            $switchOne, $switchTwo, $switchThree, $switchFour,
            $fan, $temperature, $keypad);

        return $status;
    }

    /**
     * Queries the {@var $database} for a user account.
     * @param $username string The account's username.
     * @return UserAccount The user account.
     * @throws ExecuteStatementException If the statement fails to execute.
     * @throws FetchStatementException If the statement fails to fetch a result.
     * @throws PrepareStatementException If the statement fails to prepare.
     */
    public function queryUser($username)
    {
        $statement = $this->database->prepare('SELECT * FROM users WHERE username = :username');

        if ($statement === false) {
            throw new PrepareStatementException(__FUNCTION__);
        }

        $statement->bindParam(':username', $username, PDO::PARAM_STR);

        if ($statement->execute() == false) {
            throw new ExecuteStatementException(__FUNCTION__);
        }

        $result = $statement->fetch(PDO::FETCH_ASSOC);

        if ($result === false) {
            throw new FetchStatementException(__FUNCTION__);
        }

        $username = $result['username'];
        $passwordHash = $result['passwordHash'];
        $rank = $result['rank'];

        return new UserAccount($username, $passwordHash, $rank);
    }

    /**
     * Updates the {@var database} with the status of a circuit board.
     * @param $msisdn int The msisdn of the circuit board.
     * @param $status CircuitBoardStatus The circuit board's status.
     * @throws ExecuteStatementException If the statement fails to execute.
     * @throws PrepareStatementException If the statement fails to prepare.
     */
    public function updateBoardStatus($msisdn, $status)
    {
        $date = $status->getDate()->format(DB_DATE_FORMAT);
        $switchOne = $status->getSwitchOne();
        $switchTwo = $status->getSwitchTwo();
        $switchThree = $status->getSwitchThree();
        $switchFour = $status->getSwitchFour();
        $fan = $status->getFan();
        $temperature = $status->getTemperature();
        $keypad = $status->getKeypad();

        /*
         * 'REPLACE INTO' will create the row if it does not exist
         * or update the values in it if it does
         */
        $statement = $this->database->prepare(
            'REPLACE INTO board_status
            SET msisdn = :msisdn,
            date = :date,
            switchOne = :switchOne,
            switchTwo = :switchTwo,
            switchThree = :switchThree,
            switchFour = :switchFour,
            fan = :fan,
            temperature = :temperature,
            keypad = :keypad');

        if ($statement === false) {
            throw new PrepareStatementException(__FUNCTION__);
        }

        $statement->bindParam(':msisdn', $msisdn, PDO::PARAM_STR);
        $statement->bindParam(':date', $date, PDO::PARAM_STR);
        $statement->bindParam(':switchOne', $switchOne, PDO::PARAM_STR);
        $statement->bindParam(':switchTwo', $switchTwo, PDO::PARAM_STR);
        $statement->bindParam(':switchThree', $switchThree, PDO::PARAM_STR);
        $statement->bindParam(':switchFour', $switchFour, PDO::PARAM_STR);
        $statement->bindParam(':fan', $fan, PDO::PARAM_STR);
        $statement->bindParam(':temperature', $temperature, PDO::PARAM_INT);
        $statement->bindParam(':keypad', $keypad, PDO::PARAM_INT);

        if ($statement->execute() === false) {
            throw new ExecuteStatementException(__FUNCTION__);
        }
    }


    public function addAccount($account)
    {
        $statement = $this->database->prepare(
            'INSERT INTO users
            SET username = :username,
            passwordHash = :passwordHash,
            rank = :rank');

        if ($statement === false) {
            throw new PrepareStatementException(__FUNCTION__);
        }

        $username = $account->getUsername();
        $passwordHash = $account->getPasswordHash();
        $rank = $account->getRank();

        $statement->bindParam(':username', $username, PDO::PARAM_STR);
        $statement->bindParam(':passwordHash', $passwordHash, PDO::PARAM_STR);
        $statement->bindParam(':rank', $rank, PDO::PARAM_STR);

        if ($statement->execute() === false) {
            throw new ExecuteStatementException(__FUNCTION__);
        }
    }

    /**
     * Deletes a user account from the the {@var database}.
     * @param $username string The username.
     * @throws ExecuteStatementException If the statement fails to execute.
     * @throws PrepareStatementException If the statement fails to prepare.
     */
    public function deleteUser($username)
    {
        $statement = $this->database->prepare(
            'DELETE FROM users
            WHERE username = :username');

        if ($statement === false) {
            throw new PrepareStatementException(__FUNCTION__);
        }

        $statement->bindParam(':username', $username, PDO::PARAM_STR);

        if ($statement->execute() === false) {
            throw new ExecuteStatementException(__FUNCTION__);
        }
    }
}

class DatabaseException extends Exception
{
    /**
     * Creates a new database exception.
     * @param $action string The database action being performed.
     * @param $function string The function name.
     */
    public function __construct($action, $function)
    {
        parent::__construct("[$function] Failed to $action statement.");
    }
}

final class PrepareStatementException extends DatabaseException
{
    /**
     * Creates a new prepare statement exception.
     * @param $function string The function name.
     */
    public function __construct($function)
    {
        parent::__construct('prepare', $function);
    }
}

final class ExecuteStatementException extends DatabaseException
{
    /**
     * Creates a new execute statement exception.
     * @param $function string The function name.
     */
    public function __construct($function)
    {
        parent::__construct('execute', $function);
    }
}

final class FetchStatementException extends DatabaseException
{
    /**
     * Creates a new fetch statement exception.
     * @param $function string The function name.
     */
    public function __construct($function)
    {
        parent::__construct('fetch', $function);
    }
}

This is my SMSvalidator:

<?php

/**
 * Validates raw XML formatted SMS messages.
 */
final class SMSValidator
{
    /**
     * The message to validate.
     * @var array
     */
    private $message;

    /**
     * Creates a new {@link SMSValidator}
     * @param $message array The message to validate
     */
    public function __construct($message)
    {
        $this->message = $message;
    }

    /**
     * Gets the value of a field in this message.
     * @param $key string The field's key.
     * @return mixed The value
     * @throws Exception If the key is missing.
     */
    private function getValue($key)
    {
        if (!isset($this->message[$key])) {
            throw new MissingSMSKeyException($key);
        }

        return $this->message[$key];
    }

    /**
     * Validates the 'SOURCEMSISDN' field.
     * @return string The validated field.
     * @throws Exception If an error occurs during sanitisation/validation.
     */
    public function validateMSISDN()
    {
        $key = 'SOURCEMSISDN';

        $msisdn = $this->getValue($key);
        $msisdn = filter_var($msisdn, FILTER_SANITIZE_NUMBER_INT);
        $msisdn = filter_var($msisdn, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0, 'max_range' => 999999999999999))); // at minimum 1 digit, at maximum 15 digits

        if ($msisdn === false) {
            throw new FilterException($key);
        }

        return (int)$msisdn;
    }

    /**
     * Validates the received date value.
     * @return DateTime The validated date object.
     * @throws Exception If an error occurs during sanitisation/validation.
     */
    public function validateDate()
    {
        $key = 'RECEIVEDTIME';

        $receivedTime = $this->getValue($key);
        $receivedTime = filter_var($receivedTime, FILTER_SANITIZE_STRING);

        if ($receivedTime === false) {
            throw new FilterException($key);
        }

        $date = DateTime::createFromFormat(DATE_FORMAT, $receivedTime);

        if ($date === false) {
            throw new InvalidDateException($key);
        }

        return $date;
    }

    /**
     * Validates the bearer field.
     * @return string The bearer field.
     * @throws Exception If an error occurs during sanitisation/validation.
     */
    public function validateBearer()
    {
        $key = 'BEARER';

        $bearer = $this->getValue($key);
        $bearer = filter_var($bearer, FILTER_SANITIZE_STRING);

        if ($bearer === false) {
            throw new FilterException($key);
        }

        if ($bearer !== 'SMS') {
            throw new BearerMismatchException($key);
        }

        return $bearer;
    }

    /**
     * Validates the SMS identifier.
     * @return string The SMS identifier.
     * @throws Exception If an error occurs during sanitisation/validation.
     */
    public function validateSMSIdentifier()
    {
        $key = 'ID';

        $smsIdentifier = $this->getValue($key);
        $smsIdentifier = filter_var($smsIdentifier, FILTER_SANITIZE_STRING);

        if ($smsIdentifier === false) {
            throw new FilterException($key);
        }

        if ($smsIdentifier !== SMS_IDENTIFIER) {
            throw new IDMismatchException($key);
        }

        return $smsIdentifier;
    }

    /**
     * Sanitizes and validates a switch status.
     * @param $switchNumber int The switch number to validate.
     * @return string The switch status.
     * @throws Exception If an error occurs during sanitisation/validation.
     */
    public function validateSwitch($switchNumber)
    {
        $key = 'S' . $switchNumber;

        if ($switchNumber < 1 || $switchNumber > 4) {
            throw new InvalidSwitchException($key);
        }

        $switch = $this->getValue($key);
        $switch = filter_var($switch, FILTER_SANITIZE_NUMBER_INT);
        $switch = filter_var($switch, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0, 'max_range' => 1)));

        if ($switch === false) {
            throw new FilterException($key);
        }

        if ($switch === 0) {
            return 'OFF';
        } else if ($switch === 1) {
            return 'ON';
        }

        throw new SwitchStateMismatchException($key);
    }

    /**
     * Sanitizes and validates the fan status.
     * @return string The fan status.
     * @throws Exception If an error occurs during sanitisation/validation.
     */
    public function validateFan()
    {
        $key = 'F';

        $fan = $this->getValue($key);
        $fan = filter_var($fan, FILTER_SANITIZE_NUMBER_INT);
        $fan = filter_var($fan, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0, 'max_range' => 1)));

        if ($fan === false) {
            throw new FilterException($key);
        }

        if ($fan === 0) {
            return 'FORWARD';
        } else if ($fan === 1) {
            return 'REVERSE';
        }

        throw new FanStateMismatchException($key);
    }

    /**
     * Sanitizes and validates a temperature amount.
     * @return string The validated temperature.
     * @throws Exception If an error occurs during sanitisation/validation.
     */
    public function validateTemperature()
    {
        $key = 'T';

        $temperature = $this->getValue($key);
        $temperature = filter_var($temperature, FILTER_SANITIZE_NUMBER_INT);
        $temperature = filter_var($temperature, FILTER_VALIDATE_INT, array('options' => array('min_range' => -99, 'max_range' => 999))); // 3 max digits at all times

        if ($temperature === false) {
            throw new FilterException($key);
        }

        return (int)$temperature;
    }

    /**
     * Sanitizes and validates the keypad input.
     * @return string The validated keypad input.
     * @throws Exception If an error occurs during sanitisation/validation.
     */
    public function validateKeypad()
    {
        $key = 'K';

        $keypad = $this->getValue($key);
        $keypad = filter_var($keypad, FILTER_SANITIZE_NUMBER_INT);
        $keypad = filter_var($keypad, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0, 'max_range' => 9))); // must be 1 digit

        if ($keypad === false) {
            throw new FilterException($key);
        }

        return (int)$keypad;
    }

    /**
     * Sanitizes and validates the {@var $message} into a {@link CircuitBoardStatus}.
     * @return CircuitBoardStatus The validated circuit board status or {@code null} if the message did not contain a valid circuit board status..
     */
    public function validateStatus()
    {
        $date = $this->validateDate();
        $this->validateBearer();
        $switchOne = $this->validateSwitch(1);
        $switchTwo = $this->validateSwitch(2);
        $switchThree = $this->validateSwitch(3);
        $switchFour = $this->validateSwitch(4);
        $fan = $this->validateFan();
        $temperature = $this->validateTemperature();
        $keypad = $this->validateKeypad();

        $status = new CircuitBoardStatus($date,
            $switchOne, $switchTwo, $switchThree, $switchFour,
            $fan, $temperature, $keypad);

        return $status;
    }
}

final class MissingSMSKeyException extends Exception
{
    public function __construct($key)
    {
        parent::__construct("Missing value for $key.");
    }
}

final class FilterException extends Exception
{
    public function __construct($key)
    {
        parent::__construct("$key Filter failed.");
    }
}

final class InvalidDateException extends Exception
{
    public function __construct($key)
    {
        parent::__construct("$key Must be in format of " . DATE_FORMAT . ".");
    }
}

final class BearerMismatchException extends Exception
{
    public function __construct($key)
    {
        parent::__construct("$key Must be SMS.");
    }
}

final class IDMismatchException extends Exception
{
    public function __construct($key)
    {
        parent::__construct("$key Must match " . SMS_IDENTIFIER . ".");
    }
}

final class InvalidSwitchException extends Exception
{
    public function __construct($key)
    {
        parent::__construct("$key Switch number must be 1-4 inclusive.");
    }
}

final class SwitchStateMismatchException extends Exception
{
    public function __construct($key)
    {
        parent::__construct("$key Must be either 0 (OFF) or 1 (ON).");
    }
}

final class FanStateMismatchException extends Exception
{
    public function __construct($key)
    {
        parent::__construct("$key Must be either 0 (FORWARD) or 1 (REVERSE).");
    }
}

when i debug the application i get a filter exception when testing the SOURCEMSISDN, i can't understand why though as the msisdn (this is the primary key) provided is correct

this is a valid XML message:

<messagerx>
<sourcemsisdn>12345</sourcemsisdn>
<destinationmsisdn>12345</destinationmsisdn>
<receivedtime>27/08/2018 02:19:28</receivedtime>
<bearer>SMS</bearer>
<messageref>0</messageref>
<message>
<id>abc123</id>
<s1>0</s1>
<s2>1</s2>
<s3>0</s3>
<s4>1</s4>
<f>0</f>
<t>38</t>
<k>5</k>
</message>
</messagerx>

This is my TestSMSvalidator:

<?php

require_once __DIR__ . '/../../../../includes/application/controllers/helpers/SMSValidator.php';

/* normally can't store arrays as constants, however if we serialize it... */
define('VALID_SMS_MESSAGE', serialize(array(

    'SOURCEMSISDN'      => M2M_MSISDN,
    'DESTINATIONMSISDN' => M2M_MSISDN,
    'RECEIVEDTIME'      => '27/11/2014 02:19:28',
    'BEARER'            => 'SMS',
    'ID'                => SMS_IDENTIFIER,
    'S1'                => 0,
    'S2'                => 1,
    'S3'                => 0,
    'S4'                => 1,
    'F'                 => 0,
    'T'                 => 30,
    'K'                 => 5
)));


final class TestSMSValidator extends M2MTestCase
{
    function testValidMessage()
    {
        $message = unserialize(VALID_SMS_MESSAGE);
        $validator = new SMSValidator($message);
        $validator->validateStatus();
    }

    static function validateMSISDN($msisdn)
    {
        $message = unserialize(VALID_SMS_MESSAGE);
        $message['SOURCEMSISDN'] = $msisdn;
        $validator = new SMSValidator($message);
        return $validator->validateMSISDN();
    }

    function testValidMSISDN()
    {
        $this->assertIdentical(447817814149, $this->validateMSISDN(447817814149));
        $this->assertIdentical(447817814149, $this->validateMSISDN('+447817814149'));
        $this->assertException('FilterException', [$this, 'validateMSISDN'], [-447817814149]);
        $this->assertIdentical(447817814149, $this->validateMSISDN('<447817814149>'));
        $this->assertIdentical(4401010101, $this->validateMSISDN(4401010101));
        $this->assertIdentical(005, $this->validateMSISDN(005));
        $this->assertIdentical(447817814149, $this->validateMSISDN('(+44) 7817 814 149'));
        $this->assertException('MissingSMSKeyException', [$this, 'validateMSISDN'], [null]);
    }

    function validateDate($date)
    {
        $message = unserialize(VALID_SMS_MESSAGE);
        $message['RECEIVEDTIME'] = $date;

        $validator = new SMSValidator($message);
        return $validator->validateDate();
    }

    function testValidDate()
    {
        $this->assertNotNull($this->validateDate('27/12/2014 02:19:28'));
        $this->assertException('InvalidDateException', [$this, 'validateDate'], ['27/12/2014']);
        $this->assertException('InvalidDateException', [$this, 'validateDate'], ['Monday 29th Dec']);
        $this->assertNotNull($this->validateDate('1/1/2001 01:01:01'));
        $this->assertException('InvalidDateException', [$this, 'validateDate'], ['\'\'']);
        $this->assertException('InvalidDateException', [$this, 'validateDate'], ['<>\'\'#&']);
        $this->assertException('MissingSMSKeyException', [$this, 'validateDate'], [null]);
    }

    function validateBearer($bearer)
    {
        $message = unserialize(VALID_SMS_MESSAGE);
        $message['BEARER'] = $bearer;

        $validator = new SMSValidator($message);
        return $validator->validateBearer();
    }

    function testValidBearer()
    {
        $this->assertIdentical('SMS', $this->validateBearer('SMS'));
        $this->assertException('BearerMismatchException', [$this, 'validateBearer'], ['sms']);
        $this->assertException('BearerMismatchException', [$this, 'validateBearer'], ['<sms>']);
        $this->assertException('BearerMismatchException', [$this, 'validateBearer'], ['<SMS>']);
        $this->assertException('MissingSMSKeyException', [$this, 'validateBearer'], [null]);
    }

    function validateSMSIdentifier($id)
    {
        $message = unserialize(VALID_SMS_MESSAGE);
        $message['ID'] = $id;

        $validator = new SMSValidator($message);
        return $validator->validateSMSIdentifier();
    }

    function testValidSMSIdentifier()
    {
        $this->assertIdentical('abc123', $this->validateSMSIdentifier('abc123'));
        $this->assertException('IDMismatchException', [$this, 'validateSMSIdentifier'], ['ABC123']);
        $this->assertException('IDMismatchException', [$this, 'validateSMSIdentifier'], ['abc__123']);
        $this->assertException('IDMismatchException', [$this, 'validateSMSIdentifier'], ['#_&']);
        $this->assertException('MissingSMSKeyException', [$this, 'validateSMSIdentifier'], [null]);
    }

    function validateSwitch($state)
    {
        $switches = [1, 2, 3, 4];
        $switchNumber = $switches[array_rand($switches)]; // pick a random switch

        $message = unserialize(VALID_SMS_MESSAGE);
        $message["S$switchNumber"] = $state;

        $validator = new SMSValidator($message);
        return $validator->validateSwitch($switchNumber);
    }

    function testValidSwitch()
    {
        $this->assertIdentical('OFF', $this->validateSwitch(0));
        $this->assertIdentical('ON', $this->validateSwitch(1));
        $this->assertException('FilterException', [$this, 'validateSwitch'], ['off']);
        $this->assertException('FilterException', [$this, 'validateSwitch'], [2]);
        $this->assertException('FilterException', [$this, 'validateSwitch'], [-1]);
        $this->assertException('MissingSMSKeyException', [$this, 'validateSwitch'], [null]);
    }

    function validateFan($fan)
    {
        $message = unserialize(VALID_SMS_MESSAGE);
        $message['F'] = $fan;

        $validator = new SMSValidator($message);
        return $validator->validateFan();
    }

    function testValidFan()
    {
        $this->assertIdentical('FORWARD', $this->validateFan(0));
        $this->assertIdentical('FORWARD', $this->validateFan('<0>'));
        $this->assertIdentical('REVERSE', $this->validateFan(1));
        $this->assertIdentical('REVERSE', $this->validateFan('1;'));
        $this->assertException('FilterException', [$this, 'validateFan'], [2]);
        $this->assertException('FilterException', [$this, 'validateFan'], [3]);
        $this->assertException('FilterException', [$this, 'validateFan'], [-1]);
        $this->assertException('FilterException', [$this, 'validateFan'], ['On']);
        $this->assertException('FilterException', [$this, 'validateFan'], ['off']);
        $this->assertException('FilterException', [$this, 'validateFan'], ['FORWARD']);
        $this->assertException('MissingSMSKeyException', [$this, 'validateFan'], [null]);
    }

    function validateTemperature($temperature)
    {
        $message = unserialize(VALID_SMS_MESSAGE);
        $message['T'] = $temperature;

        $validator = new SMSValidator($message);
        return $validator->validateTemperature();
    }

    function testValidTemperature()
    {
        $this->assertIdentical(25, $this->validateTemperature(25));
        $this->assertIdentical(99, $this->validateTemperature(99));
        $this->assertIdentical(105, $this->validateTemperature(105));
        $this->assertIdentical(-12, $this->validateTemperature(-12));
        $this->assertException('FilterException', [$this, 'validateTemperature'], ['HOT!']);
        $this->assertException('FilterException', [$this, 'validateTemperature'], ['really cold']);
        $this->assertIdentical(-55, $this->validateTemperature(-55));
        $this->assertIdentical(-25, $this->validateTemperature(-25));
        $this->assertIdentical(25, $this->validateTemperature('SELECT 25'));
        $this->assertException('MissingSMSKeyException', [$this, 'validateTemperature'], [null]);
    }

    function validateKeypad($keypad)
    {
        $message = unserialize(VALID_SMS_MESSAGE);
        $message['K'] = $keypad;

        $validator = new SMSValidator($message);
        return $validator->validateKeypad();
    }

    function testValidKeypad()
    {
        $this->assertIdentical(0, $this->validateKeypad(0));
        $this->assertIdentical(5, $this->validateKeypad(5));
        $this->assertException('FilterException', [$this, 'validateKeypad'], [10]);
        $this->assertException('FilterException', [$this, 'validateKeypad'], [-1]);
        $this->assertException('FilterException', [$this, 'validateKeypad'], ['five']);
        $this->assertIdentical(5, $this->validateKeypad('_5'));
        $this->assertIdentical(2, $this->validateKeypad('&2&'));
        $this->assertException('MissingSMSKeyException', [$this, 'validateKeypad'], [null]);
    }
}

 

Link to comment
Share on other sites

i did that but is seems i get these errors when i try and put some random data in:

Fail: C:\xampp\htdocs\gotmad\test\application/controllers/helpers\TestDatabaseWrapper.php -> TestDatabaseWrapper -> testQueryBoardStatus -> Identical expectation [String: ON] fails with [String: OFF] at character 1 with [ON] and [OFF] at [C:\xampp\htdocs\gotmad\test\application\controllers\helpers\TestDatabaseWrapper.php line 40]
Fail: C:\xampp\htdocs\gotmad\test\application/controllers/helpers\TestDatabaseWrapper.php -> TestDatabaseWrapper -> testQueryBoardStatus -> Identical expectation [String: ON] fails with [String: OFF] at character 1 with [ON] and [OFF] at [C:\xampp\htdocs\gotmad\test\application\controllers\helpers\TestDatabaseWrapper.php line 41]
Fail: C:\xampp\htdocs\gotmad\test\application/controllers/helpers\TestDatabaseWrapper.php -> TestDatabaseWrapper -> testQueryBoardStatus -> Identical expectation [String: ON] fails with [String: OFF] at character 1 with [ON] and [OFF] at [C:\xampp\htdocs\gotmad\test\application\controllers\helpers\TestDatabaseWrapper.php line 43]
Fail: C:\xampp\htdocs\gotmad\test\application/controllers/helpers\TestDatabaseWrapper.php -> TestDatabaseWrapper -> testQueryBoardStatus -> Identical expectation [String: FORWARD] fails with [String: REVERSE] at character 0 with [FORWARD] and [REVERSE] at [C:\xampp\htdocs\gotmad\test\application\controllers\helpers\TestDatabaseWrapper.php line 44]
Fail: C:\xampp\htdocs\gotmad\test\application/controllers/helpers\TestDatabaseWrapper.php -> TestDatabaseWrapper -> testQueryBoardStatus -> Identical expectation [Integer: 12] fails with [Integer: 37] because [Integer: 12] differs from [Integer: 37] by 25 at [C:\xampp\htdocs\gotmad\test\application\controllers\helpers\TestDatabaseWrapper.php line 45]
Exception: C:\xampp\htdocs\gotmad\test\application/controllers/helpers\TestSMSValidator.php -> TestSMSValidator -> testValidMSISDN -> Unexpected exception of type [FilterException] with message [SOURCEMSISDN Filter failed.] in [C:\xampp\htdocs\gotmad\includes\application\controllers\helpers\SMSValidator.php line 52]

Link to comment
Share on other sites

no i don't think that is a SOAP problem, yeah actually i have a really hard time figuring out what's wrong, the value is: define('M2M_MSISDN', 447817814149); it should give a filter exception when it's something like -447817814149

i am not sure about the 64-bit i am using XAMPP which i think is using 32-bit

 

 

Link to comment
Share on other sites

well i cannot find xampp 64 bit for windows, only for linux...but i tried with '12345' and i still get the same error.

when i try the 12 digit number into my testdatabase class instead of '12345' i get fetch exceptions and random data are not going into the database

here is my DatabaseTest

<?php

require_once __DIR__ . '/../../../../includes/application/controllers/helpers/DatabaseWrapper.php';

final class TestDatabaseWrapper extends M2MTestCase
{
	/**
	 * @var DatabaseWrapper
	 */
	private $db;

	function setUp()
	{
		$this->db = new DatabaseWrapper();
		$this->db->connect(TEST_DB_NAME);
	}

	function testQueryAllBoardInformation()
	{
		$result = $this->db->queryAllBoardInformation();
		
	}

	function testQueryBoardInformation()
	{
		$expected = new CircuitBoardInformation(447817814149, 'testboard');
		$result = $this->db->queryBoardInformation(447817814149);
		$this->assertIdentical($expected, $result);

		$this->assertException('FetchStatementException', [$this->db, 'queryBoardInformation'], [12]);
	}

	function testQueryBoardStatus()
	{
		$expected = new CircuitBoardStatus(new DateTime('2015-01-07 18:47:17.000000'), 'ON', 'ON', 'ON', 'ON', 'FORWARD', 12, 3);
		$result = $this->db->queryBoardStatus(447817814149);

		// for some reason DateTime identical assertions never match?

		$this->assertIdentical($expected->getSwitchOne(), $result->getSwitchOne());
		$this->assertIdentical($expected->getSwitchTwo(), $result->getSwitchTwo());
		$this->assertIdentical($expected->getSwitchThree(), $result->getSwitchThree());
		$this->assertIdentical($expected->getSwitchFour(), $result->getSwitchFour());
		$this->assertIdentical($expected->getFan(), $result->getFan());
		$this->assertIdentical($expected->getTemperature(), $result->getTemperature());
		$this->assertIdentical($expected->getKeypad(), $result->getKeypad());

		$this->assertException('FetchStatementException', [$this->db, 'queryBoardStatus'], [12]);
	}

	function testQueryUser()
	{
		$expected = new UserAccount('test', '$2y$10$XQCPxvGTXsqdKY4/h831A.Y9NjizXLPM7uQkM/OkLEdFXHSItLKsO', 'USER');
		$result = $this->db->queryUser('test');
		$this->assertIdentical($expected, $result);

		$this->assertException('FetchStatementException', [$this->db, 'queryUser'], ['nobody']);
	}

	function randomCircuitBoardStatus()
	{
		$switchStates = array('OFF', 'ON');
		$fanStates = array('FORWARD', 'REVERSE');

		return new CircuitBoardStatus(new DateTime(),
			$switchStates[array_rand($switchStates)], $switchStates[array_rand($switchStates)], $switchStates[array_rand($switchStates)], $switchStates[array_rand($switchStates)],
			$fanStates[array_rand($fanStates)], rand(0, 99), rand(0, 9));
	}

	function testUpdateBoardStatus()
	{
		for ($i = 0; $i < 10; $i++) { /* as we use random data lets perform this test a few times */
			$expected = $this->randomCircuitBoardStatus();
			$this->db->updateBoardStatus(447817814149, $expected);
			$result = $this->db->queryBoardStatus(447817814149);

			$this->assertIdentical($expected->getSwitchOne(), $result->getSwitchOne());
			$this->assertIdentical($expected->getSwitchTwo(), $result->getSwitchTwo());
			$this->assertIdentical($expected->getSwitchThree(), $result->getSwitchThree());
			$this->assertIdentical($expected->getSwitchFour(), $result->getSwitchFour());
			$this->assertIdentical($expected->getFan(), $result->getFan());
			$this->assertIdentical($expected->getTemperature(), $result->getTemperature());
			$this->assertIdentical($expected->getKeypad(), $result->getKeypad());
		}
	}

	function testAddDeleteAccount()
	{
		$expected = new UserAccount('new_acc', 'pass', 'ADMIN');
		$this->db->addAccount($expected);
		$result = $this->db->queryUser('new_acc');
		$this->db->deleteUser('new_acc'); // clean up after ourselves
		$this->assertIdentical($expected, $result);
	}
}

also to explain more in detail, i have a button check updates and when i click that button the app needs to connect to the soap server and fetch new status updates - instead it says no updates found

this is my updatecontroller as well: 

<?php

require_once __DIR__ . '/../models/helpers/CircuitBoard.php';
require_once __DIR__ . '/helpers/DatabaseWrapper.php';
require_once __DIR__ . '/helpers/SMSValidator.php';
require_once __DIR__ . '/helpers/SoapClientWrapper.php';
require_once __DIR__ . '/helpers/XMLParser.php';
require_once __DIR__ . '/AbstractController.php';

/**
 * Controls a 'check updates' action.

 */
final class UpdatesController extends AbstractController
{
	/**
	 * Creates a new {@link StatusesController}.
	 * @param $model UpdatesModel The model.
	 */
	public function __construct($model)
	{
		parent::__construct($model);
	}

	/**
	 * Fetches the statuses of the circuit boards from the database.
	 * @throws Exception If a query fails to execute.
	 */
	public function fetchUpdates() {
		$soap = new SoapClientWrapper();
		$messages = $soap->getNewMessages();

		$database = new DatabaseWrapper();
		$database->connect(DB_NAME);

		foreach ($messages as $message) {
			$xmlParser = new XMLParser($message);
			$xmlParser->parse();
			$parsedMessage = $xmlParser->getParsedData();

			$validator = new SMSValidator($parsedMessage);

			try {
				$msisdn = $validator->validateMSISDN();
				$status = $validator->validateStatus();

				$information = $database->queryBoardInformation($msisdn);

				$update = new CircuitBoard($information, $status);

				$database->updateBoardStatus($msisdn, $status);

				$this->model->addUpdate($update);
			} catch (Exception $e) {
				continue;
			}
		}
	}
}

 

Link to comment
Share on other sites

I have a couple of questions and comments:

  1. What database are you using. What is your database structure? 
  2. Depending on the architecture of the workstation you are using, you can utilize virtualbox to run virtual operating systems.  Installing Vagrant with virtualbox would be a good fast way to get a Linux OS up, and given the vast number of vagrants out there, you can probably find one that has everything you need in your application stack.

With that said, you need a 64bit workstation that also supports VT in the bios in order to run 64bit OS's virtually.  I wrote a blog post about a particular laptop I was planning on buying, that talks about this issue and has some useful information about the underlying requirements for 64bit virtualization.  

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.