| @@ -8,8 +8,11 @@ | ||
| 8 | 8 | declare( strict_types=1 ); |
| 9 | 9 | |
| 10 | 10 | namespace Packetery\Module; |
| 11 | 11 | |
| 12 | +use Packetery\Module\Options\OptionsProvider; | |
| 13 | +use Packetery\Nette\Forms\Container; | |
| 14 | +use Packetery\Nette\Forms\Controls\TextInput; | |
| 12 | 15 | use Packetery\Nette\Forms\Form; |
| 13 | 16 | use Packetery\Nette\Forms\Validator; |
| 14 | 17 | use Packetery\Nette\Http\Request; |
| 15 | 18 | |
| @@ -18,21 +21,13 @@ | ||
| 18 | 21 | * |
| 19 | 22 | * @package Packetery |
| 20 | 23 | */ |
| 21 | 24 | class FormFactory { |
| 22 | - | |
| 23 | 25 | /** |
| 24 | - * HTTP Request. | |
| 25 | - * | |
| 26 | 26 | * @var Request |
| 27 | 27 | */ |
| 28 | 28 | private $request; |
| 29 | 29 | |
| 30 | - /** | |
| 31 | - * Plugin constructor. | |
| 32 | - * | |
| 33 | - * @param Request $request HTTP request. | |
| 34 | - */ | |
| 35 | 30 | public function __construct( Request $request ) { |
| 36 | 31 | add_action( |
| 37 | 32 | 'init', |
| 38 | 33 | function () { |
| @@ -61,10 +56,51 @@ | ||
| 61 | 56 | * |
| 62 | 57 | * @return Form |
| 63 | 58 | */ |
| 64 | 59 | public function create( ?string $name = null ): Form { |
| 65 | - $form = new Form( $name ); | |
| 66 | - $form->setHttpRequest( $this->request ); | |
| 60 | + $form = new Form( $name ); | |
| 61 | + $form->httpRequest = $this->request; | |
| 67 | 62 | $form->allowCrossOrigin(); |
| 63 | + | |
| 68 | 64 | return $form; |
| 65 | + } | |
| 66 | + | |
| 67 | + public function addDimension( Container $container, string $name, string $label, string $unit ): TextInput { | |
| 68 | + $numberInputType = $this->getNumType( $unit ); | |
| 69 | + | |
| 70 | + switch ( $numberInputType ) { | |
| 71 | + case Form::INTEGER: | |
| 72 | + $numberInput = $container->addInteger( $name, sprintf( '%s (%s)', $label, $unit ) ); | |
| 73 | + | |
| 74 | + break; | |
| 75 | + case Form::FLOAT: | |
| 76 | + $numberInput = $container->addText( $name, sprintf( '%s (%s)', $label, $unit ) )->addRule( Form::FLOAT ); | |
| 77 | + | |
| 78 | + break; | |
| 79 | + default: | |
| 80 | + throw new \InvalidArgumentException( 'Unsupported number input type: ' . $numberInputType ); | |
| 81 | + } | |
| 82 | + | |
| 83 | + $numberInput | |
| 84 | + ->setHtmlType( 'number' ) | |
| 85 | + ->setHtmlAttribute( 'step', 'any' ) | |
| 86 | + ->addRule( Form::MIN, null, $this->setMinValue( $unit ) ); | |
| 87 | + | |
| 88 | + return $numberInput; | |
| 89 | + } | |
| 90 | + | |
| 91 | + private function getNumType( string $unit ): string { | |
| 92 | + if ( $unit === OptionsProvider::DIMENSIONS_UNIT_CM ) { | |
| 93 | + return Form::FLOAT; | |
| 94 | + } | |
| 95 | + | |
| 96 | + return Form::INTEGER; | |
| 97 | + } | |
| 98 | + | |
| 99 | + private function setMinValue( string $unit ): float { | |
| 100 | + if ( $unit === OptionsProvider::DIMENSIONS_UNIT_CM ) { | |
| 101 | + return 0.1; | |
| 102 | + } | |
| 103 | + | |
| 104 | + return 1; | |
| 69 | 105 | } |
| 70 | 106 | } |