PageRenderTime 77ms CodeModel.GetById 36ms RepoModel.GetById 0ms app.codeStats 0ms

/src/application/libraries/Zend/Form/Element.php

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