Skip to content

13. Cálculo de impostos: Exercício com XML

Neste exercício, que já estudámos várias vezes, o servidor devolve os resultados ao cliente na forma de um fluxo XML.

13.1. O servidor (impots_05B_web)

O serviço web de cálculo de impostos escrito anteriormente tem uma arquitetura em camadas:

No exemplo anterior, o serviço web enviava uma das duas linhas seguintes aos seus clientes:

<erreur>message d'erreur</erreur>
<impot>montant de l'impôt</impot>

Este não é um documento XML bem formado, pois falta-lhe uma tag raiz. O novo serviço web enviará a sua resposta no seguinte formato:

<reponse><erreur>message d'erreur</erreur></reponse>

ou

<reponse><impot>montant de l'impôt</impot></reponse>

Em ambos os casos, a resposta é um documento XML bem formado que pode ser processado pelo módulo [simpleXML].

Na arquitetura de três camadas, apenas a camada [web] precisa de ser modificada. O seu código [impots_05B_web] passa a ser o seguinte:


<?php
 
// business layer
require_once "impots_05_metier.php";
 
// error management
ini_set("display_errors", "off");
 
// uTF-8 header
header("Content-Type: text/plain; charset=utf-8");
 
// ------------------------------------------------------------------------------
// tax web service
// definition of constants
$HOTE = "localhost";
$PORT = 3306;
$BASE = "dbimpots";
$USER = "root";
$PWD = "";
// the data required to calculate the tax has been placed in table mysqL $TABLE
// belonging to the $BASE database. The table has the following structure
// limits decimal(10,2), coeffR decimal(6,2), coeffN decimal(10,2)
// taxable person parameters (marital status, number of children, annual salary)
// are sent by the customer in the form params=marital status, number of children, annual salary
// results (marital status, number of children, annual salary, tax payable) are returned to the customer
// in the form <impot>impot</impot>
// or as <error>error</error>, if parameters are invalid
// retrieve the [business] layer in the session
session_start();
if (!isset($_SESSION['metier'])) {
// instantiation of the [dao] layer and the [business] layer
  try {
    $_SESSION['metier'] = new ImpotsMetier(new ImpotsDaoWithMySQL($HOTE, $PORT, $BASE, $USER, $PWD));
  } catch (ImpotsException $ie) {
    print "<reponse><erreur>Erreur : " . utf8_encode($ie->getMessage() . "</erreur></reponse>");
    exit;
  }
}
$metier = $_SESSION['metier'];
 
// retrieve the line sent by the client
$params = utf8_encode(htmlspecialchars(strtolower(trim($_POST['params']))));
//print "parameters received --> $params\n";
$items = explode(",", $params);
// there must be only 3 parameters
if (count($items) != 3) {
  print "<reponse><erreur>[$params] : nombre de paramètres invalides</erreur></reponse>\n";
  exit;
}//if
// first parameter (marital status) must be yes/no
$marié = trim($items[0]);
if ($marié != "oui" and $marié != "non") {
  print "<reponse><erreur>[$params] : 1er paramètre invalide</erreur></reponse>\n";
  exit;
}//if
// the second parameter (number of children) must be an integer
if (!preg_match("/^\s*(\d+)\s*$/", $items[1], $champs)) {
  print "<reponse><erreur>[$params] : 2ième paramètre invalide</erreur></reponse>\n";
  exit;
}//if
$enfants = $champs[1];
// the third parameter (salary) must be an integer
if (!preg_match("/^\s*(\d+)\s*$/", $items[2], $champs)) {
  print "<reponse><erreur>[$params] : 3ième paramètre invalide</erreur></reponse>\n";
  exit;
}//if
$salaire = $champs[1];
// tax calculation
$impôt = $metier->calculerImpot($marié, $enfants, $salaire);
// return the result
print "<reponse><impot>$impôt</impot></reponse>\n";
// end
exit;

O formato da resposta do serviço web é modificado nas linhas 35, 47, 53, 58, 64 e 71.

13.2. O cliente (client_impots_05b_web)

O cliente é modificado para ter em conta o novo formato de resposta. Utilizamos [simpleXML] para o processar:


<?php
 
// tax client
// error management
ini_set("display_errors", "off");
 
// ---------------------------------------------------------------------------------
// a class of utility functions
class Utilitaires {
...
}
 
// main -----------------------------------------------------
// definition of constants
$DATA = "data.txt";
$RESULTATS = "resultats.txt";
// server data
$HOTE = "localhost";
$PORT = 80;
$urlServeur = "/exemples-web/impots_05B_web.php";
 
...
exit;
 
function calculerImpot($HOTE, $PORT, $urlServeur, &$cookie, $params) {
  // connects client to ($HOTE,$PORT,$urlServeur)
// sends the $cookie cookie if it is non-empty. $cookie is passed by reference
// sends $params to the server
// exploits the result line
...
  // read line result
  $ligne = fgets($connexion, 1000);
  // close the connection
  fclose($connexion);
  // result calculation
  $xml = new SimpleXMLElement($ligne);
  $erreur = isset($xml->erreur) ? $xml->erreur : "";
  $impôt = isset($xml->impot) ? $xml->impot : "";
  // return
  return array($erreur, $impôt);
}
  • linha 32: a resposta do servidor é lida. Trata-se de um documento XML.
  • linha 36: É criado um objeto SimpleXML a partir do documento XML recebido.
  • linha 37: qualquer mensagem de erro
  • linha 38: o valor do imposto, se houver