/include/Zend/Form/Element.php

https://bitbucket.org/mohammedsafwat/oktobcms · PHP · 2121 lines · 1179 code · 207 blank · 735 comment · 180 complexity · d7bab1c0e7b1e7a0ec09f84f1c9e15d2 MD5 · raw file

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