ElementTest.php 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202
  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. class Zend_Form_ElementTest_Decorator extends Zend_Form_Decorator_Abstract
  1850. {
  1851. }
  1852. class Zend_Form_ElementTest_Element extends Zend_Form_Element
  1853. {
  1854. public function init()
  1855. {
  1856. $this->setDisableLoadDefaultDecorators(true);
  1857. }
  1858. }
  1859. class Zend_Form_ElementTest_ArrayFilter implements Zend_Filter_Interface
  1860. {
  1861. public function filter($value)
  1862. {
  1863. $value = array_filter($value, array($this, '_filter'));
  1864. return $value;
  1865. }
  1866. protected function _filter($value)
  1867. {
  1868. if (is_array($value)) {
  1869. return array_filter($value, array($this, '_filter'));
  1870. }
  1871. return (strstr($value, 'ba'));
  1872. }
  1873. /**
  1874. * Check array notation for validators
  1875. */
  1876. public function testValidatorsGivenArrayKeysOnValidation()
  1877. {
  1878. $username = new Zend_Form_Element('username');
  1879. $username->addValidator('stringLength', true, array('min' => 5, 'max' => 20, 'ignore' => 'something'));
  1880. $form = new Zend_Form(array('elements' => array($username)));
  1881. $this->assertTrue($form->isValid(array('username' => 'abcde')));
  1882. }
  1883. /**
  1884. * @see ZF-6822
  1885. */
  1886. public function testValidatorByUsingStringNotation()
  1887. {
  1888. $this->_checkZf2794();
  1889. $username = new Zend_Form_Element('username');
  1890. $username->addValidator('stringLength', true, array(5, 20))
  1891. ->addValidator('regex', true, '/^[a-zA-Z0-9_]*$/')
  1892. ->addFilter('StringToLower')
  1893. ->setRequired(true);
  1894. $form = new Zend_Form(array('elements' => array($username)));
  1895. $form->isValid(array('username' => '#'));
  1896. $validator = $username->getValidator('stringLength');
  1897. $this->assertTrue($validator->zfBreakChainOnFailure);
  1898. $validator = $username->getValidator('regex');
  1899. $this->assertTrue($validator->zfBreakChainOnFailure);
  1900. }
  1901. }
  1902. if (PHPUnit_MAIN_METHOD == 'Zend_Form_ElementTest::main') {
  1903. Zend_Form_ElementTest::main();
  1904. }