2
0

Element.php 58 KB

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