Element.php 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Form
  17. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. */
  20. /** Zend_Filter */
  21. require_once 'Zend/Filter.php';
  22. /** Zend_Validate_Interface */
  23. require_once 'Zend/Validate/Interface.php';
  24. /**
  25. * Zend_Form_Element
  26. *
  27. * @category Zend
  28. * @package Zend_Form
  29. * @subpackage Element
  30. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  31. * @license http://framework.zend.com/license/new-bsd New BSD License
  32. * @version $Id$
  33. */
  34. class Zend_Form_Element implements Zend_Validate_Interface
  35. {
  36. /**
  37. * Element Constants
  38. */
  39. const DECORATOR = 'DECORATOR';
  40. const FILTER = 'FILTER';
  41. const VALIDATE = 'VALIDATE';
  42. /**
  43. * Default view helper to use
  44. * @var string
  45. */
  46. public $helper = 'formText';
  47. /**
  48. * 'Allow empty' flag
  49. * @var bool
  50. */
  51. protected $_allowEmpty = true;
  52. /**
  53. * Flag indicating whether or not to insert NotEmpty validator when element is required
  54. * @var bool
  55. */
  56. protected $_autoInsertNotEmptyValidator = true;
  57. /**
  58. * Array to which element belongs
  59. * @var string
  60. */
  61. protected $_belongsTo;
  62. /**
  63. * Element decorators
  64. * @var array
  65. */
  66. protected $_decorators = array();
  67. /**
  68. * Element description
  69. * @var string
  70. */
  71. protected $_description;
  72. /**
  73. * Should we disable loading the default decorators?
  74. * @var bool
  75. */
  76. protected $_disableLoadDefaultDecorators = false;
  77. /**
  78. * Custom error messages
  79. * @var array
  80. */
  81. protected $_errorMessages = array();
  82. /**
  83. * Validation errors
  84. * @var array
  85. */
  86. protected $_errors = array();
  87. /**
  88. * Element filters
  89. * @var array
  90. */
  91. protected $_filters = array();
  92. /**
  93. * Ignore flag (used when retrieving values at form level)
  94. * @var bool
  95. */
  96. protected $_ignore = false;
  97. /**
  98. * Does the element represent an array?
  99. * @var bool
  100. */
  101. protected $_isArray = false;
  102. /**
  103. * Is the error marked as in an invalid state?
  104. * @var bool
  105. */
  106. protected $_isError = false;
  107. /**
  108. * Has the element been manually marked as invalid?
  109. * @var bool
  110. */
  111. protected $_isErrorForced = false;
  112. /**
  113. * Element label
  114. * @var string
  115. */
  116. protected $_label;
  117. /**
  118. * Plugin loaders for filter and validator chains
  119. * @var array
  120. */
  121. protected $_loaders = array();
  122. /**
  123. * Formatted validation error messages
  124. * @var array
  125. */
  126. protected $_messages = array();
  127. /**
  128. * Element name
  129. * @var string
  130. */
  131. protected $_name;
  132. /**
  133. * Order of element
  134. * @var int
  135. */
  136. protected $_order;
  137. /**
  138. * Required flag
  139. * @var bool
  140. */
  141. protected $_required = false;
  142. /**
  143. * @var Zend_Translate
  144. */
  145. protected $_translator;
  146. /**
  147. * Is translation disabled?
  148. * @var bool
  149. */
  150. protected $_translatorDisabled = false;
  151. /**
  152. * Element type
  153. * @var string
  154. */
  155. protected $_type;
  156. /**
  157. * Array of initialized validators
  158. * @var array Validators
  159. */
  160. protected $_validators = array();
  161. /**
  162. * Array of un-initialized validators
  163. * @var array
  164. */
  165. protected $_validatorRules = array();
  166. /**
  167. * Element value
  168. * @var mixed
  169. */
  170. protected $_value;
  171. /**
  172. * @var Zend_View_Interface
  173. */
  174. protected $_view;
  175. /**
  176. * Constructor
  177. *
  178. * $spec may be:
  179. * - string: name of element
  180. * - array: options with which to configure element
  181. * - Zend_Config: Zend_Config with options for configuring element
  182. *
  183. * @param string|array|Zend_Config $spec
  184. * @return void
  185. * @throws Zend_Form_Exception if no element name after initialization
  186. */
  187. public function __construct($spec, $options = null)
  188. {
  189. if (is_string($spec)) {
  190. $this->setName($spec);
  191. } elseif (is_array($spec)) {
  192. $this->setOptions($spec);
  193. } elseif ($spec instanceof Zend_Config) {
  194. $this->setConfig($spec);
  195. }
  196. if (is_string($spec) && is_array($options)) {
  197. $this->setOptions($options);
  198. } elseif (is_string($spec) && ($options instanceof Zend_Config)) {
  199. $this->setConfig($options);
  200. }
  201. if (null === $this->getName()) {
  202. require_once 'Zend/Form/Exception.php';
  203. throw new Zend_Form_Exception('Zend_Form_Element requires each element to have a name');
  204. }
  205. /**
  206. * Extensions
  207. */
  208. $this->init();
  209. /**
  210. * Register ViewHelper decorator by default
  211. */
  212. $this->loadDefaultDecorators();
  213. }
  214. /**
  215. * Initialize object; used by extending classes
  216. *
  217. * @return void
  218. */
  219. public function init()
  220. {
  221. }
  222. /**
  223. * Set flag to disable loading default decorators
  224. *
  225. * @param bool $flag
  226. * @return Zend_Form_Element
  227. */
  228. public function setDisableLoadDefaultDecorators($flag)
  229. {
  230. $this->_disableLoadDefaultDecorators = (bool) $flag;
  231. return $this;
  232. }
  233. /**
  234. * Should we load the default decorators?
  235. *
  236. * @return bool
  237. */
  238. public function loadDefaultDecoratorsIsDisabled()
  239. {
  240. return $this->_disableLoadDefaultDecorators;
  241. }
  242. /**
  243. * Load default decorators
  244. *
  245. * @return void
  246. */
  247. public function loadDefaultDecorators()
  248. {
  249. if ($this->loadDefaultDecoratorsIsDisabled()) {
  250. return;
  251. }
  252. $decorators = $this->getDecorators();
  253. if (empty($decorators)) {
  254. $this->addDecorator('ViewHelper')
  255. ->addDecorator('Errors')
  256. ->addDecorator('Description', array('tag' => 'p', 'class' => 'description'))
  257. ->addDecorator('HtmlTag', array('tag' => 'dd',
  258. 'id' => $this->getName() . '-element'))
  259. ->addDecorator('Label', array('tag' => 'dt'));
  260. }
  261. }
  262. /**
  263. * Set object state from options array
  264. *
  265. * @param array $options
  266. * @return Zend_Form_Element
  267. */
  268. public function setOptions(array $options)
  269. {
  270. if (isset($options['prefixPath'])) {
  271. $this->addPrefixPaths($options['prefixPath']);
  272. unset($options['prefixPath']);
  273. }
  274. if (isset($options['disableTranslator'])) {
  275. $this->setDisableTranslator($options['disableTranslator']);
  276. unset($options['disableTranslator']);
  277. }
  278. unset($options['options']);
  279. unset($options['config']);
  280. foreach ($options as $key => $value) {
  281. $method = 'set' . ucfirst($key);
  282. if (in_array($method, array('setTranslator', 'setPluginLoader', 'setView'))) {
  283. if (!is_object($value)) {
  284. continue;
  285. }
  286. }
  287. if (method_exists($this, $method)) {
  288. // Setter exists; use it
  289. $this->$method($value);
  290. } else {
  291. // Assume it's metadata
  292. $this->setAttrib($key, $value);
  293. }
  294. }
  295. return $this;
  296. }
  297. /**
  298. * Set object state from Zend_Config object
  299. *
  300. * @param Zend_Config $config
  301. * @return Zend_Form_Element
  302. */
  303. public function setConfig(Zend_Config $config)
  304. {
  305. return $this->setOptions($config->toArray());
  306. }
  307. // Localization:
  308. /**
  309. * Set translator object for localization
  310. *
  311. * @param Zend_Translate|null $translator
  312. * @return Zend_Form_Element
  313. */
  314. public function setTranslator($translator = null)
  315. {
  316. if (null === $translator) {
  317. $this->_translator = null;
  318. } elseif ($translator instanceof Zend_Translate_Adapter) {
  319. $this->_translator = $translator;
  320. } elseif ($translator instanceof Zend_Translate) {
  321. $this->_translator = $translator->getAdapter();
  322. } else {
  323. require_once 'Zend/Form/Exception.php';
  324. throw new Zend_Form_Exception('Invalid translator specified');
  325. }
  326. return $this;
  327. }
  328. /**
  329. * Retrieve localization translator object
  330. *
  331. * @return Zend_Translate_Adapter|null
  332. */
  333. public function getTranslator()
  334. {
  335. if ($this->translatorIsDisabled()) {
  336. return null;
  337. }
  338. if (null === $this->_translator) {
  339. require_once 'Zend/Form.php';
  340. return Zend_Form::getDefaultTranslator();
  341. }
  342. return $this->_translator;
  343. }
  344. /**
  345. * Indicate whether or not translation should be disabled
  346. *
  347. * @param bool $flag
  348. * @return Zend_Form_Element
  349. */
  350. public function setDisableTranslator($flag)
  351. {
  352. $this->_translatorDisabled = (bool) $flag;
  353. return $this;
  354. }
  355. /**
  356. * Is translation disabled?
  357. *
  358. * @return bool
  359. */
  360. public function translatorIsDisabled()
  361. {
  362. return $this->_translatorDisabled;
  363. }
  364. // Metadata
  365. /**
  366. * Filter a name to only allow valid variable characters
  367. *
  368. * @param string $value
  369. * @param bool $allowBrackets
  370. * @return string
  371. */
  372. public function filterName($value, $allowBrackets = false)
  373. {
  374. $charset = '^a-zA-Z0-9_\x7f-\xff';
  375. if ($allowBrackets) {
  376. $charset .= '\[\]';
  377. }
  378. return preg_replace('/[' . $charset . ']/', '', (string) $value);
  379. }
  380. /**
  381. * Set element name
  382. *
  383. * @param string $name
  384. * @return Zend_Form_Element
  385. */
  386. public function setName($name)
  387. {
  388. $name = $this->filterName($name);
  389. if ('' === $name) {
  390. require_once 'Zend/Form/Exception.php';
  391. throw new Zend_Form_Exception('Invalid name provided; must contain only valid variable characters and be non-empty');
  392. }
  393. $this->_name = $name;
  394. return $this;
  395. }
  396. /**
  397. * Return element name
  398. *
  399. * @return string
  400. */
  401. public function getName()
  402. {
  403. return $this->_name;
  404. }
  405. /**
  406. * Get fully qualified name
  407. *
  408. * Places name as subitem of array and/or appends brackets.
  409. *
  410. * @return string
  411. */
  412. public function getFullyQualifiedName()
  413. {
  414. $name = $this->getName();
  415. if (null !== ($belongsTo = $this->getBelongsTo())) {
  416. $name = $belongsTo . '[' . $name . ']';
  417. }
  418. if ($this->isArray()) {
  419. $name .= '[]';
  420. }
  421. return $name;
  422. }
  423. /**
  424. * Get element id
  425. *
  426. * @return string
  427. */
  428. public function getId()
  429. {
  430. if (isset($this->id)) {
  431. return $this->id;
  432. }
  433. $id = $this->getFullyQualifiedName();
  434. // Bail early if no array notation detected
  435. if (!strstr($id, '[')) {
  436. return $id;
  437. }
  438. // Strip array notation
  439. if ('[]' == substr($id, -2)) {
  440. $id = substr($id, 0, strlen($id) - 2);
  441. }
  442. $id = str_replace('][', '-', $id);
  443. $id = str_replace(array(']', '['), '-', $id);
  444. $id = trim($id, '-');
  445. return $id;
  446. }
  447. /**
  448. * Set element value
  449. *
  450. * @param mixed $value
  451. * @return Zend_Form_Element
  452. */
  453. public function setValue($value)
  454. {
  455. $this->_value = $value;
  456. return $this;
  457. }
  458. /**
  459. * Filter a value
  460. *
  461. * @param string $value
  462. * @param string $key
  463. * @return void
  464. */
  465. protected function _filterValue(&$value, &$key)
  466. {
  467. foreach ($this->getFilters() as $filter) {
  468. $value = $filter->filter($value);
  469. }
  470. }
  471. /**
  472. * Retrieve filtered element value
  473. *
  474. * @return mixed
  475. */
  476. public function getValue()
  477. {
  478. $valueFiltered = $this->_value;
  479. if ($this->isArray() && is_array($valueFiltered)) {
  480. array_walk_recursive($valueFiltered, array($this, '_filterValue'));
  481. } else {
  482. $this->_filterValue($valueFiltered, $valueFiltered);
  483. }
  484. return $valueFiltered;
  485. }
  486. /**
  487. * Retrieve unfiltered element value
  488. *
  489. * @return mixed
  490. */
  491. public function getUnfilteredValue()
  492. {
  493. return $this->_value;
  494. }
  495. /**
  496. * Set element label
  497. *
  498. * @param string $label
  499. * @return Zend_Form_Element
  500. */
  501. public function setLabel($label)
  502. {
  503. $this->_label = (string) $label;
  504. return $this;
  505. }
  506. /**
  507. * Retrieve element label
  508. *
  509. * @return string
  510. */
  511. public function getLabel()
  512. {
  513. return $this->_label;
  514. }
  515. /**
  516. * Set element order
  517. *
  518. * @param int $order
  519. * @return Zend_Form_Element
  520. */
  521. public function setOrder($order)
  522. {
  523. $this->_order = (int) $order;
  524. return $this;
  525. }
  526. /**
  527. * Retrieve element order
  528. *
  529. * @return int
  530. */
  531. public function getOrder()
  532. {
  533. return $this->_order;
  534. }
  535. /**
  536. * Set required flag
  537. *
  538. * @param bool $flag Default value is true
  539. * @return Zend_Form_Element
  540. */
  541. public function setRequired($flag = true)
  542. {
  543. $this->_required = (bool) $flag;
  544. return $this;
  545. }
  546. /**
  547. * Is the element required?
  548. *
  549. * @return bool
  550. */
  551. public function isRequired()
  552. {
  553. return $this->_required;
  554. }
  555. /**
  556. * Set flag indicating whether a NotEmpty validator should be inserted when element is required
  557. *
  558. * @param bool $flag
  559. * @return Zend_Form_Element
  560. */
  561. public function setAutoInsertNotEmptyValidator($flag)
  562. {
  563. $this->_autoInsertNotEmptyValidator = (bool) $flag;
  564. return $this;
  565. }
  566. /**
  567. * Get flag indicating whether a NotEmpty validator should be inserted when element is required
  568. *
  569. * @return bool
  570. */
  571. public function autoInsertNotEmptyValidator()
  572. {
  573. return $this->_autoInsertNotEmptyValidator;
  574. }
  575. /**
  576. * Set element description
  577. *
  578. * @param string $description
  579. * @return Zend_Form_Element
  580. */
  581. public function setDescription($description)
  582. {
  583. $this->_description = (string) $description;
  584. return $this;
  585. }
  586. /**
  587. * Retrieve element description
  588. *
  589. * @return string
  590. */
  591. public function getDescription()
  592. {
  593. return $this->_description;
  594. }
  595. /**
  596. * Set 'allow empty' flag
  597. *
  598. * When the allow empty flag is enabled and the required flag is false, the
  599. * element will validate with empty values.
  600. *
  601. * @param bool $flag
  602. * @return Zend_Form_Element
  603. */
  604. public function setAllowEmpty($flag)
  605. {
  606. $this->_allowEmpty = (bool) $flag;
  607. return $this;
  608. }
  609. /**
  610. * Get 'allow empty' flag
  611. *
  612. * @return bool
  613. */
  614. public function getAllowEmpty()
  615. {
  616. return $this->_allowEmpty;
  617. }
  618. /**
  619. * Set ignore flag (used when retrieving values at form level)
  620. *
  621. * @param bool $flag
  622. * @return Zend_Form_Element
  623. */
  624. public function setIgnore($flag)
  625. {
  626. $this->_ignore = (bool) $flag;
  627. return $this;
  628. }
  629. /**
  630. * Get ignore flag (used when retrieving values at form level)
  631. *
  632. * @return bool
  633. */
  634. public function getIgnore()
  635. {
  636. return $this->_ignore;
  637. }
  638. /**
  639. * Set flag indicating if element represents an array
  640. *
  641. * @param bool $flag
  642. * @return Zend_Form_Element
  643. */
  644. public function setIsArray($flag)
  645. {
  646. $this->_isArray = (bool) $flag;
  647. return $this;
  648. }
  649. /**
  650. * Is the element representing an array?
  651. *
  652. * @return bool
  653. */
  654. public function isArray()
  655. {
  656. return $this->_isArray;
  657. }
  658. /**
  659. * Set array to which element belongs
  660. *
  661. * @param string $array
  662. * @return Zend_Form_Element
  663. */
  664. public function setBelongsTo($array)
  665. {
  666. $array = $this->filterName($array, true);
  667. if (!empty($array)) {
  668. $this->_belongsTo = $array;
  669. }
  670. return $this;
  671. }
  672. /**
  673. * Return array name to which element belongs
  674. *
  675. * @return string
  676. */
  677. public function getBelongsTo()
  678. {
  679. return $this->_belongsTo;
  680. }
  681. /**
  682. * Return element type
  683. *
  684. * @return string
  685. */
  686. public function getType()
  687. {
  688. if (null === $this->_type) {
  689. $this->_type = get_class($this);
  690. }
  691. return $this->_type;
  692. }
  693. /**
  694. * Set element attribute
  695. *
  696. * @param string $name
  697. * @param mixed $value
  698. * @return Zend_Form_Element
  699. * @throws Zend_Form_Exception for invalid $name values
  700. */
  701. public function setAttrib($name, $value)
  702. {
  703. $name = (string) $name;
  704. if ('_' == $name[0]) {
  705. require_once 'Zend/Form/Exception.php';
  706. throw new Zend_Form_Exception(sprintf('Invalid attribute "%s"; must not contain a leading underscore', $name));
  707. }
  708. if (null === $value) {
  709. unset($this->$name);
  710. } else {
  711. $this->$name = $value;
  712. }
  713. return $this;
  714. }
  715. /**
  716. * Set multiple attributes at once
  717. *
  718. * @param array $attribs
  719. * @return Zend_Form_Element
  720. */
  721. public function setAttribs(array $attribs)
  722. {
  723. foreach ($attribs as $key => $value) {
  724. $this->setAttrib($key, $value);
  725. }
  726. return $this;
  727. }
  728. /**
  729. * Retrieve element attribute
  730. *
  731. * @param string $name
  732. * @return string
  733. */
  734. public function getAttrib($name)
  735. {
  736. $name = (string) $name;
  737. if (isset($this->$name)) {
  738. return $this->$name;
  739. }
  740. return null;
  741. }
  742. /**
  743. * Return all attributes
  744. *
  745. * @return array
  746. */
  747. public function getAttribs()
  748. {
  749. $attribs = get_object_vars($this);
  750. foreach ($attribs as $key => $value) {
  751. if ('_' == substr($key, 0, 1)) {
  752. unset($attribs[$key]);
  753. }
  754. }
  755. return $attribs;
  756. }
  757. /**
  758. * Overloading: retrieve object property
  759. *
  760. * Prevents access to properties beginning with '_'.
  761. *
  762. * @param string $key
  763. * @return mixed
  764. */
  765. public function __get($key)
  766. {
  767. if ('_' == $key[0]) {
  768. require_once 'Zend/Form/Exception.php';
  769. throw new Zend_Form_Exception(sprintf('Cannot retrieve value for protected/private property "%s"', $key));
  770. }
  771. if (!isset($this->$key)) {
  772. return null;
  773. }
  774. return $this->$key;
  775. }
  776. /**
  777. * Overloading: set object property
  778. *
  779. * @param string $key
  780. * @param mixed $value
  781. * @return voide
  782. */
  783. public function __set($key, $value)
  784. {
  785. $this->setAttrib($key, $value);
  786. }
  787. /**
  788. * Overloading: allow rendering specific decorators
  789. *
  790. * Call renderDecoratorName() to render a specific decorator.
  791. *
  792. * @param string $method
  793. * @param array $args
  794. * @return string
  795. * @throws Zend_Form_Exception for invalid decorator or invalid method call
  796. */
  797. public function __call($method, $args)
  798. {
  799. if ('render' == substr($method, 0, 6)) {
  800. $decoratorName = substr($method, 6);
  801. if (false !== ($decorator = $this->getDecorator($decoratorName))) {
  802. $decorator->setElement($this);
  803. $seed = '';
  804. if (0 < count($args)) {
  805. $seed = array_shift($args);
  806. }
  807. return $decorator->render($seed);
  808. }
  809. require_once 'Zend/Form/Element/Exception.php';
  810. throw new Zend_Form_Element_Exception(sprintf('Decorator by name %s does not exist', $decoratorName));
  811. }
  812. require_once 'Zend/Form/Element/Exception.php';
  813. throw new Zend_Form_Element_Exception(sprintf('Method %s does not exist', $method));
  814. }
  815. // Loaders
  816. /**
  817. * Set plugin loader to use for validator or filter chain
  818. *
  819. * @param Zend_Loader_PluginLoader_Interface $loader
  820. * @param string $type 'decorator', 'filter', or 'validate'
  821. * @return Zend_Form_Element
  822. * @throws Zend_Form_Exception on invalid type
  823. */
  824. public function setPluginLoader(Zend_Loader_PluginLoader_Interface $loader, $type)
  825. {
  826. $type = strtoupper($type);
  827. switch ($type) {
  828. case self::DECORATOR:
  829. case self::FILTER:
  830. case self::VALIDATE:
  831. $this->_loaders[$type] = $loader;
  832. return $this;
  833. default:
  834. require_once 'Zend/Form/Exception.php';
  835. throw new Zend_Form_Exception(sprintf('Invalid type "%s" provided to setPluginLoader()', $type));
  836. }
  837. }
  838. /**
  839. * Retrieve plugin loader for validator or filter chain
  840. *
  841. * Instantiates with default rules if none available for that type. Use
  842. * 'decorator', 'filter', or 'validate' for $type.
  843. *
  844. * @param string $type
  845. * @return Zend_Loader_PluginLoader
  846. * @throws Zend_Loader_Exception on invalid type.
  847. */
  848. public function getPluginLoader($type)
  849. {
  850. $type = strtoupper($type);
  851. switch ($type) {
  852. case self::FILTER:
  853. case self::VALIDATE:
  854. $prefixSegment = ucfirst(strtolower($type));
  855. $pathSegment = $prefixSegment;
  856. case self::DECORATOR:
  857. if (!isset($prefixSegment)) {
  858. $prefixSegment = 'Form_Decorator';
  859. $pathSegment = 'Form/Decorator';
  860. }
  861. if (!isset($this->_loaders[$type])) {
  862. require_once 'Zend/Loader/PluginLoader.php';
  863. $this->_loaders[$type] = new Zend_Loader_PluginLoader(
  864. array('Zend_' . $prefixSegment . '_' => 'Zend/' . $pathSegment . '/')
  865. );
  866. }
  867. return $this->_loaders[$type];
  868. default:
  869. require_once 'Zend/Form/Exception.php';
  870. throw new Zend_Form_Exception(sprintf('Invalid type "%s" provided to getPluginLoader()', $type));
  871. }
  872. }
  873. /**
  874. * Add prefix path for plugin loader
  875. *
  876. * If no $type specified, assumes it is a base path for both filters and
  877. * validators, and sets each according to the following rules:
  878. * - decorators: $prefix = $prefix . '_Decorator'
  879. * - filters: $prefix = $prefix . '_Filter'
  880. * - validators: $prefix = $prefix . '_Validate'
  881. *
  882. * Otherwise, the path prefix is set on the appropriate plugin loader.
  883. *
  884. * @param string $prefix
  885. * @param string $path
  886. * @param string $type
  887. * @return Zend_Form_Element
  888. * @throws Zend_Form_Exception for invalid type
  889. */
  890. public function addPrefixPath($prefix, $path, $type = null)
  891. {
  892. $type = strtoupper($type);
  893. switch ($type) {
  894. case self::DECORATOR:
  895. case self::FILTER:
  896. case self::VALIDATE:
  897. $loader = $this->getPluginLoader($type);
  898. $loader->addPrefixPath($prefix, $path);
  899. return $this;
  900. case null:
  901. $prefix = rtrim($prefix, '_');
  902. $path = rtrim($path, DIRECTORY_SEPARATOR);
  903. foreach (array(self::DECORATOR, self::FILTER, self::VALIDATE) as $type) {
  904. $cType = ucfirst(strtolower($type));
  905. $pluginPath = $path . DIRECTORY_SEPARATOR . $cType . DIRECTORY_SEPARATOR;
  906. $pluginPrefix = $prefix . '_' . $cType;
  907. $loader = $this->getPluginLoader($type);
  908. $loader->addPrefixPath($pluginPrefix, $pluginPath);
  909. }
  910. return $this;
  911. default:
  912. require_once 'Zend/Form/Exception.php';
  913. throw new Zend_Form_Exception(sprintf('Invalid type "%s" provided to getPluginLoader()', $type));
  914. }
  915. }
  916. /**
  917. * Add many prefix paths at once
  918. *
  919. * @param array $spec
  920. * @return Zend_Form_Element
  921. */
  922. public function addPrefixPaths(array $spec)
  923. {
  924. if (isset($spec['prefix']) && isset($spec['path'])) {
  925. return $this->addPrefixPath($spec['prefix'], $spec['path']);
  926. }
  927. foreach ($spec as $type => $paths) {
  928. if (is_numeric($type) && is_array($paths)) {
  929. $type = null;
  930. if (isset($paths['prefix']) && isset($paths['path'])) {
  931. if (isset($paths['type'])) {
  932. $type = $paths['type'];
  933. }
  934. $this->addPrefixPath($paths['prefix'], $paths['path'], $type);
  935. }
  936. } elseif (!is_numeric($type)) {
  937. if (!isset($paths['prefix']) || !isset($paths['path'])) {
  938. foreach ($paths as $prefix => $spec) {
  939. if (is_array($spec)) {
  940. foreach ($spec as $path) {
  941. if (!is_string($path)) {
  942. continue;
  943. }
  944. $this->addPrefixPath($prefix, $path, $type);
  945. }
  946. } elseif (is_string($spec)) {
  947. $this->addPrefixPath($prefix, $spec, $type);
  948. }
  949. }
  950. } else {
  951. $this->addPrefixPath($paths['prefix'], $paths['path'], $type);
  952. }
  953. }
  954. }
  955. return $this;
  956. }
  957. // Validation
  958. /**
  959. * Add validator to validation chain
  960. *
  961. * Note: will overwrite existing validators if they are of the same class.
  962. *
  963. * @param string|Zend_Validate_Interface $validator
  964. * @param bool $breakChainOnFailure
  965. * @param array $options
  966. * @return Zend_Form_Element
  967. * @throws Zend_Form_Exception if invalid validator type
  968. */
  969. public function addValidator($validator, $breakChainOnFailure = false, $options = array())
  970. {
  971. if ($validator instanceof Zend_Validate_Interface) {
  972. $name = get_class($validator);
  973. if (!isset($validator->zfBreakChainOnFailure)) {
  974. $validator->zfBreakChainOnFailure = $breakChainOnFailure;
  975. }
  976. } elseif (is_string($validator)) {
  977. $name = $validator;
  978. $validator = array(
  979. 'validator' => $validator,
  980. 'breakChainOnFailure' => $breakChainOnFailure,
  981. 'options' => $options,
  982. );
  983. } else {
  984. require_once 'Zend/Form/Exception.php';
  985. throw new Zend_Form_Exception('Invalid validator provided to addValidator; must be string or Zend_Validate_Interface');
  986. }
  987. $this->_validators[$name] = $validator;
  988. return $this;
  989. }
  990. /**
  991. * Add multiple validators
  992. *
  993. * @param array $validators
  994. * @return Zend_Form_Element
  995. */
  996. public function addValidators(array $validators)
  997. {
  998. foreach ($validators as $validatorInfo) {
  999. if (is_string($validatorInfo)) {
  1000. $this->addValidator($validatorInfo);
  1001. } elseif ($validatorInfo instanceof Zend_Validate_Interface) {
  1002. $this->addValidator($validatorInfo);
  1003. } elseif (is_array($validatorInfo)) {
  1004. $argc = count($validatorInfo);
  1005. $breakChainOnFailure = false;
  1006. $options = array();
  1007. if (isset($validatorInfo['validator'])) {
  1008. $validator = $validatorInfo['validator'];
  1009. if (isset($validatorInfo['breakChainOnFailure'])) {
  1010. $breakChainOnFailure = $validatorInfo['breakChainOnFailure'];
  1011. }
  1012. if (isset($validatorInfo['options'])) {
  1013. $options = $validatorInfo['options'];
  1014. }
  1015. $this->addValidator($validator, $breakChainOnFailure, $options);
  1016. } else {
  1017. switch (true) {
  1018. case (0 == $argc):
  1019. break;
  1020. case (1 <= $argc):
  1021. $validator = array_shift($validatorInfo);
  1022. case (2 <= $argc):
  1023. $breakChainOnFailure = array_shift($validatorInfo);
  1024. case (3 <= $argc):
  1025. $options = array_shift($validatorInfo);
  1026. default:
  1027. $this->addValidator($validator, $breakChainOnFailure, $options);
  1028. break;
  1029. }
  1030. }
  1031. } else {
  1032. require_once 'Zend/Form/Exception.php';
  1033. throw new Zend_Form_Exception('Invalid validator passed to addValidators()');
  1034. }
  1035. }
  1036. return $this;
  1037. }
  1038. /**
  1039. * Set multiple validators, overwriting previous validators
  1040. *
  1041. * @param array $validators
  1042. * @return Zend_Form_Element
  1043. */
  1044. public function setValidators(array $validators)
  1045. {
  1046. $this->clearValidators();
  1047. return $this->addValidators($validators);
  1048. }
  1049. /**
  1050. * Retrieve a single validator by name
  1051. *
  1052. * @param string $name
  1053. * @return Zend_Validate_Interface|false False if not found, validator otherwise
  1054. */
  1055. public function getValidator($name)
  1056. {
  1057. if (!isset($this->_validators[$name])) {
  1058. $len = strlen($name);
  1059. foreach ($this->_validators as $localName => $validator) {
  1060. if ($len > strlen($localName)) {
  1061. continue;
  1062. }
  1063. if (0 === substr_compare($localName, $name, -$len, $len, true)) {
  1064. if (is_array($validator)) {
  1065. return $this->_loadValidator($validator);
  1066. }
  1067. return $validator;
  1068. }
  1069. }
  1070. return false;
  1071. }
  1072. if (is_array($this->_validators[$name])) {
  1073. return $this->_loadValidator($this->_validators[$name]);
  1074. }
  1075. return $this->_validators[$name];
  1076. }
  1077. /**
  1078. * Retrieve all validators
  1079. *
  1080. * @return array
  1081. */
  1082. public function getValidators()
  1083. {
  1084. $validators = array();
  1085. foreach ($this->_validators as $key => $value) {
  1086. if ($value instanceof Zend_Validate_Interface) {
  1087. $validators[$key] = $value;
  1088. continue;
  1089. }
  1090. $validator = $this->_loadValidator($value);
  1091. $validators[get_class($validator)] = $validator;
  1092. }
  1093. return $validators;
  1094. }
  1095. /**
  1096. * Remove a single validator by name
  1097. *
  1098. * @param string $name
  1099. * @return bool
  1100. */
  1101. public function removeValidator($name)
  1102. {
  1103. if (isset($this->_validators[$name])) {
  1104. unset($this->_validators[$name]);
  1105. } else {
  1106. $len = strlen($name);
  1107. foreach (array_keys($this->_validators) as $validator) {
  1108. if ($len > strlen($validator)) {
  1109. continue;
  1110. }
  1111. if (0 === substr_compare($validator, $name, -$len, $len, true)) {
  1112. unset($this->_validators[$validator]);
  1113. break;
  1114. }
  1115. }
  1116. }
  1117. return $this;
  1118. }
  1119. /**
  1120. * Clear all validators
  1121. *
  1122. * @return Zend_Form_Element
  1123. */
  1124. public function clearValidators()
  1125. {
  1126. $this->_validators = array();
  1127. return $this;
  1128. }
  1129. /**
  1130. * Validate element value
  1131. *
  1132. * If a translation adapter is registered, any error messages will be
  1133. * translated according to the current locale, using the given error code;
  1134. * if no matching translation is found, the original message will be
  1135. * utilized.
  1136. *
  1137. * Note: The *filtered* value is validated.
  1138. *
  1139. * @param mixed $value
  1140. * @param mixed $context
  1141. * @return boolean
  1142. */
  1143. public function isValid($value, $context = null)
  1144. {
  1145. $this->setValue($value);
  1146. $value = $this->getValue();
  1147. if ((('' === $value) || (null === $value))
  1148. && !$this->isRequired()
  1149. && $this->getAllowEmpty()
  1150. ) {
  1151. return true;
  1152. }
  1153. if ($this->isRequired()
  1154. && $this->autoInsertNotEmptyValidator()
  1155. && !$this->getValidator('NotEmpty'))
  1156. {
  1157. $validators = $this->getValidators();
  1158. $notEmpty = array('validator' => 'NotEmpty', 'breakChainOnFailure' => true);
  1159. array_unshift($validators, $notEmpty);
  1160. $this->setValidators($validators);
  1161. }
  1162. $this->_messages = array();
  1163. $this->_errors = array();
  1164. $result = true;
  1165. $translator = $this->getTranslator();
  1166. $isArray = $this->isArray();
  1167. foreach ($this->getValidators() as $key => $validator) {
  1168. if (method_exists($validator, 'setTranslator')) {
  1169. $validator->setTranslator($translator);
  1170. }
  1171. if ($isArray && is_array($value)) {
  1172. $messages = array();
  1173. $errors = array();
  1174. foreach ($value as $val) {
  1175. if (!$validator->isValid($val, $context)) {
  1176. $result = false;
  1177. if ($this->_hasErrorMessages()) {
  1178. $messages = $this->_getErrorMessages();
  1179. $errors = $messages;
  1180. } else {
  1181. $messages = array_merge($messages, $validator->getMessages());
  1182. $errors = array_merge($errors, $validator->getErrors());
  1183. }
  1184. }
  1185. }
  1186. if ($result) {
  1187. continue;
  1188. }
  1189. } elseif ($validator->isValid($value, $context)) {
  1190. continue;
  1191. } else {
  1192. $result = false;
  1193. if ($this->_hasErrorMessages()) {
  1194. $messages = $this->_getErrorMessages();
  1195. $errors = $messages;
  1196. } else {
  1197. $messages = $validator->getMessages();
  1198. $errors = array_keys($messages);
  1199. }
  1200. }
  1201. $result = false;
  1202. $this->_messages = array_merge($this->_messages, $messages);
  1203. $this->_errors = array_merge($this->_errors, $errors);
  1204. if ($validator->zfBreakChainOnFailure) {
  1205. break;
  1206. }
  1207. }
  1208. // If element manually flagged as invalid, return false
  1209. if ($this->_isErrorForced) {
  1210. return false;
  1211. }
  1212. return $result;
  1213. }
  1214. /**
  1215. * Add a custom error message to return in the event of failed validation
  1216. *
  1217. * @param string $message
  1218. * @return Zend_Form_Element
  1219. */
  1220. public function addErrorMessage($message)
  1221. {
  1222. $this->_errorMessages[] = (string) $message;
  1223. return $this;
  1224. }
  1225. /**
  1226. * Add multiple custom error messages to return in the event of failed validation
  1227. *
  1228. * @param array $messages
  1229. * @return Zend_Form_Element
  1230. */
  1231. public function addErrorMessages(array $messages)
  1232. {
  1233. foreach ($messages as $message) {
  1234. $this->addErrorMessage($message);
  1235. }
  1236. return $this;
  1237. }
  1238. /**
  1239. * Same as addErrorMessages(), but clears custom error message stack first
  1240. *
  1241. * @param array $messages
  1242. * @return Zend_Form_Element
  1243. */
  1244. public function setErrorMessages(array $messages)
  1245. {
  1246. $this->clearErrorMessages();
  1247. return $this->addErrorMessages($messages);
  1248. }
  1249. /**
  1250. * Retrieve custom error messages
  1251. *
  1252. * @return array
  1253. */
  1254. public function getErrorMessages()
  1255. {
  1256. return $this->_errorMessages;
  1257. }
  1258. /**
  1259. * Clear custom error messages stack
  1260. *
  1261. * @return Zend_Form_Element
  1262. */
  1263. public function clearErrorMessages()
  1264. {
  1265. $this->_errorMessages = array();
  1266. return $this;
  1267. }
  1268. /**
  1269. * Mark the element as being in a failed validation state
  1270. *
  1271. * @return Zend_Form_Element
  1272. */
  1273. public function markAsError()
  1274. {
  1275. $messages = $this->getMessages();
  1276. $customMessages = $this->_getErrorMessages();
  1277. $messages = $messages + $customMessages;
  1278. if (empty($messages)) {
  1279. $this->_isError = true;
  1280. } else {
  1281. $this->_messages = $messages;
  1282. }
  1283. $this->_isErrorForced = true;
  1284. return $this;
  1285. }
  1286. /**
  1287. * Add an error message and mark element as failed validation
  1288. *
  1289. * @param string $message
  1290. * @return Zend_Form_Element
  1291. */
  1292. public function addError($message)
  1293. {
  1294. $this->addErrorMessage($message);
  1295. $this->markAsError();
  1296. return $this;
  1297. }
  1298. /**
  1299. * Add multiple error messages and flag element as failed validation
  1300. *
  1301. * @param array $messages
  1302. * @return Zend_Form_Element
  1303. */
  1304. public function addErrors(array $messages)
  1305. {
  1306. foreach ($messages as $message) {
  1307. $this->addError($message);
  1308. }
  1309. return $this;
  1310. }
  1311. /**
  1312. * Overwrite any previously set error messages and flag as failed validation
  1313. *
  1314. * @param array $messages
  1315. * @return Zend_Form_Element
  1316. */
  1317. public function setErrors(array $messages)
  1318. {
  1319. $this->clearErrorMessages();
  1320. return $this->addErrors($messages);
  1321. }
  1322. /**
  1323. * Are there errors registered?
  1324. *
  1325. * @return bool
  1326. */
  1327. public function hasErrors()
  1328. {
  1329. return (!empty($this->_messages) || $this->_isError);
  1330. }
  1331. /**
  1332. * Retrieve validator chain errors
  1333. *
  1334. * @return array
  1335. */
  1336. public function getErrors()
  1337. {
  1338. return $this->_errors;
  1339. }
  1340. /**
  1341. * Retrieve error messages
  1342. *
  1343. * @return array
  1344. */
  1345. public function getMessages()
  1346. {
  1347. return $this->_messages;
  1348. }
  1349. // Filtering
  1350. /**
  1351. * Add a filter to the element
  1352. *
  1353. * @param string|Zend_Filter_Interface $filter
  1354. * @return Zend_Form_Element
  1355. */
  1356. public function addFilter($filter, $options = array())
  1357. {
  1358. if ($filter instanceof Zend_Filter_Interface) {
  1359. $name = get_class($filter);
  1360. } elseif (is_string($filter)) {
  1361. $name = $filter;
  1362. $filter = array(
  1363. 'filter' => $filter,
  1364. 'options' => $options,
  1365. );
  1366. $this->_filters[$name] = $filter;
  1367. } else {
  1368. require_once 'Zend/Form/Exception.php';
  1369. throw new Zend_Form_Exception('Invalid filter provided to addFilter; must be string or Zend_Filter_Interface');
  1370. }
  1371. $this->_filters[$name] = $filter;
  1372. return $this;
  1373. }
  1374. /**
  1375. * Add filters to element
  1376. *
  1377. * @param array $filters
  1378. * @return Zend_Form_Element
  1379. */
  1380. public function addFilters(array $filters)
  1381. {
  1382. foreach ($filters as $filterInfo) {
  1383. if (is_string($filterInfo)) {
  1384. $this->addFilter($filterInfo);
  1385. } elseif ($filterInfo instanceof Zend_Filter_Interface) {
  1386. $this->addFilter($filterInfo);
  1387. } elseif (is_array($filterInfo)) {
  1388. $argc = count($filterInfo);
  1389. $options = array();
  1390. if (isset($filterInfo['filter'])) {
  1391. $filter = $filterInfo['filter'];
  1392. if (isset($filterInfo['options'])) {
  1393. $options = $filterInfo['options'];
  1394. }
  1395. $this->addFilter($filter, $options);
  1396. } else {
  1397. switch (true) {
  1398. case (0 == $argc):
  1399. break;
  1400. case (1 <= $argc):
  1401. $filter = array_shift($filterInfo);
  1402. case (2 <= $argc):
  1403. $options = array_shift($filterInfo);
  1404. default:
  1405. $this->addFilter($filter, $options);
  1406. break;
  1407. }
  1408. }
  1409. } else {
  1410. require_once 'Zend/Form/Exception.php';
  1411. throw new Zend_Form_Exception('Invalid filter passed to addFilters()');
  1412. }
  1413. }
  1414. return $this;
  1415. }
  1416. /**
  1417. * Add filters to element, overwriting any already existing
  1418. *
  1419. * @param array $filters
  1420. * @return Zend_Form_Element
  1421. */
  1422. public function setFilters(array $filters)
  1423. {
  1424. $this->clearFilters();
  1425. return $this->addFilters($filters);
  1426. }
  1427. /**
  1428. * Retrieve a single filter by name
  1429. *
  1430. * @param string $name
  1431. * @return Zend_Filter_Interface
  1432. */
  1433. public function getFilter($name)
  1434. {
  1435. if (!isset($this->_filters[$name])) {
  1436. $len = strlen($name);
  1437. foreach ($this->_filters as $localName => $filter) {
  1438. if ($len > strlen($localName)) {
  1439. continue;
  1440. }
  1441. if (0 === substr_compare($localName, $name, -$len, $len, true)) {
  1442. if (is_array($filter)) {
  1443. return $this->_loadFilter($filter);
  1444. }
  1445. return $filter;
  1446. }
  1447. }
  1448. return false;
  1449. }
  1450. if (is_array($this->_filters[$name])) {
  1451. return $this->_loadFilter($this->_filters[$name]);
  1452. }
  1453. return $this->_filters[$name];
  1454. }
  1455. /**
  1456. * Get all filters
  1457. *
  1458. * @return array
  1459. */
  1460. public function getFilters()
  1461. {
  1462. $filters = array();
  1463. foreach ($this->_filters as $key => $value) {
  1464. if ($value instanceof Zend_Filter_Interface) {
  1465. $filters[$key] = $value;
  1466. continue;
  1467. }
  1468. $filter = $this->_loadFilter($value);
  1469. $filters[get_class($filter)] = $filter;
  1470. }
  1471. return $filters;
  1472. }
  1473. /**
  1474. * Remove a filter by name
  1475. *
  1476. * @param string $name
  1477. * @return Zend_Form_Element
  1478. */
  1479. public function removeFilter($name)
  1480. {
  1481. if (isset($this->_filters[$name])) {
  1482. unset($this->_filters[$name]);
  1483. } else {
  1484. $len = strlen($name);
  1485. foreach (array_keys($this->_filters) as $filter) {
  1486. if ($len > strlen($filter)) {
  1487. continue;
  1488. }
  1489. if (0 === substr_compare($filter, $name, -$len, $len, true)) {
  1490. unset($this->_filters[$filter]);
  1491. break;
  1492. }
  1493. }
  1494. }
  1495. return $this;
  1496. }
  1497. /**
  1498. * Clear all filters
  1499. *
  1500. * @return Zend_Form_Element
  1501. */
  1502. public function clearFilters()
  1503. {
  1504. $this->_filters = array();
  1505. return $this;
  1506. }
  1507. // Rendering
  1508. /**
  1509. * Set view object
  1510. *
  1511. * @param Zend_View_Interface $view
  1512. * @return Zend_Form_Element
  1513. */
  1514. public function setView(Zend_View_Interface $view = null)
  1515. {
  1516. $this->_view = $view;
  1517. return $this;
  1518. }
  1519. /**
  1520. * Retrieve view object
  1521. *
  1522. * Retrieves from ViewRenderer if none previously set.
  1523. *
  1524. * @return null|Zend_View_Interface
  1525. */
  1526. public function getView()
  1527. {
  1528. if (null === $this->_view) {
  1529. require_once 'Zend/Controller/Action/HelperBroker.php';
  1530. $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
  1531. $this->setView($viewRenderer->view);
  1532. }
  1533. return $this->_view;
  1534. }
  1535. /**
  1536. * Instantiate a decorator based on class name or class name fragment
  1537. *
  1538. * @param string $name
  1539. * @param null|array $options
  1540. * @return Zend_Form_Decorator_Interface
  1541. */
  1542. protected function _getDecorator($name, $options)
  1543. {
  1544. $class = $this->getPluginLoader(self::DECORATOR)->load($name);
  1545. if (null === $options) {
  1546. $decorator = new $class;
  1547. } else {
  1548. $decorator = new $class($options);
  1549. }
  1550. return $decorator;
  1551. }
  1552. /**
  1553. * Add a decorator for rendering the element
  1554. *
  1555. * @param string|Zend_Form_Decorator_Interface $decorator
  1556. * @param array|Zend_Config $options Options with which to initialize decorator
  1557. * @return Zend_Form_Element
  1558. */
  1559. public function addDecorator($decorator, $options = null)
  1560. {
  1561. if ($decorator instanceof Zend_Form_Decorator_Interface) {
  1562. $name = get_class($decorator);
  1563. } elseif (is_string($decorator)) {
  1564. $name = $decorator;
  1565. $decorator = array(
  1566. 'decorator' => $name,
  1567. 'options' => $options,
  1568. );
  1569. } elseif (is_array($decorator)) {
  1570. foreach ($decorator as $name => $spec) {
  1571. break;
  1572. }
  1573. if (is_numeric($name)) {
  1574. require_once 'Zend/Form/Exception.php';
  1575. throw new Zend_Form_Exception('Invalid alias provided to addDecorator; must be alphanumeric string');
  1576. }
  1577. if (is_string($spec)) {
  1578. $decorator = array(
  1579. 'decorator' => $spec,
  1580. 'options' => $options,
  1581. );
  1582. } elseif ($spec instanceof Zend_Form_Decorator_Interface) {
  1583. $decorator = $spec;
  1584. }
  1585. } else {
  1586. require_once 'Zend/Form/Exception.php';
  1587. throw new Zend_Form_Exception('Invalid decorator provided to addDecorator; must be string or Zend_Form_Decorator_Interface');
  1588. }
  1589. $this->_decorators[$name] = $decorator;
  1590. return $this;
  1591. }
  1592. /**
  1593. * Add many decorators at once
  1594. *
  1595. * @param array $decorators
  1596. * @return Zend_Form_Element
  1597. */
  1598. public function addDecorators(array $decorators)
  1599. {
  1600. foreach ($decorators as $decoratorInfo) {
  1601. if (is_string($decoratorInfo)) {
  1602. $this->addDecorator($decoratorInfo);
  1603. } elseif ($decoratorInfo instanceof Zend_Form_Decorator_Interface) {
  1604. $this->addDecorator($decoratorInfo);
  1605. } elseif (is_array($decoratorInfo)) {
  1606. $argc = count($decoratorInfo);
  1607. $options = array();
  1608. if (isset($decoratorInfo['decorator'])) {
  1609. $decorator = $decoratorInfo['decorator'];
  1610. if (isset($decoratorInfo['options'])) {
  1611. $options = $decoratorInfo['options'];
  1612. }
  1613. $this->addDecorator($decorator, $options);
  1614. } else {
  1615. switch (true) {
  1616. case (0 == $argc):
  1617. break;
  1618. case (1 <= $argc):
  1619. $decorator = array_shift($decoratorInfo);
  1620. case (2 <= $argc):
  1621. $options = array_shift($decoratorInfo);
  1622. default:
  1623. $this->addDecorator($decorator, $options);
  1624. break;
  1625. }
  1626. }
  1627. } else {
  1628. require_once 'Zend/Form/Exception.php';
  1629. throw new Zend_Form_Exception('Invalid decorator passed to addDecorators()');
  1630. }
  1631. }
  1632. return $this;
  1633. }
  1634. /**
  1635. * Overwrite all decorators
  1636. *
  1637. * @param array $decorators
  1638. * @return Zend_Form_Element
  1639. */
  1640. public function setDecorators(array $decorators)
  1641. {
  1642. $this->clearDecorators();
  1643. return $this->addDecorators($decorators);
  1644. }
  1645. /**
  1646. * Retrieve a registered decorator
  1647. *
  1648. * @param string $name
  1649. * @return false|Zend_Form_Decorator_Abstract
  1650. */
  1651. public function getDecorator($name)
  1652. {
  1653. if (!isset($this->_decorators[$name])) {
  1654. $len = strlen($name);
  1655. foreach ($this->_decorators as $localName => $decorator) {
  1656. if ($len > strlen($localName)) {
  1657. continue;
  1658. }
  1659. if (0 === substr_compare($localName, $name, -$len, $len, true)) {
  1660. if (is_array($decorator)) {
  1661. return $this->_loadDecorator($decorator, $localName);
  1662. }
  1663. return $decorator;
  1664. }
  1665. }
  1666. return false;
  1667. }
  1668. if (is_array($this->_decorators[$name])) {
  1669. return $this->_loadDecorator($this->_decorators[$name], $name);
  1670. }
  1671. return $this->_decorators[$name];
  1672. }
  1673. /**
  1674. * Retrieve all decorators
  1675. *
  1676. * @return array
  1677. */
  1678. public function getDecorators()
  1679. {
  1680. foreach ($this->_decorators as $key => $value) {
  1681. if (is_array($value)) {
  1682. $this->_loadDecorator($value, $key);
  1683. }
  1684. }
  1685. return $this->_decorators;
  1686. }
  1687. /**
  1688. * Remove a single decorator
  1689. *
  1690. * @param string $name
  1691. * @return Zend_Form_Element
  1692. */
  1693. public function removeDecorator($name)
  1694. {
  1695. if (isset($this->_decorators[$name])) {
  1696. unset($this->_decorators[$name]);
  1697. } else {
  1698. $len = strlen($name);
  1699. foreach (array_keys($this->_decorators) as $decorator) {
  1700. if ($len > strlen($decorator)) {
  1701. continue;
  1702. }
  1703. if (0 === substr_compare($decorator, $name, -$len, $len, true)) {
  1704. unset($this->_decorators[$decorator]);
  1705. break;
  1706. }
  1707. }
  1708. }
  1709. return $this;
  1710. }
  1711. /**
  1712. * Clear all decorators
  1713. *
  1714. * @return Zend_Form_Element
  1715. */
  1716. public function clearDecorators()
  1717. {
  1718. $this->_decorators = array();
  1719. return $this;
  1720. }
  1721. /**
  1722. * Render form element
  1723. *
  1724. * @param Zend_View_Interface $view
  1725. * @return string
  1726. */
  1727. public function render(Zend_View_Interface $view = null)
  1728. {
  1729. if (null !== $view) {
  1730. $this->setView($view);
  1731. }
  1732. $content = '';
  1733. foreach ($this->getDecorators() as $decorator) {
  1734. $decorator->setElement($this);
  1735. $content = $decorator->render($content);
  1736. }
  1737. return $content;
  1738. }
  1739. /**
  1740. * String representation of form element
  1741. *
  1742. * Proxies to {@link render()}.
  1743. *
  1744. * @return string
  1745. */
  1746. public function __toString()
  1747. {
  1748. try {
  1749. $return = $this->render();
  1750. return $return;
  1751. } catch (Exception $e) {
  1752. trigger_error($e->getMessage(), E_USER_WARNING);
  1753. return '';
  1754. }
  1755. }
  1756. /**
  1757. * Lazy-load a filter
  1758. *
  1759. * @param array $filter
  1760. * @return Zend_Filter_Interface
  1761. */
  1762. protected function _loadFilter(array $filter)
  1763. {
  1764. $origName = $filter['filter'];
  1765. $name = $this->getPluginLoader(self::FILTER)->load($filter['filter']);
  1766. if (array_key_exists($name, $this->_filters)) {
  1767. require_once 'Zend/Form/Exception.php';
  1768. throw new Zend_Form_Exception(sprintf('Filter instance already exists for filter "%s"', $origName));
  1769. }
  1770. if (empty($filter['options'])) {
  1771. $instance = new $name;
  1772. } else {
  1773. $r = new ReflectionClass($name);
  1774. if ($r->hasMethod('__construct')) {
  1775. $instance = $r->newInstanceArgs((array) $filter['options']);
  1776. } else {
  1777. $instance = $r->newInstance();
  1778. }
  1779. }
  1780. if ($origName != $name) {
  1781. $filterNames = array_keys($this->_filters);
  1782. $order = array_flip($filterNames);
  1783. $order[$name] = $order[$origName];
  1784. $filtersExchange = array();
  1785. unset($order[$origName]);
  1786. asort($order);
  1787. foreach ($order as $key => $index) {
  1788. if ($key == $name) {
  1789. $filtersExchange[$key] = $instance;
  1790. continue;
  1791. }
  1792. $filtersExchange[$key] = $this->_filters[$key];
  1793. }
  1794. $this->_filters = $filtersExchange;
  1795. } else {
  1796. $this->_filters[$name] = $instance;
  1797. }
  1798. return $instance;
  1799. }
  1800. /**
  1801. * Lazy-load a validator
  1802. *
  1803. * @param array $validator Validator definition
  1804. * @return Zend_Validate_Interface
  1805. */
  1806. protected function _loadValidator(array $validator)
  1807. {
  1808. $origName = $validator['validator'];
  1809. $name = $this->getPluginLoader(self::VALIDATE)->load($validator['validator']);
  1810. if (array_key_exists($name, $this->_validators)) {
  1811. require_once 'Zend/Form/Exception.php';
  1812. throw new Zend_Form_Exception(sprintf('Validator instance already exists for validator "%s"', $origName));
  1813. }
  1814. if (empty($validator['options'])) {
  1815. $instance = new $name;
  1816. } else {
  1817. $messages = false;
  1818. if (isset($validator['options']['messages'])) {
  1819. $messages = $validator['options']['messages'];
  1820. unset($validator['options']['messages']);
  1821. }
  1822. $r = new ReflectionClass($name);
  1823. if ($r->hasMethod('__construct')) {
  1824. $numeric = false;
  1825. if (is_array($validator['options'])) {
  1826. $keys = array_keys($validator['options']);
  1827. foreach($keys as $key) {
  1828. if (is_numeric($key)) {
  1829. $numeric = true;
  1830. break;
  1831. }
  1832. }
  1833. }
  1834. if ($numeric) {
  1835. $instance = $r->newInstanceArgs((array) $validator['options']);
  1836. } else {
  1837. $instance = $r->newInstance($validator['options']);
  1838. }
  1839. } else {
  1840. $instance = $r->newInstance();
  1841. }
  1842. if ($messages) {
  1843. if (is_array($messages)) {
  1844. $instance->setMessages($messages);
  1845. } elseif (is_string($messages)) {
  1846. $instance->setMessage($messages);
  1847. }
  1848. }
  1849. }
  1850. $instance->zfBreakChainOnFailure = $validator['breakChainOnFailure'];
  1851. if ($origName != $name) {
  1852. $validatorNames = array_keys($this->_validators);
  1853. $order = array_flip($validatorNames);
  1854. $order[$name] = $order[$origName];
  1855. $validatorsExchange = array();
  1856. unset($order[$origName]);
  1857. asort($order);
  1858. foreach ($order as $key => $index) {
  1859. if ($key == $name) {
  1860. $validatorsExchange[$key] = $instance;
  1861. continue;
  1862. }
  1863. $validatorsExchange[$key] = $this->_validators[$key];
  1864. }
  1865. $this->_validators = $validatorsExchange;
  1866. } else {
  1867. $this->_validators[$name] = $instance;
  1868. }
  1869. return $instance;
  1870. }
  1871. /**
  1872. * Lazy-load a decorator
  1873. *
  1874. * @param array $decorator Decorator type and options
  1875. * @param mixed $name Decorator name or alias
  1876. * @return Zend_Form_Decorator_Interface
  1877. */
  1878. protected function _loadDecorator(array $decorator, $name)
  1879. {
  1880. $sameName = false;
  1881. if ($name == $decorator['decorator']) {
  1882. $sameName = true;
  1883. }
  1884. $instance = $this->_getDecorator($decorator['decorator'], $decorator['options']);
  1885. if ($sameName) {
  1886. $newName = get_class($instance);
  1887. $decoratorNames = array_keys($this->_decorators);
  1888. $order = array_flip($decoratorNames);
  1889. $order[$newName] = $order[$name];
  1890. $decoratorsExchange = array();
  1891. unset($order[$name]);
  1892. asort($order);
  1893. foreach ($order as $key => $index) {
  1894. if ($key == $newName) {
  1895. $decoratorsExchange[$key] = $instance;
  1896. continue;
  1897. }
  1898. $decoratorsExchange[$key] = $this->_decorators[$key];
  1899. }
  1900. $this->_decorators = $decoratorsExchange;
  1901. } else {
  1902. $this->_decorators[$name] = $instance;
  1903. }
  1904. return $instance;
  1905. }
  1906. /**
  1907. * Retrieve error messages and perform translation and value substitution
  1908. *
  1909. * @return array
  1910. */
  1911. protected function _getErrorMessages()
  1912. {
  1913. $translator = $this->getTranslator();
  1914. $messages = $this->getErrorMessages();
  1915. $value = $this->getValue();
  1916. foreach ($messages as $key => $message) {
  1917. if (null !== $translator) {
  1918. $message = $translator->translate($message);
  1919. }
  1920. if ($this->isArray() || is_array($value)) {
  1921. $aggregateMessages = array();
  1922. foreach ($value as $val) {
  1923. $aggregateMessages[] = str_replace('%value%', $val, $message);
  1924. }
  1925. $messages[$key] = $aggregateMessages;
  1926. } else {
  1927. $messages[$key] = str_replace('%value%', $value, $message);
  1928. }
  1929. }
  1930. return $messages;
  1931. }
  1932. /**
  1933. * Are there custom error messages registered?
  1934. *
  1935. * @return bool
  1936. */
  1937. protected function _hasErrorMessages()
  1938. {
  1939. return !empty($this->_errorMessages);
  1940. }
  1941. }