ElementTest.php 81 KB

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