PageRenderTime 49ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/libs/Nette/Forms/Controls/BaseControl.php

https://bitbucket.org/jelito/asdf
PHP | 720 lines | 325 code | 132 blank | 263 comment | 28 complexity | 006db735638089abb7e0fe0f11c33bd9 MD5 | raw file
  1. <?php
  2. /**
  3. * This file is part of the Nette Framework (http://nette.org)
  4. * Copyright (c) 2004 David Grudl (http://davidgrudl.com)
  5. */
  6. namespace Nette\Forms\Controls;
  7. use Nette,
  8. Nette\Forms\IControl,
  9. Nette\Utils\Html,
  10. Nette\Utils\Validators,
  11. Nette\Forms\Form;
  12. /**
  13. * Base class that implements the basic functionality common to form controls.
  14. *
  15. * @author David Grudl
  16. *
  17. * @property-read Nette\Forms\Form $form
  18. * @property-read string $htmlName
  19. * @property string $htmlId
  20. * @property-read array $options
  21. * @property Nette\Localization\ITranslator|NULL $translator
  22. * @property mixed $value
  23. * @property-read bool $filled
  24. * @property-write $defaultValue
  25. * @property bool $disabled
  26. * @property bool $omitted
  27. * @property-read Nette\Utils\Html $control
  28. * @property-read Nette\Utils\Html $label
  29. * @property-read Nette\Utils\Html $controlPrototype
  30. * @property-read Nette\Utils\Html $labelPrototype
  31. * @property-read Nette\Forms\Rules $rules
  32. * @property bool $required
  33. * @property-read array $errors
  34. */
  35. abstract class BaseControl extends Nette\ComponentModel\Component implements IControl
  36. {
  37. /** @var string */
  38. public static $idMask = 'frm-%s';
  39. /** @var string textual caption or label */
  40. public $caption;
  41. /** @var mixed current control value */
  42. protected $value;
  43. /** @var Nette\Utils\Html control element template */
  44. protected $control;
  45. /** @var Nette\Utils\Html label element template */
  46. protected $label;
  47. /** @var array */
  48. private $errors = array();
  49. /** @var bool */
  50. protected $disabled = FALSE;
  51. /** @var bool */
  52. private $omitted = FALSE;
  53. /** @var Nette\Forms\Rules */
  54. private $rules;
  55. /** @var Nette\Localization\ITranslator */
  56. private $translator = TRUE; // means autodetect
  57. /** @var array user options */
  58. private $options = array();
  59. /**
  60. * @param string caption
  61. */
  62. public function __construct($caption = NULL)
  63. {
  64. $this->monitor('Nette\Forms\Form');
  65. parent::__construct();
  66. $this->control = Html::el('input', array('type' => NULL, 'name' => NULL));
  67. $this->label = Html::el('label');
  68. $this->caption = $caption;
  69. $this->rules = new Nette\Forms\Rules($this);
  70. $this->setValue(NULL);
  71. }
  72. /**
  73. * This method will be called when the component becomes attached to Form.
  74. * @param Nette\ComponentModel\IComponent
  75. * @return void
  76. */
  77. protected function attached($form)
  78. {
  79. if (!$this->isDisabled() && $form instanceof Form && $form->isAnchored() && $form->isSubmitted()) {
  80. $this->loadHttpData();
  81. }
  82. }
  83. /**
  84. * Returns form.
  85. * @param bool throw exception if form doesn't exist?
  86. * @return Nette\Forms\Form
  87. */
  88. public function getForm($need = TRUE)
  89. {
  90. return $this->lookup('Nette\Forms\Form', $need);
  91. }
  92. /**
  93. * Loads HTTP data.
  94. * @return void
  95. */
  96. public function loadHttpData()
  97. {
  98. $this->setValue($this->getHttpData(Form::DATA_TEXT));
  99. }
  100. /**
  101. * Loads HTTP data.
  102. * @return mixed
  103. */
  104. public function getHttpData($type, $htmlTail = NULL)
  105. {
  106. return $this->getForm()->getHttpData($type, $this->getHtmlName() . $htmlTail);
  107. }
  108. /**
  109. * Returns HTML name of control.
  110. * @return string
  111. */
  112. public function getHtmlName()
  113. {
  114. return Nette\Forms\Helpers::generateHtmlName($this->lookupPath('Nette\Forms\Form'));
  115. }
  116. /********************* interface IFormControl ****************d*g**/
  117. /**
  118. * Sets control's value.
  119. * @return self
  120. */
  121. public function setValue($value)
  122. {
  123. $this->value = $value;
  124. return $this;
  125. }
  126. /**
  127. * Returns control's value.
  128. * @return mixed
  129. */
  130. public function getValue()
  131. {
  132. return $this->value;
  133. }
  134. /**
  135. * Is control filled?
  136. * @return bool
  137. */
  138. public function isFilled()
  139. {
  140. $value = $this->getValue();
  141. return $value !== NULL && $value !== array() && $value !== '';
  142. }
  143. /**
  144. * Sets control's default value.
  145. * @return self
  146. */
  147. public function setDefaultValue($value)
  148. {
  149. $form = $this->getForm(FALSE);
  150. if ($this->isDisabled() || !$form || !$form->isAnchored() || !$form->isSubmitted()) {
  151. $this->setValue($value);
  152. }
  153. return $this;
  154. }
  155. /**
  156. * Disables or enables control.
  157. * @param bool
  158. * @return self
  159. */
  160. public function setDisabled($value = TRUE)
  161. {
  162. if ($this->disabled = (bool) $value) {
  163. $this->omitted = TRUE;
  164. $this->setValue(NULL);
  165. }
  166. return $this;
  167. }
  168. /**
  169. * Is control disabled?
  170. * @return bool
  171. */
  172. public function isDisabled()
  173. {
  174. return $this->disabled === TRUE;
  175. }
  176. /**
  177. * Sets whether control value is excluded from $form->getValues() result.
  178. * @param bool
  179. * @return self
  180. */
  181. public function setOmitted($value = TRUE)
  182. {
  183. $this->omitted = (bool) $value;
  184. return $this;
  185. }
  186. /**
  187. * Is control value excluded from $form->getValues() result?
  188. * @return bool
  189. */
  190. public function isOmitted()
  191. {
  192. return $this->omitted;
  193. }
  194. /********************* rendering ****************d*g**/
  195. /**
  196. * Generates control's HTML element.
  197. * @return Nette\Utils\Html
  198. */
  199. public function getControl()
  200. {
  201. $this->setOption('rendered', TRUE);
  202. $el = clone $this->control;
  203. return $el->addAttributes(array(
  204. 'name' => $this->getHtmlName(),
  205. 'id' => $this->getHtmlId(),
  206. 'required' => $this->isRequired(),
  207. 'disabled' => $this->isDisabled(),
  208. 'data-nette-rules' => self::exportRules($this->rules) ?: NULL,
  209. ));
  210. }
  211. /**
  212. * Generates label's HTML element.
  213. * @param string
  214. * @return Nette\Utils\Html
  215. */
  216. public function getLabel($caption = NULL)
  217. {
  218. $label = clone $this->label;
  219. $label->for = $this->getHtmlId();
  220. $label->setText($this->translate($caption === NULL ? $this->caption : $caption));
  221. return $label;
  222. }
  223. /**
  224. * Returns control's HTML element template.
  225. * @return Nette\Utils\Html
  226. */
  227. public function getControlPrototype()
  228. {
  229. return $this->control;
  230. }
  231. /**
  232. * Returns label's HTML element template.
  233. * @return Nette\Utils\Html
  234. */
  235. public function getLabelPrototype()
  236. {
  237. return $this->label;
  238. }
  239. /**
  240. * Changes control's HTML id.
  241. * @param string new ID, or FALSE or NULL
  242. * @return self
  243. */
  244. public function setHtmlId($id)
  245. {
  246. $this->control->id = $id;
  247. return $this;
  248. }
  249. /**
  250. * Returns control's HTML id.
  251. * @return string
  252. */
  253. public function getHtmlId()
  254. {
  255. if (!isset($this->control->id)) {
  256. $this->control->id = sprintf(self::$idMask, $this->lookupPath());
  257. }
  258. return $this->control->id;
  259. }
  260. /**
  261. * Changes control's HTML attribute.
  262. * @param string name
  263. * @param mixed value
  264. * @return self
  265. */
  266. public function setAttribute($name, $value = TRUE)
  267. {
  268. $this->control->$name = $value;
  269. return $this;
  270. }
  271. /********************* translator ****************d*g**/
  272. /**
  273. * Sets translate adapter.
  274. * @return self
  275. */
  276. public function setTranslator(Nette\Localization\ITranslator $translator = NULL)
  277. {
  278. $this->translator = $translator;
  279. return $this;
  280. }
  281. /**
  282. * Returns translate adapter.
  283. * @return Nette\Localization\ITranslator|NULL
  284. */
  285. public function getTranslator()
  286. {
  287. if ($this->translator === TRUE) {
  288. return $this->getForm(FALSE) ? $this->getForm()->getTranslator() : NULL;
  289. }
  290. return $this->translator;
  291. }
  292. /**
  293. * Returns translated string.
  294. * @param mixed
  295. * @param int plural count
  296. * @return string
  297. */
  298. public function translate($value, $count = NULL)
  299. {
  300. if ($translator = $this->getTranslator()) {
  301. $tmp = is_array($value) ? array(& $value) : array(array(& $value));
  302. foreach ($tmp[0] as & $v) {
  303. if ($v != NULL && !$v instanceof Html) { // intentionally ==
  304. $v = $translator->translate((string) $v, $count);
  305. }
  306. }
  307. }
  308. return $value;
  309. }
  310. /********************* rules ****************d*g**/
  311. /**
  312. * Adds a validation rule.
  313. * @param mixed rule type
  314. * @param string message to display for invalid data
  315. * @param mixed optional rule arguments
  316. * @return self
  317. */
  318. public function addRule($validator, $message = NULL, $arg = NULL)
  319. {
  320. $this->rules->addRule($validator, $message, $arg);
  321. return $this;
  322. }
  323. /**
  324. * Adds a validation condition a returns new branch.
  325. * @param mixed condition type
  326. * @param mixed optional condition arguments
  327. * @return Nette\Forms\Rules new branch
  328. */
  329. public function addCondition($validator, $value = NULL)
  330. {
  331. return $this->rules->addCondition($validator, $value);
  332. }
  333. /**
  334. * Adds a validation condition based on another control a returns new branch.
  335. * @param Nette\Forms\IControl form control
  336. * @param mixed condition type
  337. * @param mixed optional condition arguments
  338. * @return Nette\Forms\Rules new branch
  339. */
  340. public function addConditionOn(IControl $control, $validator, $value = NULL)
  341. {
  342. return $this->rules->addConditionOn($control, $validator, $value);
  343. }
  344. /**
  345. * @return Nette\Forms\Rules
  346. */
  347. public function getRules()
  348. {
  349. return $this->rules;
  350. }
  351. /**
  352. * Makes control mandatory.
  353. * @param mixed state or error message
  354. * @return self
  355. */
  356. public function setRequired($value = TRUE)
  357. {
  358. $this->rules->setRequired($value);
  359. return $this;
  360. }
  361. /**
  362. * Is control mandatory?
  363. * @return bool
  364. */
  365. public function isRequired()
  366. {
  367. return $this->rules->isRequired();
  368. }
  369. /**
  370. * Performs the server side validation.
  371. * @return void
  372. */
  373. public function validate()
  374. {
  375. if ($this->isDisabled()) {
  376. return;
  377. }
  378. $this->cleanErrors();
  379. $this->rules->validate();
  380. }
  381. /**
  382. * Adds error message to the list.
  383. * @param string error message
  384. * @return void
  385. */
  386. public function addError($message)
  387. {
  388. $this->errors[] = $message;
  389. }
  390. /**
  391. * Returns errors corresponding to control.
  392. * @return string
  393. */
  394. public function getError()
  395. {
  396. return $this->errors ? implode(' ', array_unique($this->errors)) : NULL;
  397. }
  398. /**
  399. * Returns errors corresponding to control.
  400. * @return array
  401. */
  402. public function getErrors()
  403. {
  404. return array_unique($this->errors);
  405. }
  406. /**
  407. * @return bool
  408. */
  409. public function hasErrors()
  410. {
  411. return (bool) $this->errors;
  412. }
  413. /**
  414. * @return void
  415. */
  416. public function cleanErrors()
  417. {
  418. $this->errors = array();
  419. }
  420. /**
  421. * @return array
  422. */
  423. protected static function exportRules($rules)
  424. {
  425. $payload = array();
  426. foreach ($rules as $rule) {
  427. if (!is_string($op = $rule->validator)) {
  428. if (!Nette\Utils\Callback::isStatic($op)) {
  429. continue;
  430. }
  431. $op = Nette\Utils\Callback::toString($op);
  432. }
  433. if ($rule->branch) {
  434. $item = array(
  435. 'op' => ($rule->isNegative ? '~' : '') . $op,
  436. 'rules' => static::exportRules($rule->branch, FALSE),
  437. 'control' => $rule->control->getHtmlName()
  438. );
  439. if ($rule->branch->getToggles()) {
  440. $item['toggle'] = $rule->branch->getToggles();
  441. }
  442. } else {
  443. $item = array('op' => ($rule->isNegative ? '~' : '') . $op, 'msg' => $rules->formatMessage($rule, FALSE));
  444. }
  445. if (is_array($rule->arg)) {
  446. foreach ($rule->arg as $key => $value) {
  447. $item['arg'][$key] = $value instanceof IControl ? array('control' => $value->getHtmlName()) : $value;
  448. }
  449. } elseif ($rule->arg !== NULL) {
  450. $item['arg'] = $rule->arg instanceof IControl ? array('control' => $rule->arg->getHtmlName()) : $rule->arg;
  451. }
  452. $payload[] = $item;
  453. }
  454. return $payload;
  455. }
  456. /********************* validators ****************d*g**/
  457. /**
  458. * Is control's value equal with second parameter?
  459. * @return bool
  460. */
  461. public static function validateEqual(IControl $control, $arg)
  462. {
  463. $value = $control->getValue();
  464. foreach ((is_array($value) ? $value : array($value)) as $val) {
  465. foreach ((is_array($arg) ? $arg : array($arg)) as $item) {
  466. if ((string) $val === (string) $item) {
  467. continue 2;
  468. }
  469. }
  470. return FALSE;
  471. }
  472. return TRUE;
  473. }
  474. /**
  475. * Is control's value not equal with second parameter?
  476. * @return bool
  477. */
  478. public static function validateNotEqual(IControl $control, $arg)
  479. {
  480. return !static::validateEqual($control, $arg);
  481. }
  482. /**
  483. * Is control filled?
  484. * @return bool
  485. */
  486. public static function validateFilled(IControl $control)
  487. {
  488. return $control->isFilled();
  489. }
  490. /**
  491. * Is control not filled?
  492. * @return bool
  493. */
  494. public static function validateBlank(IControl $control)
  495. {
  496. return !$control->isFilled();
  497. }
  498. /**
  499. * Is control valid?
  500. * @return bool
  501. */
  502. public static function validateValid(IControl $control)
  503. {
  504. return $control->getRules()->validate();
  505. }
  506. /**
  507. * Is a control's value number in specified range?
  508. * @return bool
  509. */
  510. public static function validateRange(IControl $control, $range)
  511. {
  512. return Validators::isInRange($control->getValue(), $range);
  513. }
  514. /**
  515. * Is a control's value number greater than or equal to the specified minimum?
  516. * @return bool
  517. */
  518. public static function validateMin(IControl $control, $minimum)
  519. {
  520. return Validators::isInRange($control->getValue(), array($minimum, NULL));
  521. }
  522. /**
  523. * Is a control's value number less than or equal to the specified maximum?
  524. * @return bool
  525. */
  526. public static function validateMax(IControl $control, $maximum)
  527. {
  528. return Validators::isInRange($control->getValue(), array(NULL, $maximum));
  529. }
  530. /**
  531. * Count/length validator. Range is array, min and max length pair.
  532. * @return bool
  533. */
  534. public static function validateLength(IControl $control, $range)
  535. {
  536. if (!is_array($range)) {
  537. $range = array($range, $range);
  538. }
  539. $value = $control->getValue();
  540. return Validators::isInRange(is_array($value) ? count($value) : Nette\Utils\Strings::length($value), $range);
  541. }
  542. /**
  543. * Has control's value minimal count/length?
  544. * @return bool
  545. */
  546. public static function validateMinLength(IControl $control, $length)
  547. {
  548. return static::validateLength($control, array($length, NULL));
  549. }
  550. /**
  551. * Is control's value count/length in limit?
  552. * @return bool
  553. */
  554. public static function validateMaxLength(IControl $control, $length)
  555. {
  556. return static::validateLength($control, array(NULL, $length));
  557. }
  558. /********************* user data ****************d*g**/
  559. /**
  560. * Sets user-specific option.
  561. * @return self
  562. */
  563. public function setOption($key, $value)
  564. {
  565. if ($value === NULL) {
  566. unset($this->options[$key]);
  567. } else {
  568. $this->options[$key] = $value;
  569. }
  570. return $this;
  571. }
  572. /**
  573. * Returns user-specific option.
  574. * @return mixed
  575. */
  576. public function getOption($key, $default = NULL)
  577. {
  578. return isset($this->options[$key]) ? $this->options[$key] : $default;
  579. }
  580. /**
  581. * Returns user-specific options.
  582. * @return array
  583. */
  584. public function getOptions()
  585. {
  586. return $this->options;
  587. }
  588. }