| Version 5 (modified by jean-gui, 3 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>
Explanation
- Input:
- the parameter uri = path to your text file what is accessible by your server
- the parameter x2 = 0/1: double the results
- Output: a observer-reponse which expose all possible calculation result in the file
- Test: http://flyingman.sophia.w3.org/calculator.php?uri=http://flyingman.sophia.w3.org/test.txt&x2=1
