Overview

Namespaces

  • None
  • PHP
  • Pry
    • Auth
      • Interfaces
    • Config
    • Controller
    • Date
    • Db
    • Feed
      • Abstracts
      • Writers
    • File
      • Decorator
    • Form
      • Element
    • Image
    • Log
      • Writer
    • Net
      • Exception
    • Session
    • Util
    • Validate
      • Validator
    • View

Classes

  • Error
  • Field
  • Form
  • Input
  • Overview
  • Namespace
  • Class
  • Tree
  1: <?php
  2: 
  3: /**
  4:  * Pry Framework
  5:  *
  6:  * LICENSE
  7:  *
  8:  * This source file is subject to the new BSD license that is bundled
  9:  * with this package in the file LICENSE.txt.
 10:  * 
 11:  */
 12: 
 13: namespace Pry\Form;
 14: 
 15: use Pry\Util\Token;
 16: 
 17: /**
 18:  * Class représentant un formulaire.
 19:  * 
 20:  * <code>
 21:  * $form = new Form_Form('monForm');
 22:  * $form->setPostedValue($_POST);
 23:  * $form->action('form.php')
 24:  *      ->setAttributes('onsubmit','');
 25:  * 
 26:  * $form->add('Text','nom')
 27:  *      ->label('test')
 28:  *      ->value('Mon nom')
 29:  *      ->addClass('cssclass')
 30:  *      ->minLength(3);
 31:  * $form->add('Submit','envoi')
 32:  *      ->id('envoiBtn')
 33:  *      ->value('Envoyer');
 34:  * 
 35:  * if($form->isValid($_POST))
 36:  * {
 37:  *      echo 'OK';
 38:  * }
 39:  * else
 40:  *      echo $form;
 41:  * </code>
 42:  * 
 43:  * @category Pry
 44:  * @package Form
 45:  * @version 1.1.0 
 46:  * @author Olivier ROGER <oroger.fr>
 47:  *       
 48:  */
 49: class Form
 50: {
 51: 
 52:     /**
 53:      * Liste des champs du formulaire
 54:      *
 55:      * @var array
 56:      * @access private
 57:      */
 58:     private $champs;
 59: 
 60:     /**
 61:      * Liste des champs submit
 62:      *
 63:      * @var array
 64:      * @access private
 65:      */
 66:     private $champs_submit;
 67: 
 68:     /**
 69:      * Liste des champs hidden
 70:      *
 71:      * @var array
 72:      */
 73:     private $champs_hidden;
 74: 
 75:     /**
 76:      * Contenu du formulaire après $_POST
 77:      *
 78:      * @var array
 79:      * @access private
 80:      */
 81:     private $posted_value;
 82: 
 83:     /**
 84:      * Liste des attributs du formulaire
 85:      *
 86:      * @var array
 87:      * @access private
 88:      */
 89:     protected $attrs;
 90: 
 91:     /**
 92:      * identifiant du formulaire
 93:      *
 94:      * @var string
 95:      * @access protected
 96:      */
 97:     protected $uniqid;
 98: 
 99:     /**
100:      * Instance de formulaire
101:      *
102:      * @var array
103:      * @access protected
104:      */
105:     protected static $instances = array();
106: 
107:     /**
108:      * Liste des infos à afficher
109:      *
110:      * @var array
111:      * @access public
112:      */
113:     public $listTooltips;
114:     public $javascript;
115: 
116:     /**
117:      * Constructeur
118:      *
119:      * @param string $uniqid Id unique identifiant le formulaire
120:      * @param string $method
121:      * @access public
122:      */
123:     public function __construct($uniqid, $method = 'post')
124:     {
125:         $this->champs = array();
126:         $this->champs_submit = array();
127:         $this->champs_hidden = array();
128:         $this->attrs = array();
129:         $this->listTooltips = array();
130: 
131:         if ($uniqid !== FALSE && in_array($uniqid, self::$instances))
132:             throw new \Exception('Une instance de ce formulaire semble déjà exister');
133:         else
134:         {
135:             $this->uniqid = $uniqid;
136:             self::$instances[] = $this->uniqid;
137:             $this->method($method);
138:             $this->add('Hidden', 'uniqid')
139:                     ->value($this->uniqid);
140:             if (!$this->isSubmited(true))
141:             {
142:                 Token::genToken(30);
143:                 $token = Token::getToken();
144:             }
145:             else
146:                 $token = $_POST['csrf_protect'];
147:             $this->add('Hidden', 'csrf_protect')->value($token);
148:         }
149:     }
150: 
151:     /**
152:      * Valide le formulaire
153:      *
154:      * @param array $post
155:      * @param boolean $noSubmit true si aucun bouton submit.
156:      * Permet de valider le formulaire avec un envoi javascript
157:      * @access public
158:      * @return boolean
159:      */
160:     public function isValid($post, $noSubmit = false)
161:     {
162:         if ($this->isSubmited($noSubmit) && Token::checkToken())
163:         {
164:             $valid = true;
165:             foreach ($this->champs as $objet) {
166:                 $nom        = $objet->getName();
167:                 if (strstr($nom, '[]')) // Cas des selection multiple
168:                     $nom        = substr($nom, 0, strlen($nom) - 2);
169:                 if (!isset($post[$nom]))
170:                     $post[$nom] = null;
171:                 $valid      = $objet->isValid($post[$nom]) && $valid;
172:             }
173:             return $valid;
174:         }
175:         return false;
176:     }
177: 
178:     /**
179:      * Ajoute un élément de formulaire
180:      *
181:      * @param string $type
182:      * @param string $nom
183:      * @access public
184:      * @return Form_Input
185:      */
186:     public function add($type, $nom)
187:     {
188:         if (!isset($this->champs[$nom]))
189:         {
190:             $classChamps = 'Pry\Form\Element\\' . $type;
191:             $oChamps     = new $classChamps($nom, $this);
192:             if ($type != 'Html')
193:             {
194:                 if ($type == 'Submit')
195:                     $this->champs_submit[$nom] = $oChamps;
196:                 elseif ($type == 'Hidden')
197:                     $this->champs_hidden[$nom] = $oChamps;
198: 
199:                 $this->champs[$nom]            = $oChamps;
200:             }
201:             else
202:                 $this->champs[$nom . uniqid()] = $oChamps;
203:             return $oChamps;
204:         }
205:         else
206:             throw new \UnexpectedValueException('Un champs avec le nom ' . $nom . ' existe déjà dans ' . $this->uniqid);
207:     }
208: 
209:     /**
210:      * Attribue une action
211:      *
212:      * @param string $action
213:      * @access public
214:      * @return Form_Form
215:      */
216:     public function action($action)
217:     {
218:         $this->attrs['action'] = $action;
219:         return $this;
220:     }
221: 
222:     /**
223:      * Setter d'attribut
224:      *
225:      * @param string $nom
226:      * @param string $valeur
227:      * @access public
228:      * @return Form_Form
229:      */
230:     public function setAttributes($nom, $valeur)
231:     {
232:         if (!isset($this->attrs[$nom]))
233:             $this->attrs[$nom] = $valeur;
234:         return $this;
235:     }
236: 
237:     /**
238:      * Enregistre les valeur poster pour réutilisation
239:      *
240:      * @param array $data
241:      * @access public
242:      * @return Form_Form
243:      */
244:     public function setPostedValue($data)
245:     {
246:         if (is_array($data))
247:         {
248:             foreach ($data as $name => $valeur) {
249:                 //var_dump($valeur);
250:                 $this->posted_value[$name] = $valeur;
251:             }
252:         }
253:         return $this;
254:     }
255: 
256:     /**
257:      * Récupère la valeur postée pour un élément
258:      *
259:      * @param string $name
260:      * @access public
261:      * @return string
262:      */
263:     public function getPostedvalue($name)
264:     {
265:         if (isset($this->posted_value[$name]))
266:             return $this->posted_value[$name];
267:         else
268:             return '';
269:     }
270: 
271:     /**
272:      * Attribue une méthode au formulaire
273:      *
274:      * @param string $method
275:      * @access public
276:      * @return Form_Form
277:      */
278:     public function method($method)
279:     {
280:         $method = strtolower($method);
281:         if (in_array($method, array('post', 'get')))
282:         {
283:             $this->attrs['method'] = $method;
284:             return $this;
285:         }
286:         else
287:             throw new \Exception('Merci d\'utiliser post ou get');
288:     }
289: 
290:     /**
291:      * Attribue un enctype au formulaire
292:      *
293:      * @param string $txt
294:      * @access public
295:      * @return Form_Form
296:      */
297:     public function enctype($txt)
298:     {
299:         if (in_array($txt, array('multipart/form-data', 'application/x-www-form-urlencoded')))
300:             $this->attrs['enctype'] = $txt;
301:         else
302:             throw new \InvalidArgumentException('Enctype non supporté.');
303:         return $this;
304:     }
305: 
306:     /**
307:      * Vérifie si le formulaire à bien été soumis
308:      * 
309:      * @access private
310:      * @param boolean $noSubmit true si aucun bouton submit
311:      * @return boolean
312:      */
313:     private function isSubmited($noSubmit)
314:     {
315:         $methode = ($this->attrs['method'] == 'post') ? $_POST : $_GET;
316:         if (!empty($methode['uniqid']) && $methode['uniqid'] == $this->uniqid)
317:         {
318:             if ($noSubmit)
319:                 return true;
320: 
321:             foreach ($this->champs_submit as $submit) {
322:                 if (isset($methode[$submit->getName()]))
323:                     return true;
324:             }
325:         }
326:         return false;
327:     }
328: 
329:     /**
330:      * Linéarise les attributs du formulaire
331:      * @access private
332:      * @return string
333:      */
334:     private function attrsToString()
335:     {
336:         $attributs = '';
337:         foreach ($this->attrs as $key => $value)
338:             $attributs .= $key . '="' . $value . '" ';
339: 
340:         return $attributs;
341:     }
342: 
343:     /**
344:      * Retourne une chaine des différents élément du formulaire
345:      * @access private
346:      * @return string
347:      */
348:     private function fieldsToString()
349:     {
350:         $champsTxt = '';
351:         foreach ($this->champs as $champ)
352:             $champsTxt .= $champ->__toString() . "\n";
353: 
354:         return $champsTxt;
355:     }
356: 
357:     /**
358:      * Ecriture du formulaire et ajout des appel JS
359:      * @access private
360:      * @return string
361:      */
362:     public function __toString()
363:     {
364:         $form = '<form ' . $this->attrsToString() . ' >' . "\n";
365:         $form.='<p>' . "\n";
366:         $form.= $this->fieldsToString();
367:         $form.='</p>' . "\n";
368:         $form.='</form>' . "\n";
369:         $form.='<script type="text/javascript" >' . "\n";
370:         $form .= '$(document).ready(function(){';
371:         if (!empty($this->javascript))
372:         {
373:             $form.= $this->javascript;
374:         }
375:         if (count($this->listTooltips) > 0)
376:         {
377:             $form.= '$(\'.form_tooltip\').tipTip();';
378:         }
379:         $form.='});';
380:         $form.='</script>' . "\n";
381:         return $form;
382:     }
383: 
384: }
385: 
386: ?>
Pry API documentation generated by ApiGen 2.8.0