ElementTest.php 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230
  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. * @subpackage UnitTests
  18. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id$
  21. */
  22. if (!defined('PHPUnit_MAIN_METHOD')) {
  23. define('PHPUnit_MAIN_METHOD', 'Zend_Form_ElementTest::main');
  24. }
  25. require_once dirname(__FILE__) . '/../../TestHelper.php';
  26. // error_reporting(E_ALL);
  27. require_once 'Zend/Form/Element.php';
  28. require_once 'Zend/Config.php';
  29. require_once 'Zend/Controller/Action/HelperBroker.php';
  30. require_once 'Zend/Form.php';
  31. require_once 'Zend/Form/Decorator/Abstract.php';
  32. require_once 'Zend/Form/Decorator/HtmlTag.php';
  33. require_once 'Zend/Loader/PluginLoader.php';
  34. require_once 'Zend/Registry.php';
  35. require_once 'Zend/Translate.php';
  36. require_once 'Zend/Validate/NotEmpty.php';
  37. require_once 'Zend/Validate/EmailAddress.php';
  38. require_once 'Zend/View.php';
  39. /**
  40. * @category Zend
  41. * @package Zend_Form
  42. * @subpackage UnitTests
  43. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  44. * @license http://framework.zend.com/license/new-bsd New BSD License
  45. * @group Zend_Form
  46. */
  47. class Zend_Form_ElementTest extends PHPUnit_Framework_TestCase
  48. {
  49. public static function main()
  50. {
  51. $suite = new PHPUnit_Framework_TestSuite('Zend_Form_ElementTest');
  52. $result = PHPUnit_TextUI_TestRunner::run($suite);
  53. }
  54. public function setUp()
  55. {
  56. Zend_Registry::_unsetInstance();
  57. Zend_Form::setDefaultTranslator(null);
  58. if (isset($this->error)) {
  59. unset($this->error);
  60. }
  61. $this->element = new Zend_Form_Element('foo');
  62. Zend_Controller_Action_HelperBroker::resetHelpers();
  63. }
  64. public function tearDown()
  65. {
  66. }
  67. public function getView()
  68. {
  69. $view = new Zend_View();
  70. $libPath = dirname(__FILE__) . '/../../../library';
  71. $view->addHelperPath($libPath . '/Zend/View/Helper');
  72. return $view;
  73. }
  74. public function testConstructorRequiresMinimallyElementName()
  75. {
  76. try {
  77. $element = new Zend_Form_Element(1);
  78. $this->fail('Zend_Form_Element constructor should not accept integer argument');
  79. } catch (Zend_Form_Exception $e) {
  80. }
  81. try {
  82. $element = new Zend_Form_Element(true);
  83. $this->fail('Zend_Form_Element constructor should not accept boolean argument');
  84. } catch (Zend_Form_Exception $e) {
  85. }
  86. try {
  87. $element = new Zend_Form_Element('foo');
  88. } catch (Exception $e) {
  89. $this->fail('Zend_Form_Element constructor should accept String values');
  90. }
  91. $config = array('foo' => 'bar');
  92. try {
  93. $element = new Zend_Form_Element($config);
  94. $this->fail('Zend_Form_Element constructor requires array with name element');
  95. } catch (Zend_Form_Exception $e) {
  96. }
  97. $config = array('name' => 'bar');
  98. try {
  99. $element = new Zend_Form_Element($config);
  100. } catch (Zend_Form_Exception $e) {
  101. $this->fail('Zend_Form_Element constructor should accept array with name element');
  102. }
  103. $config = new Zend_Config(array('foo' => 'bar'));
  104. try {
  105. $element = new Zend_Form_Element($config);
  106. $this->fail('Zend_Form_Element constructor requires Zend_Config object with name element');
  107. } catch (Zend_Form_Exception $e) {
  108. }
  109. $config = new Zend_Config(array('name' => 'bar'));
  110. try {
  111. $element = new Zend_Form_Element($config);
  112. } catch (Zend_Form_Exception $e) {
  113. $this->fail('Zend_Form_Element constructor should accept Zend_Config with name element');
  114. }
  115. }
  116. public function testNoTranslatorByDefault()
  117. {
  118. $this->assertNull($this->element->getTranslator());
  119. }
  120. public function testGetTranslatorRetrievesGlobalDefaultWhenAvailable()
  121. {
  122. $this->testNoTranslatorByDefault();
  123. $translator = new Zend_Translate('array', array('foo' => 'bar'));
  124. Zend_Form::setDefaultTranslator($translator);
  125. $received = $this->element->getTranslator();
  126. $this->assertSame($translator->getAdapter(), $received);
  127. }
  128. public function testTranslatorAccessorsWork()
  129. {
  130. $translator = new Zend_Translate('array', array('foo' => 'bar'));
  131. $this->element->setTranslator($translator);
  132. $received = $this->element->getTranslator($translator);
  133. $this->assertSame($translator->getAdapter(), $received);
  134. }
  135. public function testCanDisableTranslation()
  136. {
  137. $this->testGetTranslatorRetrievesGlobalDefaultWhenAvailable();
  138. $this->element->setDisableTranslator(true);
  139. $this->assertNull($this->element->getTranslator());
  140. }
  141. public function testSetNameNormalizesValueToContainOnlyValidVariableCharacters()
  142. {
  143. $this->element->setName('f%\o^&*)o\(%$b#@!.a}{;-,r');
  144. $this->assertEquals('foobar', $this->element->getName());
  145. try {
  146. $this->element->setName('%\^&*)\(%$#@!.}{;-,');
  147. $this->fail('Empty names should raise exception');
  148. } catch (Zend_Form_Exception $e) {
  149. $this->assertContains('Invalid name provided', $e->getMessage());
  150. }
  151. }
  152. public function testZeroIsAllowedAsElementName()
  153. {
  154. try {
  155. $this->element->setName(0);
  156. $this->assertSame('0', $this->element->getName());
  157. } catch (Zend_Form_Exception $e) {
  158. $this->fail('Should allow zero as element name');
  159. }
  160. }
  161. /**
  162. * @see ZF-2851
  163. */
  164. public function testSetNameShouldNotAllowEmptyString()
  165. {
  166. foreach (array('', ' ', ' ') as $name) {
  167. try {
  168. $this->element->setName($name);
  169. $this->fail('setName() should not allow empty string');
  170. } catch (Zend_Form_Exception $e) {
  171. $this->assertContains('Invalid name', $e->getMessage());
  172. }
  173. }
  174. }
  175. public function testElementValueInitiallyNull()
  176. {
  177. $this->assertNull($this->element->getValue());
  178. }
  179. public function testValueAccessorsWork()
  180. {
  181. $this->element->setValue('bar');
  182. $this->assertContains('bar', $this->element->getValue());
  183. }
  184. public function testGetValueFiltersValue()
  185. {
  186. $this->element->setValue('This 0 is 1 a-2-TEST')
  187. ->addFilter('alnum')
  188. ->addFilter('stringToUpper');
  189. $test = $this->element->getValue();
  190. $this->assertEquals('THIS0IS1A2TEST', $test);
  191. }
  192. public function checkFilterValues($item, $key)
  193. {
  194. $this->assertRegexp('/^[A-Z]+$/', $item);
  195. }
  196. public function testRetrievingArrayValueFiltersAllArrayValues()
  197. {
  198. $this->element->setValue(array(
  199. 'foo',
  200. array(
  201. 'bar',
  202. 'baz'
  203. ),
  204. 'bat'
  205. ))
  206. ->setIsArray(true)
  207. ->addFilter('StringToUpper');
  208. $test = $this->element->getValue();
  209. $this->assertTrue(is_array($test));
  210. array_walk_recursive($test, array($this, 'checkFilterValues'));
  211. }
  212. public function testRetrievingArrayValueDoesNotFilterAllValuesWhenNotIsArray()
  213. {
  214. $values = array(
  215. 'foo',
  216. array(
  217. 'bar',
  218. 'baz'
  219. ),
  220. 'bat'
  221. );
  222. $this->element->setValue($values)
  223. ->addFilter(new Zend_Form_ElementTest_ArrayFilter());
  224. $test = $this->element->getValue();
  225. $this->assertTrue(is_array($test));
  226. require_once 'Zend/Json.php';
  227. $test = Zend_Json::encode($test);
  228. $this->assertNotContains('foo', $test);
  229. foreach (array('bar', 'baz', 'bat') as $value) {
  230. $this->assertContains($value, $test);
  231. }
  232. }
  233. public function testGetUnfilteredValueRetrievesOriginalValue()
  234. {
  235. $this->element->setValue('bar');
  236. $this->assertSame('bar', $this->element->getUnfilteredValue());
  237. }
  238. public function testLabelInitiallyNull()
  239. {
  240. $this->assertNull($this->element->getLabel());
  241. }
  242. public function testLabelAccessorsWork()
  243. {
  244. $this->element->setLabel('FooBar');
  245. $this->assertEquals('FooBar', $this->element->getLabel());
  246. }
  247. public function testOrderNullByDefault()
  248. {
  249. $this->assertNull($this->element->getOrder());
  250. }
  251. public function testCanSetOrder()
  252. {
  253. $this->testOrderNullByDefault();
  254. $this->element->setOrder(50);
  255. $this->assertEquals(50, $this->element->getOrder());
  256. }
  257. public function testRequiredFlagFalseByDefault()
  258. {
  259. $this->assertFalse($this->element->isRequired());
  260. }
  261. public function testRequiredAcccessorsWork()
  262. {
  263. $this->assertFalse($this->element->isRequired());
  264. $this->element->setRequired(true);
  265. $this->assertTrue($this->element->isRequired());
  266. }
  267. public function testIsValidInsertsNotEmptyValidatorWhenElementIsRequiredByDefault()
  268. {
  269. $this->_checkZf2794();
  270. $this->element->setRequired(true);
  271. $this->assertFalse($this->element->isValid(''));
  272. $validator = $this->element->getValidator('NotEmpty');
  273. $this->assertTrue($validator instanceof Zend_Validate_NotEmpty);
  274. $this->assertTrue($validator->zfBreakChainOnFailure);
  275. }
  276. /**
  277. * @see ZF-2862
  278. */
  279. public function testBreakChainOnFailureFlagsForExistingValidatorsRemainSetWhenNotEmptyValidatorAutoInserted()
  280. {
  281. $this->_checkZf2794();
  282. $username = new Zend_Form_Element('username');
  283. $username->addValidator('stringLength', true, array(5, 20))
  284. ->addValidator('regex', true, array('/^[a-zA-Z0-9_]*$/'))
  285. ->addFilter('StringToLower')
  286. ->setRequired(true);
  287. $form = new Zend_Form(array('elements' => array($username)));
  288. $form->isValid(array('username' => '#'));
  289. $validator = $username->getValidator('stringLength');
  290. $this->assertTrue($validator->zfBreakChainOnFailure);
  291. $validator = $username->getValidator('regex');
  292. $this->assertTrue($validator->zfBreakChainOnFailure);
  293. }
  294. public function testAutoInsertNotEmptyValidatorFlagTrueByDefault()
  295. {
  296. $this->assertTrue($this->element->autoInsertNotEmptyValidator());
  297. }
  298. public function testCanSetAutoInsertNotEmptyValidatorFlag()
  299. {
  300. $this->testAutoInsertNotEmptyValidatorFlagTrueByDefault();
  301. $this->element->setAutoInsertNotEmptyValidator(false);
  302. $this->assertFalse($this->element->autoInsertNotEmptyValidator());
  303. $this->element->setAutoInsertNotEmptyValidator(true);
  304. $this->assertTrue($this->element->autoInsertNotEmptyValidator());
  305. }
  306. public function testIsValidDoesNotInsertNotEmptyValidatorWhenElementIsRequiredButAutoInsertNotEmptyValidatorFlagIsFalse()
  307. {
  308. $this->element->setAutoInsertNotEmptyValidator(false)
  309. ->setRequired(true);
  310. $this->assertTrue($this->element->isValid(''));
  311. }
  312. public function testDescriptionInitiallyNull()
  313. {
  314. $this->assertNull($this->element->getDescription());
  315. }
  316. public function testCanSetDescription()
  317. {
  318. $this->testDescriptionInitiallyNull();
  319. $this->element->setDescription('element hint');
  320. $this->assertEquals('element hint', $this->element->getDescription());
  321. }
  322. public function testElementIsNotArrayByDefault()
  323. {
  324. $this->assertFalse($this->element->isArray());
  325. }
  326. public function testCanSetArrayFlag()
  327. {
  328. $this->testElementIsNotArrayByDefault();
  329. $this->element->setIsArray(true);
  330. $this->assertTrue($this->element->isArray());
  331. $this->element->setIsArray(false);
  332. $this->assertFalse($this->element->isArray());
  333. }
  334. public function testElementBelongsToNullByDefault()
  335. {
  336. $this->assertNull($this->element->getBelongsTo());
  337. }
  338. public function testCanSetArrayElementBelongsTo()
  339. {
  340. $this->testElementBelongsToNullByDefault();
  341. $this->element->setBelongsTo('foo');
  342. $this->assertEquals('foo', $this->element->getBelongsTo());
  343. }
  344. public function testArrayElementBelongsToNormalizedToValidVariableCharactersOnly()
  345. {
  346. $this->testElementBelongsToNullByDefault();
  347. $this->element->setBelongsTo('f%\o^&*)o\(%$b#@!.a}{;-,r');
  348. $this->assertEquals('foobar', $this->element->getBelongsTo());
  349. }
  350. public function testGetTypeReturnsCurrentElementClass()
  351. {
  352. $this->assertEquals('Zend_Form_Element', $this->element->getType());
  353. }
  354. public function testCanUseAccessorsToSetIndidualAttribs()
  355. {
  356. $this->element->setAttrib('foo', 'bar')
  357. ->setAttrib('bar', 'baz')
  358. ->setAttrib('baz', 'bat');
  359. $this->assertEquals('bar', $this->element->getAttrib('foo'));
  360. $this->assertEquals('baz', $this->element->getAttrib('bar'));
  361. $this->assertEquals('bat', $this->element->getAttrib('baz'));
  362. }
  363. public function testGetUndefinedAttribShouldReturnNull()
  364. {
  365. $this->assertNull($this->element->getAttrib('bogus'));
  366. }
  367. public function testSetAttribThrowsExceptionsForKeysWithLeadingUnderscores()
  368. {
  369. try {
  370. $this->element->setAttrib('_foo', 'bar');
  371. $this->fail('setAttrib() should throw an exception for invalid keys');
  372. } catch (Zend_Form_Exception $e) {
  373. $this->assertContains('Invalid attribute', $e->getMessage());
  374. }
  375. }
  376. public function testPassingNullValueToSetAttribUnsetsAttrib()
  377. {
  378. $this->element->setAttrib('foo', 'bar');
  379. $this->assertEquals('bar', $this->element->getAttrib('foo'));
  380. $this->element->setAttrib('foo', null);
  381. $this->assertFalse(isset($this->element->foo));
  382. }
  383. public function testSetAttribsSetsMultipleAttribs()
  384. {
  385. $this->element->setAttribs(array(
  386. 'foo' => 'bar',
  387. 'bar' => 'baz',
  388. 'baz' => 'bat'
  389. ));
  390. $this->assertEquals('bar', $this->element->getAttrib('foo'));
  391. $this->assertEquals('baz', $this->element->getAttrib('bar'));
  392. $this->assertEquals('bat', $this->element->getAttrib('baz'));
  393. }
  394. public function testGetAttribsRetrievesAllAttributes()
  395. {
  396. $attribs = array(
  397. 'foo' => 'bar',
  398. 'bar' => 'baz',
  399. 'baz' => 'bat'
  400. );
  401. $this->element->setAttribs($attribs);
  402. $attribs['helper'] = 'formText';
  403. $received = $this->element->getAttribs();
  404. $this->assertEquals($attribs, $received);
  405. }
  406. public function testPassingNullValuesToSetAttribsUnsetsAttribs()
  407. {
  408. $this->testSetAttribsSetsMultipleAttribs();
  409. $this->element->setAttribs(array('foo' => null));
  410. $this->assertNull($this->element->foo);
  411. }
  412. public function testRetrievingOverloadedValuesThrowsExceptionWithInvalidKey()
  413. {
  414. try {
  415. $name = $this->element->_name;
  416. $this->fail('Overloading should not return protected or private members');
  417. } catch (Zend_Form_Exception $e) {
  418. $this->assertContains('Cannot retrieve value for protected/private', $e->getMessage());
  419. }
  420. }
  421. public function testCanSetAndRetrieveAttribsViaOverloading()
  422. {
  423. $this->element->foo = 'bar';
  424. $this->assertEquals('bar', $this->element->foo);
  425. }
  426. public function testGetPluginLoaderRetrievesDefaultValidatorPluginLoader()
  427. {
  428. $loader = $this->element->getPluginLoader('validate');
  429. $this->assertTrue($loader instanceof Zend_Loader_PluginLoader);
  430. $paths = $loader->getPaths('Zend_Validate');
  431. $this->assertTrue(is_array($paths), var_export($loader, 1));
  432. $this->assertTrue(0 < count($paths));
  433. $this->assertContains('Validate', $paths[0]);
  434. }
  435. public function testGetPluginLoaderRetrievesDefaultFilterPluginLoader()
  436. {
  437. $loader = $this->element->getPluginLoader('filter');
  438. $this->assertTrue($loader instanceof Zend_Loader_PluginLoader);
  439. $paths = $loader->getPaths('Zend_Filter');
  440. $this->assertTrue(is_array($paths));
  441. $this->assertTrue(0 < count($paths));
  442. $this->assertContains('Filter', $paths[0]);
  443. }
  444. public function testGetPluginLoaderRetrievesDefaultDecoratorPluginLoader()
  445. {
  446. $loader = $this->element->getPluginLoader('decorator');
  447. $this->assertTrue($loader instanceof Zend_Loader_PluginLoader);
  448. $paths = $loader->getPaths('Zend_Form_Decorator');
  449. $this->assertTrue(is_array($paths));
  450. $this->assertTrue(0 < count($paths));
  451. $this->assertContains('Decorator', $paths[0]);
  452. }
  453. public function testCanSetCustomValidatorPluginLoader()
  454. {
  455. $loader = new Zend_Loader_PluginLoader();
  456. $this->element->setPluginLoader($loader, 'validate');
  457. $test = $this->element->getPluginLoader('validate');
  458. $this->assertSame($loader, $test);
  459. }
  460. public function testPassingInvalidTypeToSetPluginLoaderThrowsException()
  461. {
  462. $loader = new Zend_Loader_PluginLoader();
  463. try {
  464. $this->element->setPluginLoader($loader, 'foo');
  465. $this->fail('Invalid loader type should raise exception');
  466. } catch (Zend_Form_Exception $e) {
  467. $this->assertContains('Invalid type', $e->getMessage());
  468. }
  469. }
  470. public function testPassingInvalidTypeToGetPluginLoaderThrowsException()
  471. {
  472. try {
  473. $this->element->getPluginLoader('foo');
  474. $this->fail('Invalid loader type should raise exception');
  475. } catch (Zend_Form_Exception $e) {
  476. $this->assertContains('Invalid type', $e->getMessage());
  477. }
  478. }
  479. public function testCanSetCustomFilterPluginLoader()
  480. {
  481. $loader = new Zend_Loader_PluginLoader();
  482. $this->element->setPluginLoader($loader, 'filter');
  483. $test = $this->element->getPluginLoader('filter');
  484. $this->assertSame($loader, $test);
  485. }
  486. public function testCanSetCustomDecoratorPluginLoader()
  487. {
  488. $loader = new Zend_Loader_PluginLoader();
  489. $this->element->setPluginLoader($loader, 'decorator');
  490. $test = $this->element->getPluginLoader('decorator');
  491. $this->assertSame($loader, $test);
  492. }
  493. public function testPassingInvalidLoaderTypeToAddPrefixPathThrowsException()
  494. {
  495. try {
  496. $this->element->addPrefixPath('Zend_Foo', 'Zend/Foo/', 'foo');
  497. $this->fail('Invalid loader type should raise exception');
  498. } catch (Zend_Form_Exception $e) {
  499. $this->assertContains('Invalid type', $e->getMessage());
  500. }
  501. }
  502. public function testCanAddValidatorPluginLoaderPrefixPath()
  503. {
  504. $loader = $this->element->getPluginLoader('validate');
  505. $this->element->addPrefixPath('Zend_Form', 'Zend/Form/', 'validate');
  506. $paths = $loader->getPaths('Zend_Form');
  507. $this->assertTrue(is_array($paths));
  508. $this->assertContains('Form', $paths[0]);
  509. }
  510. public function testAddingValidatorPluginLoaderPrefixPathDoesNotAffectOtherLoaders()
  511. {
  512. $validateLoader = $this->element->getPluginLoader('validate');
  513. $filterLoader = $this->element->getPluginLoader('filter');
  514. $decoratorLoader = $this->element->getPluginLoader('decorator');
  515. $this->element->addPrefixPath('Zend_Form', 'Zend/Form/', 'validate');
  516. $this->assertFalse($filterLoader->getPaths('Zend_Form'));
  517. $this->assertFalse($decoratorLoader->getPaths('Zend_Form'));
  518. }
  519. public function testCanAddFilterPluginLoaderPrefixPath()
  520. {
  521. $loader = $this->element->getPluginLoader('validate');
  522. $this->element->addPrefixPath('Zend_Form', 'Zend/Form/', 'validate');
  523. $paths = $loader->getPaths('Zend_Form');
  524. $this->assertTrue(is_array($paths));
  525. $this->assertContains('Form', $paths[0]);
  526. }
  527. public function testAddingFilterPluginLoaderPrefixPathDoesNotAffectOtherLoaders()
  528. {
  529. $filterLoader = $this->element->getPluginLoader('filter');
  530. $validateLoader = $this->element->getPluginLoader('validate');
  531. $decoratorLoader = $this->element->getPluginLoader('decorator');
  532. $this->element->addPrefixPath('Zend_Form', 'Zend/Form/', 'filter');
  533. $this->assertFalse($validateLoader->getPaths('Zend_Form'));
  534. $this->assertFalse($decoratorLoader->getPaths('Zend_Form'));
  535. }
  536. public function testCanAddDecoratorPluginLoaderPrefixPath()
  537. {
  538. $loader = $this->element->getPluginLoader('decorator');
  539. $this->element->addPrefixPath('Zend_Foo', 'Zend/Foo/', 'decorator');
  540. $paths = $loader->getPaths('Zend_Foo');
  541. $this->assertTrue(is_array($paths));
  542. $this->assertContains('Foo', $paths[0]);
  543. }
  544. public function testAddingDecoratorrPluginLoaderPrefixPathDoesNotAffectOtherLoaders()
  545. {
  546. $decoratorLoader = $this->element->getPluginLoader('decorator');
  547. $filterLoader = $this->element->getPluginLoader('filter');
  548. $validateLoader = $this->element->getPluginLoader('validate');
  549. $this->element->addPrefixPath('Zend_Foo', 'Zend/Foo/', 'decorator');
  550. $this->assertFalse($validateLoader->getPaths('Zend_Foo'));
  551. $this->assertFalse($filterLoader->getPaths('Zend_Foo'));
  552. }
  553. public function testCanAddAllPluginLoaderPrefixPathsSimultaneously()
  554. {
  555. $validatorLoader = new Zend_Loader_PluginLoader();
  556. $filterLoader = new Zend_Loader_PluginLoader();
  557. $decoratorLoader = new Zend_Loader_PluginLoader();
  558. $this->element->setPluginLoader($validatorLoader, 'validate')
  559. ->setPluginLoader($filterLoader, 'filter')
  560. ->setPluginLoader($decoratorLoader, 'decorator')
  561. ->addPrefixPath('Zend', 'Zend/');
  562. $paths = $filterLoader->getPaths('Zend_Filter');
  563. $this->assertTrue(is_array($paths));
  564. $this->assertContains('Filter', $paths[0]);
  565. $paths = $validatorLoader->getPaths('Zend_Validate');
  566. $this->assertTrue(is_array($paths));
  567. $this->assertContains('Validate', $paths[0]);
  568. $paths = $decoratorLoader->getPaths('Zend_Decorator');
  569. $this->assertTrue(is_array($paths), var_export($paths, 1));
  570. $this->assertContains('Decorator', $paths[0]);
  571. }
  572. public function testPassingInvalidValidatorToAddValidatorThrowsException()
  573. {
  574. try {
  575. $this->element->addValidator(123);
  576. $this->fail('Invalid validator should raise exception');
  577. } catch (Zend_Form_Exception $e) {
  578. $this->assertContains('Invalid validator', $e->getMessage());
  579. }
  580. }
  581. public function testCanAddSingleValidatorAsString()
  582. {
  583. $this->_checkZf2794();
  584. $this->assertFalse($this->element->getValidator('digits'));
  585. $this->element->addValidator('digits');
  586. $validator = $this->element->getValidator('digits');
  587. $this->assertTrue($validator instanceof Zend_Validate_Digits, var_export($validator, 1));
  588. $this->assertFalse($validator->zfBreakChainOnFailure);
  589. }
  590. public function testCanNotRetrieveSingleValidatorRegisteredAsStringUsingClassName()
  591. {
  592. $this->assertFalse($this->element->getValidator('digits'));
  593. $this->element->addValidator('digits');
  594. $this->assertFalse($this->element->getValidator('Zend_Validate_Digits'));
  595. }
  596. public function testCanAddSingleValidatorAsValidatorObject()
  597. {
  598. $this->assertFalse($this->element->getValidator('Zend_Validate_Digits'));
  599. require_once 'Zend/Validate/Digits.php';
  600. $validator = new Zend_Validate_Digits();
  601. $this->element->addValidator($validator);
  602. $test = $this->element->getValidator('Zend_Validate_Digits');
  603. $this->assertSame($validator, $test);
  604. $this->assertFalse($validator->zfBreakChainOnFailure);
  605. }
  606. public function testOptionsAreCastToArrayWhenAddingValidator()
  607. {
  608. $this->_checkZf2794();
  609. try {
  610. $this->element->addValidator('Alnum', false, true);
  611. } catch (Exception $e) {
  612. $this->fail('Should be able to add non-array validator options');
  613. }
  614. $validator = $this->element->getValidator('Alnum');
  615. $this->assertTrue($validator instanceof Zend_Validate_Alnum);
  616. $this->assertTrue($validator->allowWhiteSpace);
  617. }
  618. public function testCanRetrieveSingleValidatorRegisteredAsValidatorObjectUsingShortName()
  619. {
  620. $this->_checkZf2794();
  621. $this->assertFalse($this->element->getValidator('digits'));
  622. require_once 'Zend/Validate/Digits.php';
  623. $validator = new Zend_Validate_Digits();
  624. $this->element->addValidator($validator);
  625. $test = $this->element->getValidator('digits');
  626. $this->assertSame($validator, $test);
  627. $this->assertFalse($validator->zfBreakChainOnFailure);
  628. }
  629. public function testRetrievingNamedValidatorShouldNotReorderValidators()
  630. {
  631. $this->element->addValidators(array(
  632. 'NotEmpty',
  633. 'Alnum',
  634. 'Digits',
  635. ));
  636. $validator = $this->element->getValidator('Alnum');
  637. $validators = $this->element->getValidators();
  638. $i = 0;
  639. $order = array();
  640. foreach (array_keys($validators) as $name) {
  641. $order[$name] = $i;
  642. ++$i;
  643. }
  644. $this->assertEquals(1, $order['Zend_Validate_Alnum'], var_export($order, 1));
  645. }
  646. public function testCanAddMultipleValidators()
  647. {
  648. $this->_checkZf2794();
  649. $this->assertFalse($this->element->getValidator('Zend_Validate_Digits'));
  650. $this->assertFalse($this->element->getValidator('Zend_Validate_Alnum'));
  651. $this->element->addValidators(array('digits', 'alnum'));
  652. $digits = $this->element->getValidator('digits');
  653. $this->assertTrue($digits instanceof Zend_Validate_Digits);
  654. $alnum = $this->element->getValidator('alnum');
  655. $this->assertTrue($alnum instanceof Zend_Validate_Alnum);
  656. }
  657. public function testRemovingUnregisteredValidatorReturnsObjectInstance()
  658. {
  659. $this->assertSame($this->element, $this->element->removeValidator('bogus'));
  660. }
  661. public function testPassingMessagesOptionToAddValidatorSetsValidatorMessages()
  662. {
  663. $messageTemplates = array(
  664. Zend_Validate_Digits::NOT_DIGITS => 'Value should only contain digits',
  665. Zend_Validate_Digits::STRING_EMPTY => 'Value needs some digits',
  666. );
  667. $this->element->setAllowEmpty(false)
  668. ->addValidator('digits', false, array('messages' => $messageTemplates));
  669. $this->element->isValid('');
  670. $messages = $this->element->getMessages();
  671. $found = false;
  672. foreach ($messages as $key => $message) {
  673. if ($key == Zend_Validate_Digits::STRING_EMPTY) {
  674. $found = true;
  675. break;
  676. }
  677. }
  678. $this->assertTrue($found, 'Empty string message not found: ' . var_export($messages, 1));
  679. $this->assertEquals($messageTemplates[Zend_Validate_Digits::STRING_EMPTY], $message);
  680. $this->element->isValid('abc');
  681. $messages = $this->element->getMessages();
  682. $found = false;
  683. foreach ($messages as $key => $message) {
  684. if ($key == Zend_Validate_Digits::NOT_DIGITS) {
  685. $found = true;
  686. break;
  687. }
  688. }
  689. $this->assertTrue($found, 'Not digits message not found');
  690. $this->assertEquals($messageTemplates[Zend_Validate_Digits::NOT_DIGITS], $message);
  691. }
  692. public function testCanPassSingleMessageToValidatorToSetValidatorMessages()
  693. {
  694. $this->_checkZf2794();
  695. $message = 'My custom empty message';
  696. $this->element->addValidator('notEmpty', false, array('messages' => $message))
  697. ->setRequired(true);
  698. $this->element->isValid('');
  699. $messages = $this->element->getMessages();
  700. $this->assertEquals(1, count($messages));
  701. $this->assertEquals($message, current($messages));
  702. }
  703. public function testMessagesAreTranslatedForCurrentLocale()
  704. {
  705. $localeFile = dirname(__FILE__) . '/_files/locale/array.php';
  706. $translations = include($localeFile);
  707. $translator = new Zend_Translate('array', $translations, 'en');
  708. $translator->setLocale('en');
  709. $this->element->setAllowEmpty(false)
  710. ->setTranslator($translator)
  711. ->addValidator('digits');
  712. $this->element->isValid('');
  713. $messages = $this->element->getMessages();
  714. $found = false;
  715. foreach ($messages as $key => $message) {
  716. if ($key == 'digitsStringEmpty') {
  717. $found = true;
  718. break;
  719. }
  720. }
  721. $this->assertTrue($found, 'String Empty message not found: ' . var_export($messages, 1));
  722. $this->assertEquals($translations['stringEmpty'], $message);
  723. $this->element->isValid('abc');
  724. $messages = $this->element->getMessages();
  725. $found = false;
  726. foreach ($messages as $key => $message) {
  727. if ($key == 'notDigits') {
  728. $found = true;
  729. break;
  730. }
  731. }
  732. $this->assertTrue($found, 'Not Digits message not found');
  733. $this->assertEquals($translations['notDigits'], $message);
  734. }
  735. /**#@+
  736. * @see ZF-2988
  737. */
  738. public function testSettingErrorMessageShouldOverrideValidationErrorMessages()
  739. {
  740. $this->element->addValidator('Alpha');
  741. $this->element->addErrorMessage('Invalid value entered');
  742. $this->assertFalse($this->element->isValid(123));
  743. $messages = $this->element->getMessages();
  744. $this->assertEquals(1, count($messages));
  745. $this->assertEquals('Invalid value entered', array_shift($messages));
  746. }
  747. public function testCustomErrorMessagesShouldBeManagedInAStack()
  748. {
  749. $this->element->addValidator('Alpha');
  750. $this->element->addErrorMessage('Invalid value entered');
  751. $this->element->addErrorMessage('Really, it is not valid');
  752. $messages = $this->element->getErrorMessages();
  753. $this->assertEquals(2, count($messages));
  754. $this->assertFalse($this->element->isValid(123));
  755. $messages = $this->element->getMessages();
  756. $this->assertEquals(2, count($messages));
  757. $this->assertEquals('Invalid value entered', array_shift($messages));
  758. $this->assertEquals('Really, it is not valid', array_shift($messages));
  759. }
  760. public function testShouldAllowSettingMultipleErrorMessagesAtOnce()
  761. {
  762. $set1 = array('foo', 'bar', 'baz');
  763. $this->element->addErrorMessages($set1);
  764. $this->assertSame($set1, $this->element->getErrorMessages());
  765. }
  766. public function testSetErrorMessagesShouldOverwriteMessages()
  767. {
  768. $set1 = array('foo', 'bar', 'baz');
  769. $set2 = array('bat', 'cat');
  770. $this->element->addErrorMessages($set1);
  771. $this->assertSame($set1, $this->element->getErrorMessages());
  772. $this->element->setErrorMessages($set2);
  773. $this->assertSame($set2, $this->element->getErrorMessages());
  774. }
  775. public function testCustomErrorMessageStackShouldBeClearable()
  776. {
  777. $this->testCustomErrorMessagesShouldBeManagedInAStack();
  778. $this->element->clearErrorMessages();
  779. $messages = $this->element->getErrorMessages();
  780. $this->assertTrue(empty($messages));
  781. }
  782. public function testCustomErrorMessagesShouldBeTranslated()
  783. {
  784. $translations = array(
  785. 'foo' => 'Foo message',
  786. );
  787. $translate = new Zend_Translate('array', $translations);
  788. $this->element->setTranslator($translate)
  789. ->addErrorMessage('foo')
  790. ->addValidator('Alpha');
  791. $this->assertFalse($this->element->isValid(123));
  792. $messages = $this->element->getMessages();
  793. $this->assertEquals(1, count($messages));
  794. $this->assertEquals('Foo message', array_shift($messages));
  795. }
  796. public function testCustomErrorMessagesShouldAllowValueSubstitution()
  797. {
  798. $this->element->addErrorMessage('"%value%" is an invalid value')
  799. ->addValidator('Alpha');
  800. $this->assertFalse($this->element->isValid(123));
  801. $this->assertTrue($this->element->hasErrors());
  802. $messages = $this->element->getMessages();
  803. $this->assertEquals(1, count($messages));
  804. $this->assertEquals('"123" is an invalid value', array_shift($messages));
  805. }
  806. public function testShouldAllowMarkingElementAsInvalid()
  807. {
  808. $this->element->setValue('foo');
  809. $this->element->addErrorMessage('Invalid value entered');
  810. $this->assertFalse($this->element->hasErrors());
  811. $this->element->markAsError();
  812. $this->assertTrue($this->element->hasErrors());
  813. $messages = $this->element->getMessages();
  814. $this->assertEquals(1, count($messages));
  815. $this->assertEquals('Invalid value entered', array_shift($messages));
  816. }
  817. public function testShouldAllowPushingErrorsOntoErrorStackWithErrorMessages()
  818. {
  819. $this->element->setValue('foo');
  820. $this->assertFalse($this->element->hasErrors());
  821. $this->element->setErrors(array('Error 1', 'Error 2'))
  822. ->addError('Error 3')
  823. ->addErrors(array('Error 4', 'Error 5'));
  824. $this->assertTrue($this->element->hasErrors());
  825. $messages = $this->element->getMessages();
  826. $this->assertEquals(5, count($messages));
  827. foreach (range(1, 5) as $id) {
  828. $message = 'Error ' . $id;
  829. $this->assertContains($message, $messages);
  830. }
  831. }
  832. public function testHasErrorsShouldIndicateStatusOfValidationErrors()
  833. {
  834. $this->element->setValue('foo');
  835. $this->assertFalse($this->element->hasErrors());
  836. $this->element->markAsError();
  837. $this->assertTrue($this->element->hasErrors());
  838. }
  839. /**#@-*/
  840. public function testAddingErrorToArrayElementShouldLoopOverAllValues()
  841. {
  842. $this->element->setIsArray(true)
  843. ->setValue(array('foo', 'bar', 'baz'))
  844. ->addError('error with value %value%');
  845. $errors = $this->element->getMessages();
  846. require_once 'Zend/Json.php';
  847. $errors = Zend_Json::encode($errors);
  848. foreach (array('foo', 'bar', 'baz') as $value) {
  849. $message = 'error with value ' . $value;
  850. $this->assertContains($message, $errors);
  851. }
  852. }
  853. /** ZF-2568 */
  854. public function testTranslatedMessagesCanContainVariableSubstitution()
  855. {
  856. $localeFile = dirname(__FILE__) . '/_files/locale/array.php';
  857. $translations = include($localeFile);
  858. $translations['notDigits'] .= ' "%value%"';
  859. $translator = new Zend_Translate('array', $translations, 'en');
  860. $translator->setLocale('en');
  861. $this->element->setAllowEmpty(false)
  862. ->setTranslator($translator)
  863. ->addValidator('digits');
  864. $this->element->isValid('abc');
  865. $messages = $this->element->getMessages();
  866. $found = false;
  867. foreach ($messages as $key => $message) {
  868. if ($key == 'notDigits') {
  869. $found = true;
  870. break;
  871. }
  872. }
  873. $this->assertTrue($found, 'String Empty message not found: ' . var_export($messages, 1));
  874. $this->assertContains(' "abc"', $message);
  875. $this->assertContains('Translating the notDigits string', $message);
  876. }
  877. public function testCanRemoveValidator()
  878. {
  879. $this->_checkZf2794();
  880. $this->assertFalse($this->element->getValidator('Zend_Validate_Digits'));
  881. $this->element->addValidator('digits');
  882. $digits = $this->element->getValidator('digits');
  883. $this->assertTrue($digits instanceof Zend_Validate_Digits);
  884. $this->element->removeValidator('digits');
  885. $this->assertFalse($this->element->getValidator('digits'));
  886. }
  887. public function testCanClearAllValidators()
  888. {
  889. $this->_checkZf2794();
  890. $this->testCanAddMultipleValidators();
  891. $validators = $this->element->getValidators();
  892. $this->element->clearValidators();
  893. $test = $this->element->getValidators();
  894. $this->assertNotEquals($validators, $test);
  895. $this->assertTrue(empty($test));
  896. foreach (array_keys($validators) as $validator) {
  897. $this->assertFalse($this->element->getValidator($validator));
  898. }
  899. }
  900. public function testCanValidateElement()
  901. {
  902. $this->element->addValidator(new Zend_Validate_NotEmpty())
  903. ->addValidator(new Zend_Validate_EmailAddress());
  904. try {
  905. $result = $this->element->isValid('matthew@zend.com');
  906. } catch (Exception $e) {
  907. $this->fail('Validating an element should work');
  908. }
  909. }
  910. public function testCanValidateArrayValue()
  911. {
  912. $this->element->setIsArray(true)
  913. ->addValidator('InArray', false, array(array('foo', 'bar', 'baz', 'bat')));
  914. $this->assertTrue($this->element->isValid(array('foo', 'bat')));
  915. }
  916. public function testShouldAllowZeroAsNonEmptyValue()
  917. {
  918. $this->element->addValidator('between', false, array(1, 100));
  919. $this->assertFalse($this->element->isValid('0'));
  920. }
  921. public function testIsValidPopulatesElementValue()
  922. {
  923. $this->testCanValidateElement();
  924. $this->assertEquals('matthew@zend.com', $this->element->getValue());
  925. }
  926. public function testErrorsPopulatedFollowingFailedIsValidCheck()
  927. {
  928. $this->element->addValidator(new Zend_Validate_NotEmpty())
  929. ->addValidator(new Zend_Validate_EmailAddress());
  930. $result = $this->element->isValid('matthew');
  931. if ($result) {
  932. $this->fail('Invalid data should fail validations');
  933. }
  934. $errors = $this->element->getErrors();
  935. $this->assertTrue(is_array($errors));
  936. $this->assertTrue(0 < count($errors));
  937. }
  938. public function testMessagesPopulatedFollowingFailedIsValidCheck()
  939. {
  940. require_once 'Zend/Validate/NotEmpty.php';
  941. require_once 'Zend/Validate/EmailAddress.php';
  942. $this->element->addValidator(new Zend_Validate_NotEmpty())
  943. ->addValidator(new Zend_Validate_EmailAddress());
  944. $result = $this->element->isValid('matthew');
  945. if ($result) {
  946. $this->fail('Invalid data should fail validations');
  947. }
  948. $messages = $this->element->getMessages();
  949. $this->assertTrue(is_array($messages));
  950. $this->assertTrue(0 < count($messages));
  951. }
  952. public function testOptionalElementDoesNotPerformValidationsOnEmptyValuesByDefault()
  953. {
  954. $this->element->addValidator(new Zend_Validate_EmailAddress());
  955. $result = $this->element->isValid('');
  956. if (!$result) {
  957. $this->fail('Empty data should not fail validations');
  958. }
  959. $errors = $this->element->getErrors();
  960. $this->assertTrue(is_array($errors));
  961. $this->assertTrue(empty($errors));
  962. }
  963. public function testOptionalElementDoesPerformValidationsWhenAllowEmptyIsFalse()
  964. {
  965. $this->element->setAllowEmpty(false)
  966. ->addValidator(new Zend_Validate_EmailAddress());
  967. $result = $this->element->isValid('');
  968. if ($result) {
  969. $this->fail('Empty data should fail validations when AllowEmpty is false');
  970. }
  971. $errors = $this->element->getErrors();
  972. $this->assertTrue(is_array($errors));
  973. $this->assertTrue(0 < count($errors));
  974. }
  975. public function testAddingInvalidFilterTypeThrowsException()
  976. {
  977. try {
  978. $this->element->addFilter(123);
  979. $this->fail('Invalid filter type should raise exception');
  980. } catch (Zend_Form_Exception $e) {
  981. $this->assertContains('Invalid filter', $e->getMessage());
  982. }
  983. }
  984. public function testCanAddSingleFilterAsString()
  985. {
  986. $this->_checkZf2794();
  987. $this->assertFalse($this->element->getFilter('digits'));
  988. $this->element->addFilter('digits');
  989. $filter = $this->element->getFilter('digits');
  990. $this->assertTrue($filter instanceof Zend_Filter_Digits);
  991. }
  992. public function testCanNotRetrieveSingleFilterRegisteredAsStringUsingClassName()
  993. {
  994. $this->assertFalse($this->element->getFilter('digits'));
  995. $this->element->addFilter('digits');
  996. $this->assertFalse($this->element->getFilter('Zend_Filter_Digits'));
  997. }
  998. public function testCanAddSingleFilterAsFilterObject()
  999. {
  1000. $this->assertFalse($this->element->getFilter('Zend_Filter_Digits'));
  1001. require_once 'Zend/Filter/Digits.php';
  1002. $filter = new Zend_Filter_Digits();
  1003. $this->element->addFilter($filter);
  1004. $test = $this->element->getFilter('Zend_Filter_Digits');
  1005. $this->assertSame($filter, $test);
  1006. }
  1007. public function testCanRetrieveSingleFilterRegisteredAsFilterObjectUsingShortName()
  1008. {
  1009. $this->_checkZf2794();
  1010. $this->assertFalse($this->element->getFilter('digits'));
  1011. require_once 'Zend/Filter/Digits.php';
  1012. $filter = new Zend_Filter_Digits();
  1013. $this->element->addFilter($filter);
  1014. $test = $this->element->getFilter('digits');
  1015. }
  1016. public function testRetrievingNamedFilterShouldNotReorderFilters()
  1017. {
  1018. $this->element->addFilters(array(
  1019. 'Alpha',
  1020. 'Alnum',
  1021. 'Digits',
  1022. ));
  1023. $filter = $this->element->getFilter('Alnum');
  1024. $filters = $this->element->getFilters();
  1025. $i = 0;
  1026. $order = array();
  1027. foreach (array_keys($filters) as $name) {
  1028. $order[$name] = $i;
  1029. ++$i;
  1030. }
  1031. $this->assertEquals(1, $order['Zend_Filter_Alnum'], var_export($order, 1));
  1032. }
  1033. public function testOptionsAreCastToArrayWhenAddingFilter()
  1034. {
  1035. $this->_checkZf2794();
  1036. try {
  1037. $this->element->addFilter('Alnum', true);
  1038. } catch (Exception $e) {
  1039. $this->fail('Should be able to add non-array filter options');
  1040. }
  1041. $filter = $this->element->getFilter('Alnum');
  1042. $this->assertTrue($filter instanceof Zend_Filter_Alnum);
  1043. $this->assertTrue($filter->allowWhiteSpace);
  1044. }
  1045. public function testShouldUseFilterConstructorOptionsAsPassedToAddFilter()
  1046. {
  1047. $this->element->addFilter('HtmlEntities', array(array('quotestyle' => ENT_QUOTES, 'charset' => 'UTF-8')));
  1048. $filter = $this->element->getFilter('HtmlEntities');
  1049. $this->assertTrue($filter instanceof Zend_Filter_HtmlEntities);
  1050. $this->assertEquals(ENT_QUOTES, $filter->getQuoteStyle());
  1051. $this->assertEquals('UTF-8', $filter->getCharSet());
  1052. }
  1053. public function testCanAddMultipleFilters()
  1054. {
  1055. $this->_checkZf2794();
  1056. $this->assertFalse($this->element->getFilter('Zend_Filter_Digits'));
  1057. $this->assertFalse($this->element->getFilter('Zend_Filter_Alnum'));
  1058. $this->element->addFilters(array('digits', 'alnum'));
  1059. $digits = $this->element->getFilter('digits');
  1060. $this->assertTrue($digits instanceof Zend_Filter_Digits);
  1061. $alnum = $this->element->getFilter('alnum');
  1062. $this->assertTrue($alnum instanceof Zend_Filter_Alnum);
  1063. }
  1064. public function testRemovingUnregisteredFilterReturnsObjectInstance()
  1065. {
  1066. $this->assertSame($this->element, $this->element->removeFilter('bogus'));
  1067. }
  1068. public function testCanRemoveFilter()
  1069. {
  1070. $this->_checkZf2794();
  1071. $this->assertFalse($this->element->getFilter('Zend_Filter_Digits'));
  1072. $this->element->addFilter('digits');
  1073. $digits = $this->element->getFilter('digits');
  1074. $this->assertTrue($digits instanceof Zend_Filter_Digits);
  1075. $this->element->removeFilter('digits');
  1076. $this->assertFalse($this->element->getFilter('digits'));
  1077. }
  1078. public function testCanClearAllFilters()
  1079. {
  1080. $this->_checkZf2794();
  1081. $this->testCanAddMultipleFilters();
  1082. $filters = $this->element->getFilters();
  1083. $this->element->clearFilters();
  1084. $test = $this->element->getFilters();
  1085. $this->assertNotEquals($filters, $test);
  1086. $this->assertTrue(empty($test));
  1087. foreach (array_keys($filters) as $filter) {
  1088. $this->assertFalse($this->element->getFilter($filter));
  1089. }
  1090. }
  1091. public function testGetViewReturnsNullWithNoViewRenderer()
  1092. {
  1093. $this->assertNull($this->element->getView());
  1094. }
  1095. public function testGetViewReturnsViewRendererViewInstanceIfViewRendererActive()
  1096. {
  1097. $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
  1098. $viewRenderer->initView();
  1099. $view = $viewRenderer->view;
  1100. $test = $this->element->getView();
  1101. $this->assertSame($view, $test);
  1102. }
  1103. public function testCanSetView()
  1104. {
  1105. $view = new Zend_View();
  1106. $this->assertNull($this->element->getView());
  1107. $this->element->setView($view);
  1108. $received = $this->element->getView();
  1109. $this->assertSame($view, $received);
  1110. }
  1111. public function testViewHelperDecoratorRegisteredByDefault()
  1112. {
  1113. $this->_checkZf2794();
  1114. $decorator = $this->element->getDecorator('viewHelper');
  1115. $this->assertTrue($decorator instanceof Zend_Form_Decorator_ViewHelper);
  1116. }
  1117. /**
  1118. * @group ZF-4822
  1119. */
  1120. public function testErrorsDecoratorRegisteredByDefault()
  1121. {
  1122. $this->_checkZf2794();
  1123. $decorator = $this->element->getDecorator('errors');
  1124. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Errors);
  1125. }
  1126. /**
  1127. * @group ZF-4822
  1128. */
  1129. public function testDescriptionDecoratorRegisteredByDefault()
  1130. {
  1131. $this->_checkZf2794();
  1132. $decorator = $this->element->getDecorator('description');
  1133. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Description);
  1134. $options = $decorator->getOptions();
  1135. $this->assertTrue(array_key_exists('tag', $options));
  1136. $this->assertEquals('p', $options['tag']);
  1137. $this->assertTrue(array_key_exists('class', $options));
  1138. $this->assertEquals('description', $options['class']);
  1139. }
  1140. /**
  1141. * @group ZF-4822
  1142. */
  1143. public function testHtmlTagDecoratorRegisteredByDefault()
  1144. {
  1145. $this->_checkZf2794();
  1146. $decorator = $this->element->getDecorator('HtmlTag');
  1147. $this->assertTrue($decorator instanceof Zend_Form_Decorator_HtmlTag);
  1148. }
  1149. /**
  1150. * @group ZF-4822
  1151. */
  1152. public function testLabelDecoratorRegisteredByDefault()
  1153. {
  1154. $this->_checkZf2794();
  1155. $decorator = $this->element->getDecorator('Label');
  1156. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Label);
  1157. }
  1158. public function testCanDisableRegisteringDefaultDecoratorsDuringInitialization()
  1159. {
  1160. $element = new Zend_Form_Element('foo', array('disableLoadDefaultDecorators' => true));
  1161. $decorators = $element->getDecorators();
  1162. $this->assertEquals(array(), $decorators);
  1163. }
  1164. public function testAddingInvalidDecoratorThrowsException()
  1165. {
  1166. try {
  1167. $this->element->addDecorator(123);
  1168. $this->fail('Invalid decorator type should raise exception');
  1169. } catch (Zend_Form_Exception $e) {
  1170. $this->assertContains('Invalid decorator', $e->getMessage());
  1171. }
  1172. }
  1173. public function testCanAddSingleDecoratorAsString()
  1174. {
  1175. $this->_checkZf2794();
  1176. $this->element->clearDecorators();
  1177. $this->assertFalse($this->element->getDecorator('viewHelper'));
  1178. $this->element->addDecorator('viewHelper');
  1179. $decorator = $this->element->getDecorator('viewHelper');
  1180. $this->assertTrue($decorator instanceof Zend_Form_Decorator_ViewHelper);
  1181. }
  1182. public function testCanNotRetrieveSingleDecoratorRegisteredAsStringUsingClassName()
  1183. {
  1184. $this->assertFalse($this->element->getDecorator('Zend_Form_Decorator_ViewHelper'));
  1185. }
  1186. public function testCanAddSingleDecoratorAsDecoratorObject()
  1187. {
  1188. $this->element->clearDecorators();
  1189. $this->assertFalse($this->element->getDecorator('viewHelper'));
  1190. $decorator = new Zend_Form_Decorator_ViewHelper;
  1191. $this->element->addDecorator($decorator);
  1192. $test = $this->element->getDecorator('Zend_Form_Decorator_ViewHelper');
  1193. $this->assertSame($decorator, $test);
  1194. }
  1195. /**
  1196. * @see ZF-3597
  1197. */
  1198. public function testAddingConcreteDecoratorShouldHonorOrder()
  1199. {
  1200. require_once dirname(__FILE__) . '/_files/decorators/TableRow.php';
  1201. $decorator = new My_Decorator_TableRow();
  1202. $this->element->setLabel('Foo')
  1203. ->setDescription('sample description')
  1204. ->clearDecorators()
  1205. ->addDecorators(array(
  1206. 'ViewHelper',
  1207. $decorator,
  1208. ));
  1209. $html = $this->element->render($this->getView());
  1210. $this->assertRegexp('#<tr><td>Foo</td><td>.*?<input[^>]+>.*?</td><td>sample description</td></tr>#s', $html, $html);
  1211. }
  1212. public function testCanRetrieveSingleDecoratorRegisteredAsDecoratorObjectUsingShortName()
  1213. {
  1214. $this->_checkZf2794();
  1215. $this->element->clearDecorators();
  1216. $this->assertFalse($this->element->getDecorator('viewHelper'));
  1217. $decorator = new Zend_Form_Decorator_ViewHelper;
  1218. $this->element->addDecorator($decorator);
  1219. $test = $this->element->getDecorator('viewHelper');
  1220. $this->assertSame($decorator, $test);
  1221. }
  1222. public function testCanAddMultipleDecorators()
  1223. {
  1224. $this->_checkZf2794();
  1225. $this->element->clearDecorators();
  1226. $this->assertFalse($this->element->getDecorator('viewHelper'));
  1227. $testDecorator = new Zend_Form_ElementTest_Decorator;
  1228. $this->element->addDecorators(array(
  1229. 'ViewHelper',
  1230. $testDecorator
  1231. ));
  1232. $viewHelper = $this->element->getDecorator('viewHelper');
  1233. $this->assertTrue($viewHelper instanceof Zend_Form_Decorator_ViewHelper);
  1234. $decorator = $this->element->getDecorator('decorator');
  1235. $this->assertSame($testDecorator, $decorator);
  1236. }
  1237. public function testRemovingUnregisteredDecoratorReturnsObjectInstance()
  1238. {
  1239. $this->_checkZf2794();
  1240. $this->assertSame($this->element, $this->element->removeDecorator('bogus'));
  1241. }
  1242. public function testCanRemoveDecorator()
  1243. {
  1244. $this->testViewHelperDecoratorRegisteredByDefault();
  1245. $this->element->removeDecorator('viewHelper');
  1246. $this->assertFalse($this->element->getDecorator('viewHelper'));
  1247. }
  1248. /**
  1249. * @see ZF-3069
  1250. */
  1251. public function testRemovingNamedDecoratorsShouldWork()
  1252. {
  1253. $this->_checkZf2794();
  1254. $this->element->setDecorators(array(
  1255. 'ViewHelper',
  1256. array(array('div' => 'HtmlTag'), array('tag' => 'div')),
  1257. array(array('div2' => 'HtmlTag'), array('tag' => 'div')),
  1258. ));
  1259. $decorators = $this->element->getDecorators();
  1260. $this->assertTrue(array_key_exists('div', $decorators));
  1261. $this->assertTrue(array_key_exists('div2', $decorators));
  1262. $this->element->removeDecorator('div');
  1263. $decorators = $this->element->getDecorators();
  1264. $this->assertFalse(array_key_exists('div', $decorators));
  1265. $this->assertTrue(array_key_exists('div2', $decorators));
  1266. }
  1267. public function testCanClearAllDecorators()
  1268. {
  1269. $this->testCanAddMultipleDecorators();
  1270. $this->element->clearDecorators();
  1271. $this->assertFalse($this->element->getDecorator('viewHelper'));
  1272. $this->assertFalse($this->element->getDecorator('decorator'));
  1273. }
  1274. public function testCanAddDecoratorAliasesToAllowMultipleDecoratorsOfSameType()
  1275. {
  1276. $this->_checkZf2794();
  1277. $this->element->setDecorators(array(
  1278. array('HtmlTag', array('tag' => 'span')),
  1279. array('decorator' => array('FooBar' => 'HtmlTag'), 'options' => array('tag' => 'div')),
  1280. ));
  1281. $decorator = $this->element->getDecorator('FooBar');
  1282. $this->assertTrue($decorator instanceof Zend_Form_Decorator_HtmlTag);
  1283. $this->assertEquals('div', $decorator->getOption('tag'));
  1284. $decorator = $this->element->getDecorator('HtmlTag');
  1285. $this->assertTrue($decorator instanceof Zend_Form_Decorator_HtmlTag);
  1286. $this->assertEquals('span', $decorator->getOption('tag'));
  1287. }
  1288. public function testRetrievingNamedDecoratorShouldNotReorderDecorators()
  1289. {
  1290. $this->element->setDecorators(array(
  1291. 'ViewHelper',
  1292. 'Errors',
  1293. array(array('inner' => 'HtmlTag'), array('tag' => 'div', 'class' => 'element')),
  1294. 'Label',
  1295. array(array('outer' => 'HtmlTag'), array('tag' => 'div')),
  1296. ));
  1297. $decorator = $this->element->getDecorator('inner');
  1298. $decorators = $this->element->getDecorators();
  1299. $i = 0;
  1300. $order = array();
  1301. foreach (array_keys($decorators) as $name) {
  1302. $order[$name] = $i;
  1303. ++$i;
  1304. }
  1305. $this->assertEquals(2, $order['inner'], var_export($order, 1));
  1306. }
  1307. /**
  1308. * @see ZF-3376
  1309. */
  1310. public function testSetDecoratorsShouldAcceptReturnOfGetDecorators()
  1311. {
  1312. $this->element->setDecorators(array(
  1313. 'ViewHelper',
  1314. 'Errors',
  1315. array('input' => 'HtmlTag', array('tag' => 'div', 'class' => 'input')),
  1316. 'Label',
  1317. array('element' => 'HtmlTag', array('tag' => 'div', 'class' => 'element')),
  1318. ));
  1319. $decorators = $this->element->getDecorators();
  1320. $this->element->setDecorators($decorators);
  1321. $this->assertSame($decorators, $this->element->getDecorators());
  1322. }
  1323. public function testRenderElementReturnsMarkup()
  1324. {
  1325. $this->element->setName('foo');
  1326. $html = $this->element->render($this->getView());
  1327. $this->assertTrue(is_string($html));
  1328. $this->assertFalse(empty($html));
  1329. $this->assertContains('<input', $html);
  1330. $this->assertContains('"foo"', $html);
  1331. }
  1332. public function testRenderElementRendersLabelWhenProvided()
  1333. {
  1334. $this->element->setView($this->getView());
  1335. $this->element->setName('foo')
  1336. ->setLabel('Foo');
  1337. $html = $this->element->render();
  1338. $this->assertTrue(is_string($html));
  1339. $this->assertFalse(empty($html));
  1340. $this->assertContains('<label', $html);
  1341. $this->assertContains('Foo', $html);
  1342. $this->assertContains('</label>', $html);
  1343. }
  1344. public function testRenderElementRendersValueWhenProvided()
  1345. {
  1346. $this->element->setView($this->getView());
  1347. $this->element->setName('foo')
  1348. ->setValue('bar');
  1349. $html = $this->element->render();
  1350. $this->assertTrue(is_string($html));
  1351. $this->assertFalse(empty($html));
  1352. $this->assertContains('<input', $html);
  1353. $this->assertContains('"foo"', $html);
  1354. $this->assertContains('"bar"', $html);
  1355. }
  1356. public function testRenderElementRendersErrorsWhenProvided()
  1357. {
  1358. $this->_checkZf2794();
  1359. $this->element->setView($this->getView())
  1360. ->setRequired(true)
  1361. ->setName('foo')
  1362. ->addValidator('NotEmpty');
  1363. $this->element->isValid('');
  1364. $html = $this->element->render();
  1365. $this->assertTrue(is_string($html));
  1366. $this->assertFalse(empty($html));
  1367. $this->assertContains('error', $html);
  1368. $this->assertRegexp('/empty/i', $html);
  1369. }
  1370. public function testToStringProxiesToRender()
  1371. {
  1372. $this->element->setView($this->getView());
  1373. $this->element->setName('foo');
  1374. $html = $this->element->__toString();
  1375. $this->assertTrue(is_string($html));
  1376. $this->assertFalse(empty($html));
  1377. $this->assertContains('<input', $html);
  1378. $this->assertContains('"foo"', $html);
  1379. }
  1380. public function raiseDecoratorException($content, $element, $options)
  1381. {
  1382. throw new Exception('Raising exception in decorator callback');
  1383. }
  1384. public function handleDecoratorErrors($errno, $errstr, $errfile = '', $errline = 0, array $errcontext = array())
  1385. {
  1386. $this->error = $errstr;
  1387. }
  1388. public function testToStringRaisesErrorWhenExceptionCaught()
  1389. {
  1390. $this->element->setDecorators(array(
  1391. array(
  1392. 'decorator' => 'Callback',
  1393. 'options' => array('callback' => array($this, 'raiseDecoratorException'))
  1394. ),
  1395. ));
  1396. $origErrorHandler = set_error_handler(array($this, 'handleDecoratorErrors'), E_USER_WARNING);
  1397. $text = $this->element->__toString();
  1398. restore_error_handler();
  1399. $this->assertTrue(empty($text));
  1400. $this->assertTrue(isset($this->error));
  1401. $this->assertEquals('Raising exception in decorator callback', $this->error);
  1402. }
  1403. public function getOptions()
  1404. {
  1405. $options = array(
  1406. 'name' => 'changed',
  1407. 'value' => 'foo',
  1408. 'label' => 'bar',
  1409. 'order' => 50,
  1410. 'required' => false,
  1411. 'foo' => 'bar',
  1412. 'baz' => 'bat'
  1413. );
  1414. return $options;
  1415. }
  1416. public function testCanSetObjectStateViaSetOptions()
  1417. {
  1418. $options = $this->getOptions();
  1419. $this->element->setOptions($options);
  1420. $this->assertEquals('changed', $this->element->getName());
  1421. $this->assertEquals('foo', $this->element->getValue());
  1422. $this->assertEquals('bar', $this->element->getLabel());
  1423. $this->assertEquals(50, $this->element->getOrder());
  1424. $this->assertFalse($this->element->isRequired());
  1425. $this->assertEquals('bar', $this->element->foo);
  1426. $this->assertEquals('bat', $this->element->baz);
  1427. }
  1428. public function testSetOptionsSkipsCallsToSetOptionsAndSetConfig()
  1429. {
  1430. $options = $this->getOptions();
  1431. $config = new Zend_Config($options);
  1432. $options['config'] = $config;
  1433. $options['options'] = $config->toArray();
  1434. $this->element->setOptions($options);
  1435. }
  1436. public function testSetOptionsSkipsSettingAccessorsRequiringObjectsWhenNoObjectPresent()
  1437. {
  1438. $options = $this->getOptions();
  1439. $options['translator'] = true;
  1440. $options['pluginLoader'] = true;
  1441. $options['view'] = true;
  1442. $this->element->setOptions($options);
  1443. }
  1444. public function testSetOptionsSetsArrayOfStringValidators()
  1445. {
  1446. $this->_checkZf2794();
  1447. $options = $this->getOptions();
  1448. $options['validators'] = array(
  1449. 'notEmpty',
  1450. 'digits'
  1451. );
  1452. $this->element->setOptions($options);
  1453. $validator = $this->element->getValidator('notEmpty');
  1454. $this->assertTrue($validator instanceof Zend_Validate_NotEmpty);
  1455. $validator = $this->element->getValidator('digits');
  1456. $this->assertTrue($validator instanceof Zend_Validate_Digits);
  1457. }
  1458. public function testSetOptionsSetsArrayOfArrayValidators()
  1459. {
  1460. $this->_checkZf2794();
  1461. $options = $this->getOptions();
  1462. $options['validators'] = array(
  1463. array('notEmpty', true, array(Zend_Validate_NotEmpty::ALL)),
  1464. array('digits', true, array('bar')),
  1465. );
  1466. $this->element->setOptions($options);
  1467. $validator = $this->element->getValidator('notEmpty');
  1468. $this->assertTrue($validator instanceof Zend_Validate_NotEmpty);
  1469. $this->assertTrue($validator->zfBreakChainOnFailure);
  1470. $validator = $this->element->getValidator('digits');
  1471. $this->assertTrue($validator instanceof Zend_Validate_Digits);
  1472. $this->assertTrue($validator->zfBreakChainOnFailure);
  1473. }
  1474. public function testSetOptionsSetsArrayOfAssociativeArrayValidators()
  1475. {
  1476. $this->_checkZf2794();
  1477. $options = $this->getOptions();
  1478. $options['validators'] = array(
  1479. array(
  1480. 'options' => array(Zend_Validate_NotEmpty::ALL),
  1481. 'breakChainOnFailure' => true,
  1482. 'validator' => 'notEmpty',
  1483. ),
  1484. array(
  1485. 'options' => array('bar'),
  1486. 'validator' => 'digits',
  1487. 'breakChainOnFailure' => true,
  1488. ),
  1489. );
  1490. $this->element->setOptions($options);
  1491. $validator = $this->element->getValidator('notEmpty');
  1492. $this->assertTrue($validator instanceof Zend_Validate_NotEmpty);
  1493. $this->assertTrue($validator->zfBreakChainOnFailure);
  1494. $validator = $this->element->getValidator('digits');
  1495. $this->assertTrue($validator instanceof Zend_Validate_Digits);
  1496. $this->assertTrue($validator->zfBreakChainOnFailure);
  1497. }
  1498. public function testSetOptionsSetsArrayOfStringFilters()
  1499. {
  1500. $this->_checkZf2794();
  1501. $options = $this->getOptions();
  1502. $options['filters'] = array('StringToUpper', 'Alpha');
  1503. $this->element->setOptions($options);
  1504. $filter = $this->element->getFilter('StringToUpper');
  1505. $this->assertTrue($filter instanceof Zend_Filter_StringToUpper);
  1506. $filter = $this->element->getFilter('Alpha');
  1507. $this->assertTrue($filter instanceof Zend_Filter_Alpha);
  1508. }
  1509. public function testSetOptionsSetsArrayOfArrayFilters()
  1510. {
  1511. $this->_checkZf2794();
  1512. $options = $this->getOptions();
  1513. $options['filters'] = array(
  1514. array('Digits', array('bar' => 'baz')),
  1515. array('Alpha', array('foo')),
  1516. );
  1517. $this->element->setOptions($options);
  1518. $filter = $this->element->getFilter('Digits');
  1519. $this->assertTrue($filter instanceof Zend_Filter_Digits);
  1520. $filter = $this->element->getFilter('Alpha');
  1521. $this->assertTrue($filter instanceof Zend_Filter_Alpha);
  1522. }
  1523. public function testSetOptionsSetsArrayOfAssociativeArrayFilters()
  1524. {
  1525. $this->_checkZf2794();
  1526. $options = $this->getOptions();
  1527. $options['filters'] = array(
  1528. array(
  1529. 'options' => array('baz'),
  1530. 'filter' => 'Digits'
  1531. ),
  1532. array(
  1533. 'options' => array('foo'),
  1534. 'filter' => 'Alpha',
  1535. ),
  1536. );
  1537. $this->element->setOptions($options);
  1538. $filter = $this->element->getFilter('Digits');
  1539. $this->assertTrue($filter instanceof Zend_Filter_Digits);
  1540. $filter = $this->element->getFilter('Alpha');
  1541. $this->assertTrue($filter instanceof Zend_Filter_Alpha);
  1542. }
  1543. public function testSetOptionsSetsArrayOfStringDecorators()
  1544. {
  1545. $this->_checkZf2794();
  1546. $options = $this->getOptions();
  1547. $options['decorators'] = array('label', 'form');
  1548. $this->element->setOptions($options);
  1549. $this->assertFalse($this->element->getDecorator('viewHelper'));
  1550. $this->assertFalse($this->element->getDecorator('errors'));
  1551. $decorator = $this->element->getDecorator('label');
  1552. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Label);
  1553. $decorator = $this->element->getDecorator('form');
  1554. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Form);
  1555. }
  1556. public function testSetOptionsSetsArrayOfArrayDecorators()
  1557. {
  1558. $this->_checkZf2794();
  1559. $options = $this->getOptions();
  1560. $options['decorators'] = array(
  1561. array('label', array('id' => 'mylabel')),
  1562. array('form', array('id' => 'form')),
  1563. );
  1564. $this->element->setOptions($options);
  1565. $this->assertFalse($this->element->getDecorator('viewHelper'));
  1566. $this->assertFalse($this->element->getDecorator('errors'));
  1567. $decorator = $this->element->getDecorator('label');
  1568. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Label);
  1569. $options = $decorator->getOptions();
  1570. $this->assertEquals('mylabel', $options['id']);
  1571. $decorator = $this->element->getDecorator('form');
  1572. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Form);
  1573. $options = $decorator->getOptions();
  1574. $this->assertEquals('form', $options['id']);
  1575. }
  1576. public function testSetOptionsSetsArrayOfAssocArrayDecorators()
  1577. {
  1578. $this->_checkZf2794();
  1579. $options = $this->getOptions();
  1580. $options['decorators'] = array(
  1581. array(
  1582. 'options' => array('id' => 'mylabel'),
  1583. 'decorator' => 'label',
  1584. ),
  1585. array(
  1586. 'options' => array('id' => 'form'),
  1587. 'decorator' => 'form',
  1588. ),
  1589. );
  1590. $this->element->setOptions($options);
  1591. $this->assertFalse($this->element->getDecorator('viewHelper'));
  1592. $this->assertFalse($this->element->getDecorator('errors'));
  1593. $decorator = $this->element->getDecorator('label');
  1594. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Label);
  1595. $options = $decorator->getOptions();
  1596. $this->assertEquals('mylabel', $options['id']);
  1597. $decorator = $this->element->getDecorator('form');
  1598. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Form);
  1599. $options = $decorator->getOptions();
  1600. $this->assertEquals('form', $options['id']);
  1601. }
  1602. public function testSetOptionsSetsGlobalPrefixPaths()
  1603. {
  1604. $options = $this->getOptions();
  1605. $options['prefixPath'] = array(
  1606. 'prefix' => 'Zend_Foo',
  1607. 'path' => 'Zend/Foo/'
  1608. );
  1609. $this->element->setOptions($options);
  1610. foreach (array('validate', 'filter', 'decorator') as $type) {
  1611. $loader = $this->element->getPluginLoader($type);
  1612. $paths = $loader->getPaths('Zend_Foo_' . ucfirst($type));
  1613. $this->assertTrue(is_array($paths), "Failed for type $type: " . var_export($paths, 1));
  1614. $this->assertFalse(empty($paths));
  1615. $this->assertContains('Foo', $paths[0]);
  1616. }
  1617. }
  1618. public function testSetOptionsSetsIndividualPrefixPathsFromKeyedArrays()
  1619. {
  1620. $options = $this->getOptions();
  1621. $options['prefixPath'] = array(
  1622. 'filter' => array('prefix' => 'Zend_Foo', 'path' => 'Zend/Foo/')
  1623. );
  1624. $this->element->setOptions($options);
  1625. $loader = $this->element->getPluginLoader('filter');
  1626. $paths = $loader->getPaths('Zend_Foo');
  1627. $this->assertTrue(is_array($paths));
  1628. $this->assertFalse(empty($paths));
  1629. $this->assertContains('Foo', $paths[0]);
  1630. }
  1631. public function testSetOptionsSetsIndividualPrefixPathsFromUnKeyedArrays()
  1632. {
  1633. $options = $this->getOptions();
  1634. $options['prefixPath'] = array(
  1635. array('type' => 'decorator', 'prefix' => 'Zend_Foo', 'path' => 'Zend/Foo/')
  1636. );
  1637. $this->element->setOptions($options);
  1638. $loader = $this->element->getPluginLoader('decorator');
  1639. $paths = $loader->getPaths('Zend_Foo');
  1640. $this->assertTrue(is_array($paths));
  1641. $this->assertFalse(empty($paths));
  1642. $this->assertContains('Foo', $paths[0]);
  1643. }
  1644. public function testCanSetObjectStateViaSetConfig()
  1645. {
  1646. $config = new Zend_Config($this->getOptions());
  1647. $this->element->setConfig($config);
  1648. $this->assertEquals('changed', $this->element->getName());
  1649. $this->assertEquals('foo', $this->element->getValue());
  1650. $this->assertEquals('bar', $this->element->getLabel());
  1651. $this->assertEquals(50, $this->element->getOrder());
  1652. $this->assertFalse($this->element->isRequired());
  1653. $this->assertEquals('bar', $this->element->foo);
  1654. $this->assertEquals('bat', $this->element->baz);
  1655. }
  1656. public function testPassingConfigObjectToConstructorSetsObjectState()
  1657. {
  1658. $config = new Zend_Config($this->getOptions());
  1659. $element = new Zend_Form_Element($config);
  1660. $this->assertEquals('changed', $element->getName());
  1661. $this->assertEquals('foo', $element->getValue());
  1662. $this->assertEquals('bar', $element->getLabel());
  1663. $this->assertEquals(50, $element->getOrder());
  1664. $this->assertFalse($element->isRequired());
  1665. $this->assertEquals('bar', $element->foo);
  1666. $this->assertEquals('bat', $element->baz);
  1667. }
  1668. public function testValueIsFilteredPriorToValidation()
  1669. {
  1670. $this->_checkZf2794();
  1671. $this->element->addFilter('StringTrim')
  1672. ->addValidator('StringLength', false, array(3, 8));
  1673. $this->assertTrue($this->element->isValid(' foobar '));
  1674. $this->assertEquals('foobar', $this->element->getValue());
  1675. $this->element->setFilters(array('StringTrim'))
  1676. ->setRequired(true)
  1677. ->setValidators(array('NotEmpty'));
  1678. $this->assertFalse($this->element->isValid(' '));
  1679. }
  1680. public function testTranslatedLabel()
  1681. {
  1682. $this->element->setLabel('FooBar');
  1683. $translator = new Zend_Translate('array', array('FooBar' => 'BazBar'));
  1684. $this->element->setTranslator($translator);
  1685. $this->assertEquals('BazBar', $this->element->getLabel());
  1686. }
  1687. // Extensions
  1688. public function testInitCalledBeforeLoadDecorators()
  1689. {
  1690. $element = new Zend_Form_ElementTest_Element('test');
  1691. $decorators = $element->getDecorators();
  1692. $this->assertTrue(empty($decorators));
  1693. }
  1694. /**
  1695. * @group ZF-3217
  1696. */
  1697. public function testElementShouldOverloadToRenderDecorators()
  1698. {
  1699. $this->element->setLabel('Foo Label')
  1700. ->setView($this->getView());
  1701. $html = $this->element->renderViewHelper();
  1702. $this->assertContains('<input', $html);
  1703. $this->assertContains('id="' . $this->element->getFullyQualifiedName() . '"', $html, 'Received: ' . $html);
  1704. $this->assertNotContains('<dd', $html);
  1705. $this->assertNotContains('<label', $html);
  1706. $html = $this->element->renderLabel('this is the content');
  1707. $this->assertRegexp('#<label[^>]*for="' . $this->element->getFullyQualifiedName() . '"[^>]*>Foo Label</label>#', $html);
  1708. $this->assertContains('this is the content', $html);
  1709. $this->assertNotContains('<input', $html);
  1710. }
  1711. /**
  1712. * @group ZF-3217
  1713. * @expectedException Zend_Form_Element_Exception
  1714. */
  1715. public function testOverloadingToInvalidMethodsShouldThrowAnException()
  1716. {
  1717. $html = $this->element->bogusMethodCall();
  1718. }
  1719. /**
  1720. * @group ZF-5150
  1721. */
  1722. public function testMarkingAsErrorShouldCauseIsErrorToReturnFalse()
  1723. {
  1724. $this->element->setValue('foo');
  1725. $this->element->markAsError();
  1726. $this->assertFalse($this->element->isValid('foo'));
  1727. }
  1728. /**
  1729. * @group ZF-4915
  1730. */
  1731. public function testElementShouldAllowSettingDefaultErrorMessageSeparator()
  1732. {
  1733. $this->element->setErrorMessageSeparator('|');
  1734. $this->assertEquals('|', $this->element->getErrorMessageSeparator());
  1735. }
  1736. /**
  1737. * @group ZF-4915
  1738. */
  1739. public function testElementShouldUseSemicolonAndSpaceAsDefaultErrorMessageSeparator()
  1740. {
  1741. $this->assertEquals('; ', $this->element->getErrorMessageSeparator());
  1742. }
  1743. /**
  1744. * Used by test methods susceptible to ZF-2794, marks a test as incomplete
  1745. *
  1746. * @link http://framework.zend.com/issues/browse/ZF-2794
  1747. * @return void
  1748. */
  1749. protected function _checkZf2794()
  1750. {
  1751. if (strtolower(substr(PHP_OS, 0, 3)) == 'win' && version_compare(PHP_VERSION, '5.1.4', '=')) {
  1752. $this->markTestIncomplete('Error occurs for PHP 5.1.4 on Windows');
  1753. }
  1754. }
  1755. /**
  1756. * @ZF-8882
  1757. */
  1758. public function testErrorMessagesShouldNotBeTranslatedWhenTranslatorIsDisabled()
  1759. {
  1760. $translations = array(
  1761. 'foo' => 'Foo message',
  1762. );
  1763. $translate = new Zend_Translate('array', $translations);
  1764. $this->element->setTranslator($translate)
  1765. ->addErrorMessage('foo')
  1766. ->addValidator('Alpha');
  1767. $this->assertFalse($this->element->isValid(123));
  1768. $messages = $this->element->getMessages();
  1769. $this->assertEquals(1, count($messages));
  1770. $this->assertEquals('Foo message', array_shift($messages));
  1771. $this->element->setDisableTranslator(true);
  1772. $this->assertFalse($this->element->isValid(123));
  1773. $messages = $this->element->getMessages();
  1774. $this->assertEquals(1, count($messages));
  1775. $this->assertEquals('foo', array_shift($messages));
  1776. }
  1777. /**
  1778. * @group ZF-9275
  1779. */
  1780. public function testElementDoesntOverrideDefaultValidatorTranslatorWithDefaultRegistryTranslator()
  1781. {
  1782. $registryTranslations = array('alphaInvalid' => 'Registry message');
  1783. $registryTranslate = new Zend_Translate('array', $registryTranslations);
  1784. Zend_Registry::set('Zend_Translate', $registryTranslate);
  1785. $validatorTranslations = array('alphaInvalid' => 'Validator message');
  1786. $validatorTranslate = new Zend_Translate('array', $validatorTranslations);
  1787. Zend_Validate_Abstract::setDefaultTranslator($validatorTranslate);
  1788. $elementTranslations = array('alphaInvalid' => 'Element message');
  1789. $elementTranslate = new Zend_Translate('array', $elementTranslations);
  1790. // the default validate translator should beat the registry one
  1791. $this->element->addValidator('Alpha');
  1792. $this->assertFalse($this->element->isValid(123));
  1793. $messages = $this->element->getMessages();
  1794. $this->assertEquals('Validator message', $messages['alphaInvalid']);
  1795. }
  1796. /**
  1797. * @group ZF-9275
  1798. */
  1799. public function testDefaultTranslatorDoesntOverrideElementTranslatorOnValdiation()
  1800. {
  1801. $registryTranslations = array('alphaInvalid' => 'Registry message');
  1802. $registryTranslate = new Zend_Translate('array', $registryTranslations);
  1803. Zend_Registry::set('Zend_Translate', $registryTranslate);
  1804. $validatorTranslations = array('alphaInvalid' => 'Validator message');
  1805. $validatorTranslate = new Zend_Translate('array', $validatorTranslations);
  1806. Zend_Validate_Abstract::setDefaultTranslator($validatorTranslate);
  1807. $elementTranslations = array('alphaInvalid' => 'Element message');
  1808. $elementTranslate = new Zend_Translate('array', $elementTranslations);
  1809. $this->element->addValidator('Alpha');
  1810. $this->element->setTranslator($elementTranslate);
  1811. $this->assertFalse($this->element->isValid(123));
  1812. $messages = $this->element->getMessages();
  1813. $this->assertEquals('Element message', $messages['alphaInvalid']);
  1814. }
  1815. /**
  1816. * @group ZF-9275
  1817. */
  1818. public function testValidatorsDefaultTranslatorDoesntOverrideFormsDefaultTranslator()
  1819. {
  1820. $formTranslations = array('alphaInvalid' => 'Form message');
  1821. $formTranslate = new Zend_Translate('array', $formTranslations);
  1822. Zend_Form::setDefaultTranslator($formTranslate);
  1823. $validatorTranslations = array('alphaInvalid' => 'Validator message');
  1824. $validatorTranslate = new Zend_Translate('array', $validatorTranslations);
  1825. Zend_Validate_Abstract::setDefaultTranslator($validatorTranslate);
  1826. // the default validate translator should beat the registry one
  1827. $this->element->addValidator('Alpha');
  1828. $this->assertFalse($this->element->isValid(123));
  1829. $messages = $this->element->getMessages();
  1830. $this->assertEquals('Form message', $messages['alphaInvalid']);
  1831. }
  1832. /**
  1833. * @group ZF-9275
  1834. */
  1835. public function testElementsTranslatorDoesntOverrideValidatorsDirectlyAttachedTranslator()
  1836. {
  1837. $elementTranslations = array('alphaInvalid' => 'Element message');
  1838. $elementTranslate = new Zend_Translate('array', $elementTranslations);
  1839. $validatorTranslations = array('alphaInvalid' => 'Direct validator message');
  1840. $validatorTranslate = new Zend_Translate('array', $validatorTranslations);
  1841. $validator = new Zend_Validate_Alpha();
  1842. $validator->setTranslator($validatorTranslate);
  1843. $this->element->addValidator($validator);
  1844. $this->assertFalse($this->element->isValid(123));
  1845. $messages = $this->element->getMessages();
  1846. $this->assertEquals('Direct validator message', $messages['alphaInvalid']);
  1847. }
  1848. /**
  1849. * Prove the fluent interface on Zend_Form::loadDefaultDecorators
  1850. *
  1851. * @link http://framework.zend.com/issues/browse/ZF-9913
  1852. * @return void
  1853. */
  1854. public function testFluentInterfaceOnLoadDefaultDecorators()
  1855. {
  1856. $this->assertSame($this->element, $this->element->loadDefaultDecorators());
  1857. }
  1858. /**
  1859. * @group ZF-7552
  1860. */
  1861. public function testAddDecoratorsKeepsNonNumericKeyNames()
  1862. {
  1863. $this->element->addDecorators(array(array(array('td' => 'HtmlTag'),
  1864. array('tag' => 'td')),
  1865. array(array('tr' => 'HtmlTag'),
  1866. array('tag' => 'tr')),
  1867. array('HtmlTag', array('tag' => 'baz'))));
  1868. $t1 = $this->element->getDecorators();
  1869. $this->element->setDecorators($t1);
  1870. $t2 = $this->element->getDecorators();
  1871. $this->assertEquals($t1, $t2);
  1872. }
  1873. }
  1874. class Zend_Form_ElementTest_Decorator extends Zend_Form_Decorator_Abstract
  1875. {
  1876. }
  1877. class Zend_Form_ElementTest_Element extends Zend_Form_Element
  1878. {
  1879. public function init()
  1880. {
  1881. $this->setDisableLoadDefaultDecorators(true);
  1882. }
  1883. }
  1884. class Zend_Form_ElementTest_ArrayFilter implements Zend_Filter_Interface
  1885. {
  1886. public function filter($value)
  1887. {
  1888. $value = array_filter($value, array($this, '_filter'));
  1889. return $value;
  1890. }
  1891. protected function _filter($value)
  1892. {
  1893. if (is_array($value)) {
  1894. return array_filter($value, array($this, '_filter'));
  1895. }
  1896. return (strstr($value, 'ba'));
  1897. }
  1898. /**
  1899. * Check array notation for validators
  1900. */
  1901. public function testValidatorsGivenArrayKeysOnValidation()
  1902. {
  1903. $username = new Zend_Form_Element('username');
  1904. $username->addValidator('stringLength', true, array('min' => 5, 'max' => 20, 'ignore' => 'something'));
  1905. $form = new Zend_Form(array('elements' => array($username)));
  1906. $this->assertTrue($form->isValid(array('username' => 'abcde')));
  1907. }
  1908. /**
  1909. * @see ZF-6822
  1910. */
  1911. public function testValidatorByUsingStringNotation()
  1912. {
  1913. $this->_checkZf2794();
  1914. $username = new Zend_Form_Element('username');
  1915. $username->addValidator('stringLength', true, array(5, 20))
  1916. ->addValidator('regex', true, '/^[a-zA-Z0-9_]*$/')
  1917. ->addFilter('StringToLower')
  1918. ->setRequired(true);
  1919. $form = new Zend_Form(array('elements' => array($username)));
  1920. $form->isValid(array('username' => '#'));
  1921. $validator = $username->getValidator('stringLength');
  1922. $this->assertTrue($validator->zfBreakChainOnFailure);
  1923. $validator = $username->getValidator('regex');
  1924. $this->assertTrue($validator->zfBreakChainOnFailure);
  1925. }
  1926. }
  1927. if (PHPUnit_MAIN_METHOD == 'Zend_Form_ElementTest::main') {
  1928. Zend_Form_ElementTest::main();
  1929. }