Version 2 (modified by hduong, 7 years ago)

--

An observer of unicorn is simply a webservice whose the reponse page validate the observer-reponse schema (output contract). In this part, we're going to make a calculator webservice which respect this output contract.

caculator.php

<?php header('Content-type: application/xml'); ?>
<?php
$resource = fopen($_GET['uri'], 'r');

$line = 0;

$errors = array();
$results = array();

while(!feof($resource)) {
    $op = trim(fgets($resource));
    $line++;
    if($op !== '') {
        if(preg_match('/^[0-9*-+()\/]+$/', $op)) {
            ob_start();
            $result = eval("return " . $op . ';');
            $out = trim(ob_get_contents());
	    ob_end_clean();
	    if($out !== '') {
	        $errors[$line] = array($op, $out);
            }
	    else {
                if($_GET['x2']) $result *= 2;
		if($_GET['xn']) $result *= $_GET['xn'];
                $results[$line] = array($op, $result);
            }
        }
	else {
            $errors[$line] = array($op, "Forbidden characters");
        }
    }
}

echo '<?xml version="1.0" encoding="UTF-8"?>'; 
?>
<observationresponse xmlns="http://www.w3.org/unicorn/observationresponse"
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xsi:schemaLocation="http://www.w3.org/QA/2006/obs_framework/ns/observation/  http://www.w3.org/QA/2006/obs_framework/response/observer-response.xsd">
  <uri><?php echo $_GET['uri']; ?></uri>
  <passed><?php echo (count($errors) === 0 ? 'true' : 'false'); ?></passed>
  <result>
    <errors>
      <errorcount><?php echo count($errors); ?></errorcount>
      <errorlist>
        <uri><?php echo $_GET['uri']; ?></uri>
	<?php foreach($errors as $line => $val): ?>
        <error>
          <line><?php echo $line; ?></line>
          <message><?php echo $val[1]; ?></message>
	  <context><?php echo $val[0]; ?></context>	
        </error>
        <?php endforeach; ?>
      </errorlist>
    </errors>
    <informations>
      <infocount><?php echo count($results); ?></infocount>
      <infolist>
        <uri><?php echo $_GET['uri']; ?></uri>
        <?php foreach($results as $line => $val): ?>
        <info>
	  <line><?php echo $line; ?></line>
          <message><?php echo $val[0]; ?> = <?php echo $val[1]; ?></message>
        </info>
        <?php endforeach; ?>
      </infolist>
    </informations>
  </result>
</observationresponse>

Explication