1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
<?php
class Contact
{
private $param = array();
private $dataOk;
private $errorList = array();
public function __construct()
{
$this->dataOk = true;
$this->errorList = array();
$this->initController();
$this->controlData();
if ($this->dataOk ) saveData();
}
// la méthode renvoie soit true soit false
public function hasBeenSaved()
{
return $this->dataOk;
}
// la méthode renvoie la liste des erreurs
public function getErrorList()
{
return $this->errorList;
}
private function initController()
{
// l'index du tableau correspond au nom du champ dans le formulaire
// le premier poste contient la regexp de contrôle de données
// le second poste contient le type de données
// le troisième poste contient le nom du champ dans la table +++ peut être pour plus tard :)
$this->param['nom'] = array("/^ *** regexp contrôle nom $/",'nom','champ_nom');
$this->param['sexe'] = array("/^ *** regexp contrôle sexe $/",'sexe','champ_sexe');
$this->param['secteur'] = array("/^ *** regexp contrôle secteur $/",'secteur','champ_secteur');
$this->param['cd'] = array("/^ *** regexp contrôle cd $/",'cd','champ_cd');
$this->param['categorie'] = array("/^ *** regexp contrôle categorie $/",'categorie','champ_categorie');
$this->param['taille1'] = array("/^ *** regexp contrôle taille $/",'taille','champ_taille1');
...
$this->param['taille2'] = array("/^ *** regexp contrôle taille $/",'taille','champ_taille2');
}
private function commonController($regexp,$type,$value)
{
if(!empty($value))
{
if (!filter_var($value, FILTER_VALIDATE_REGEXP, array("options" => array("regexp"=>$regexp))) !== false )
{
$this->errorList[] = "le format de votre $type $value est incorrect ! <br>";
$this->dataOk = false;
}
}
else
{
$this->errorList[] = "La saisie de votre $type est obligatoire <br>";
$this->dataOk = false;
}
}
private function controlData()
{
// parcours des champs à contrôler
foreach($this->param as $key => $paramProperties)
{
if (isset($_POST[$key]))
{
$this->commonController($paramProperties[0],$paramProperties[1],$_POST[$key]);
}
else
{
$this->errorList[] = "Le champ $key n''a pas été transmis <br>";
$this->dataOk = false;
}
}
}
private function saveData()
{
// connexion à la base de données
// affectation des valeurs
$nom = $_POST['nom'];
...
$taille1 = $_POST['taille1'];
$taille2 = $_POST['taille2'];
...
// enregistement dans la base de données
}
}
// utilisation
$contact = new Contact();
if (! $contact->hasBeenSaved())
{
echo "Des erreurs ont été rencontrées <br>";
foreach($contact->getErrorList() => $erreur)
{
echo "$erreur<br/>";
}
} |
Partager