## Apache Zeta Components Manual :: File Source for input.php

## Source for file input.php

Documentation is available at input.php

1. <?php
2. /**
3. * File containing the ezcConsoleInput class.
4. *
5. * Licensed to the Apache Software Foundation (ASF) under one
6. * or more contributor license agreements. See the NOTICE file
7. * distributed with this work for additional information
8. * regarding copyright ownership. The ASF licenses this file
9. * to you under the Apache License, Version 2.0 (the
10. * "License"); you may not use this file except in compliance
11. * with the License. You may obtain a copy of the License at
12. *
13. * http://www.apache.org/licenses/LICENSE-2.0
14. *
15. * Unless required by applicable law or agreed to in writing,
16. * software distributed under the License is distributed on an
17. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
18. * KIND, either express or implied. See the License for the
19. * specific language governing permissions and limitations
20. * under the License.
21. *
22. * @package ConsoleTools
23. * @version //autogentag//
24. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
25. * @filesource
26. */
28. /**
29. * The ezcConsoleInput class handles the given options and arguments on the console.
30. *
31. * This class allows the complete handling of options and arguments submitted
32. * to a console based application.
33. *
34. * The next example demonstrate how to capture the console options:
35. *
36. * <code>
37. * $optionHandler = new ezcConsoleInput();
38. *
39. * // Register simple parameter -h/--help
40. * $optionHandler->registerOption( new ezcConsoleOption( 'h', 'help' ) );
41. *
42. * // Register complex parameter -f/--file
43. * $file = new ezcConsoleOption(
44. * 'f',
45. * 'file',
46. * ezcConsoleInput::TYPE_STRING,
47. * null,
48. * false,
49. * 'Process a file.',
50. * 'Processes a single file.'
51. * );
52. * $optionHandler->registerOption( $file );
53. *
54. * // Manipulate parameter -f/--file after registration
55. * $file->multiple = true;
56. *
57. * // Register another complex parameter that depends on -f and excludes -h
58. * $dir = new ezcConsoleOption(
59. * 'd',
60. * 'dir',
61. * ezcConsoleInput::TYPE_STRING,
62. * null,
63. * true,
64. * 'Process a directory.',
65. * 'Processes a complete directory.',
66. * array( new ezcConsoleOptionRule( $optionHandler->getOption( 'f' ) ) ),
67. * array( new ezcConsoleOptionRule( $optionHandler->getOption( 'h' ) ) )
68. * );
69. * $optionHandler->registerOption( $dir );
70. *
71. * // Register an alias for this parameter
72. * $optionHandler->registerAlias( 'e', 'extended-dir', $dir );
73. *
74. * // Process registered parameters and handle errors
75. * try
76. * {
77. * $optionHandler->process( array( 'example_input.php', '-h' ) );
78. * }
79. * catch ( ezcConsoleOptionException $e )
80. * {
81. * echo $e->getMessage();
82. * exit( 1 );
83. * }
84. *
85. * // Process a single parameter
86. * $file = $optionHandler->getOption( 'f' );
87. * if ( $file->value === false )
88. * {
89. * echo "Parameter -{$file->short}/--{$file->long} was not submitted.\n";
90. * }
91. * elseif ( $file->value === true )
92. * {
93. * echo "Parameter -{$file->short}/--{$file->long} was submitted without value.\n";
94. * }
95. * else
96. * {
97. * echo "Parameter -{$file->short}/--{$file->long} was submitted with value '".var_export($file->value, true)."'.\n";
98. * }
99. *
100. * // Process all parameters at once:
101. * foreach ( $optionHandler->getOptionValues() as $paramShort => $val )
102. * {
103. * switch ( true )
104. * {
105. * case $val === false:
106. * echo "Parameter $paramShort was not submitted.\n";
107. * break;
108. * case $val === true:
109. * echo "Parameter $paramShort was submitted without a value.\n";
110. * break;
111. * case is_array( $val ):
112. * echo "Parameter $paramShort was submitted multiple times with value: '".implode(', ', $val)."'.\n";
113. * break;
114. * default:
115. * echo "Parameter $paramShort was submitted with value: '$val'.\n";
116. * break;
117. * }
118. * }
119. * </code>
120. *
121. * @package ConsoleTools
122. * @version //autogen//
123. * @mainclass
124. *
125. * @property ezcConsoleArguments $argumentDefinition Optional argument definition.
126. */
127. class ezcConsoleInput
128. {
129. /**
130. * Option does not carry a value.
131. */
132. const TYPE_NONE = 1;
134. /**
135. * Option takes an integer value.
136. */
137. const TYPE_INT = 2;
139. /**
140. * Option takes a string value.
141. */
142. const TYPE_STRING = 3;
144. /**
145. * Array of option definitions, indexed by number.
146. *
147. * This array stores the ezcConsoleOption objects representing
148. * the options.
149. *
150. * For lookup of an option after its short or long values the attributes
151. * {@link ezcConsoleInput::$optionShort}
152. * {@link ezcConsoleInput::$optionLong}
153. * are used.
154. *
155. * @var array(array)
156. */
157. private $options = array();
159. /**
160. * Short option names.
161. *
162. * Each references a key in {@link ezcConsoleInput::$options}.
163. *
164. * @var array(string=>int)
165. */
166. private $optionShort = array();
168. /**
169. * Long option names.
170. *
171. * Each references a key in {@link ezcConsoleInput::$options}.
172. *
173. * @var array(string=>int)
174. */
175. private $optionLong = array();
177. /**
178. * Arguments, if submitted, are stored here.
179. *
180. * @var array(string)
181. */
182. private $arguments = array();
184. /**
185. * Wether the process() method has already been called.
186. *
187. * @var bool
188. */
189. private $processed = false;
191. /**
192. * Indicates if an option was submitted, that has the isHelpOption flag set.
193. *
194. * @var bool
195. */
196. private $helpOptionSet = false;
198. /**
199. * Tool object for multi-byte encoding safe string operations.
200. *
201. * @var ezcConsoleStringTool
202. */
203. private $stringTool;
205. /**
206. * Input validator.
207. *
208. * @var ezcConsoleInputValidator
209. */
210. private $validator;
212. /**
213. * Help generator.
214. *
215. * @var ezcConsoleInputHelpGenerator
216. */
217. private $helpGenerator;
219. /**
220. * Collection of properties.
221. *
222. * @var array(string=>mixed)
223. */
224. protected $properties = array();
226. /**
227. * Creates an input handler.
228. */
229. public function __construct ()
230. {
231. $this->argumentDefinition = null;
232. $this->stringTool = new ezcConsoleStringTool();
234. // @TODO Verify interface and make plugable
235. $this->validator = new ezcConsoleStandardInputValidator();
236. $this->helpGenerator = new ezcConsoleInputStandardHelpGenerator( $this );
237. }
239. /**
240. * Registers the new option $option.
241. *
242. * This method adds the new option $option to your option collection. If
243. * already an option with the assigned short or long value exists, an
244. * exception will be thrown.
245. *
246. * @see ezcConsoleInput::unregisterOption()
247. *
248. * @param ezcConsoleOption $option
249. *
250. * @return ezcConsoleOption The recently registered option.
251. */
252. public function registerOption ( ezcConsoleOption $option )
253. {
254. foreach ( $this->optionShort as $short => $ref )
255. {
256. if ( $short === $option->short )
257. {
258. throw new ezcConsoleOptionAlreadyRegisteredException ( $short );
259. }
260. }
261. foreach ( $this->optionLong as $long => $ref )
262. {
263. if ( $long === $option->long )
264. {
265. throw new ezcConsoleOptionAlreadyRegisteredException ( $long );
266. }
267. }
268. $this->options[] = $option;
269. $this->optionLong[$option->long] = $option;
270. if ( $option->short !== "" )
271. {
272. $this->optionShort[$option->short] = $option;
273. }
274. return $option;
275. }
277. /**
278. * Registers an alias for an option.
279. *
280. * Registers a new alias for an existing option. Aliases can
281. * be used as if they were a normal option.
282. *
283. * The alias is registered with the short option name $short and the
284. * long option name $long. The alias references to the existing
285. * option $option.
286. *
287. * @see ezcConsoleInput::unregisterAlias()
288. *
289. * @param string $short
290. * @param string $long
291. * @param ezcConsoleOption $option
292. *
293. *
294. * @throws ezcConsoleOptionNotExistsException
295. * If the referenced option is not registered.
296. * @throws ezcConsoleOptionAlreadyRegisteredException
297. * If another option/alias has taken the provided short or long name.
298. * @return void
299. */
300. public function registerAlias ( $short, $long, ezcConsoleOption $option )
301. {
302. if ( !isset( $this->optionShort[$option->short] ) || !isset( $this->optionLong[$option->long] ) )
303. {
304. throw new ezcConsoleOptionNotExistsException ( $option->long );
305. }
306. if ( isset( $this->optionShort[$short] ) || isset( $this->optionLong[$long] ) )
307. {
308. throw new ezcConsoleOptionAlreadyRegisteredException ( isset( $this->optionShort[$short] ) ? "-$short" : "--$long" );
309. }
310. $this->optionShort[$short] = $option;
311. $this->optionLong[$long] = $option;
312. }
314. /**
315. * Registers options according to a string specification.
316. *
317. * Accepts a string to define parameters and registers all parameters as
318. * options accordingly. String definition, specified in $optionDef, looks
319. * like this:
320. *
321. * <code>
322. * [s:|size:][u:|user:][a:|all:]
323. * </code>
324. *
325. * This string registers 3 parameters:
326. * -s / --size
327. * -u / --user
328. * -a / --all
329. *
330. * @param string $optionDef
331. * @return void
332. *
333. * @throws ezcConsoleOptionStringNotWellformedException
334. * If provided string does not have the correct format.
335. */
336. public function registerOptionString ( $optionDef )
337. {
338. $regex = '\[([a-z0-9-]+)([:?*+])?([^|]*)\|([a-z0-9-]+)([:?*+])?\]';
339. // Check string for wellformedness
340. if ( preg_match ( "/^($regex)+$/", $optionDef ) == 0 )
341. {
342. throw new ezcConsoleOptionStringNotWellformedException ( "Option definition not wellformed: \"$optionDef\"" );
343. }
344. if ( preg_match_all ( "/$regex/", $optionDef, $matches ) )
345. {
346. foreach ( $matches[1] as $id => $short )
347. {
348. $option = null;
349. $option = new ezcConsoleOption ( $short, $matches[4][$id] );
350. if ( !empty( $matches[2][$id] ) || !empty( $matches[5][$id] ) )
351. {
352. switch ( !empty( $matches[2][$id] ) ? $matches[2][$id] : $matches[5][$id] )
353. {
354. case '*':
355. // Allows 0 or more occurances
356. $option->multiple = true;
357. break;
358. case '+':
359. // Allows 1 or more occurances
360. $option->multiple = true;
361. $option->type = self::TYPE_STRING;
362. break;
363. case '?':
364. $option->type = self::TYPE_STRING;
365. $option->default = '';
366. break;
367. default:
368. break;
369. }
370. }
371. if ( !empty( $matches[3][$id] ) )
372. {
373. $option->default = $matches[3][$id];
374. }
375. $this-> registerOption ( $option );
376. }
377. }
378. }
380. /**
381. * Removes an option.
382. *
383. * This function removes an option. All dependencies to that
384. * specific option are removed completely from every other registered
385. * option.
386. *
387. * @see ezcConsoleInput::registerOption()
388. *
389. * @param ezcConsoleOption $option The option object to unregister.
390. *
391. * @throws ezcConsoleOptionNotExistsException
392. * If requesting a not registered option.
393. * @return void
394. */
395. public function unregisterOption ( ezcConsoleOption $option )
396. {
397. $found = false;
398. foreach ( $this->options as $id => $existParam )
399. {
400. if ( $existParam === $option )
401. {
402. $found = true;
403. unset( $this->options[$id] );
404. continue;
405. }
406. $existParam->removeAllExclusions( $option );
407. $existParam->removeAllDependencies( $option );
408. }
409. if ( $found === false )
410. {
411. throw new ezcConsoleOptionNotExistsException ( $option->long );
412. }
413. foreach ( $this->optionLong as $name => $existParam )
414. {
415. if ( $existParam === $option )
416. {
417. unset( $this->optionLong[$name] );
418. }
419. }
420. foreach ( $this->optionShort as $name => $existParam )
421. {
422. if ( $existParam === $option )
423. {
424. unset( $this->optionShort[$name] );
425. }
426. }
427. }
429. /**
430. * Removes an alias to an option.
431. *
432. * This function removes an alias with the short name $short and long
433. * name $long.
434. *
435. * @see ezcConsoleInput::registerAlias()
436. *
437. * @throws ezcConsoleOptionNoAliasException
438. * If the requested short/long name belongs to a real parameter instead.
439. *
440. * @param string $short
441. * @param string $long
442. * @return void
443. *
444. * @todo Check if $short and $long refer to the same option!
445. */
446. public function unregisterAlias ( $short, $long )
447. {
448. foreach ( $this->options as $id => $option )
449. {
450. if ( $option->short === $short )
451. {
452. throw new ezcConsoleOptionNoAliasException ( $short );
453. }
454. if ( $option->long === $long )
455. {
456. throw new ezcConsoleOptionNoAliasException ( $long );
457. }
458. }
459. if ( isset( $this->optionShort[$short] ) )
460. {
461. unset( $this->optionShort[$short] );
462. }
463. if ( isset( $this->optionLong[$long] ) )
464. {
465. unset( $this->optionLong[$long] );
466. }
467. }
469. /**
470. * Returns the definition object for the option with the name $name.
471. *
472. * This method receives the long or short name of an option and
473. * returns the ezcConsoleOption object.
474. *
475. * @param string $name Short or long name of the option (without - or --).
476. * @return ezcConsoleOption
477. *
478. * @throws ezcConsoleOptionNotExistsException
479. * If requesting a not registered parameter.
480. */
481. public function getOption ( $name )
482. {
483. $name = $name;
484. if ( isset( $this->optionShort[$name] ) )
485. {
486. return $this->optionShort[$name];
487. }
488. if ( isset( $this->optionLong[$name] ) )
489. {
490. return $this->optionLong[$name];
491. }
492. throw new ezcConsoleOptionNotExistsException ( $name );
493. }
495. /**
496. * Process the input parameters.
497. *
498. * Actually process the input options and arguments according to the actual
499. * settings.
500. *
501. * Per default this method uses $argc and $argv for processing. You can
502. * override this setting with your own input, if necessary, using the
503. * parameters of this method. (Attention, first argument is always the pro
504. * gram name itself!)
505. *
506. * All exceptions thrown by this method contain an additional attribute "option"
507. * which specifies the parameter on which the error occurred.
508. *
509. * @param array(string) $args The arguments
510. * @return void
511. *
512. * @throws ezcConsoleOptionNotExistsException
513. * If an option that was submitted does not exist.
514. * @throws ezcConsoleOptionDependencyViolationException
515. * If a dependency rule was violated.
516. * @throws ezcConsoleOptionExclusionViolationException
517. * If an exclusion rule was violated.
518. * @throws ezcConsoleOptionTypeViolationException
519. * If the type of a submitted value violates the options type rule.
520. * @throws ezcConsoleOptionArgumentsViolationException
521. * If arguments are passed although a parameter disallowed them.
522. *
523. * @see ezcConsoleOptionException
524. */
525. public function process ( array $args = null )
526. {
527. if ( $this->processed )
528. {
529. $this-> reset ();
530. }
531. $this->processed = true;
533. if ( !isset( $args ) )
534. {
535. $args = isset( $argv ) ? $argv : isset( $_SERVER['argv'] ) ? $_SERVER['argv'] : array();
536. }
538. $nextIndex = $this->processOptions( $args );
540. if ( $this-> helpOptionSet () )
541. {
542. // No need to parse arguments
543. return;
544. }
546. $this->processArguments( $args, $nextIndex );
548. $this->checkRules();
550. $this->setOptionDefaults();
551. }
553. /**
554. * Sets defaults for options that have not been submitted.
555. *
556. * Checks all options if they have been submited. If not and a default
557. * values is present, this is set as the options value.
558. */
559. private function setOptionDefaults()
560. {
561. foreach ( $this->options as $option )
562. {
563. if ( $option->value === false || $option->value === array() )
564. {
565. // Default value to set?
566. if ( $option->default !== null )
567. {
568. $option->value = $option->default;
569. }
570. }
571. }
572. }
574. /**
575. * Reads the submitted options from $args array.
576. *
577. * Returns the next index to check for arguments.
578. *
579. * @param array(string) $args
580. * @returns int
581. *
582. * @throws ezcConsoleOptionNotExistsException
583. * if a submitted option does not exist.
584. * @throws ezcConsoleOptionTooManyValuesException
585. * if an option that expects only a single value was submitted
586. * with multiple values.
587. * @throws ezcConsoleOptionTypeViolationException
588. * if an option was submitted with a value of the wrong type.
589. * @throws ezcConsoleOptionMissingValueException
590. * if an option thats expects a value was submitted without.
591. */
592. private function processOptions( array $args )
593. {
594. $numArgs = count( $args );
595. $i = 1;
597. while ( $i < $numArgs )
598. {
599. if ( $args[$i] === '--' )
600. {
601. break;
602. }
604. // Equalize parameter handling (long params with =)
605. if ( iconv_substr ( $args[$i], 0, 2, 'UTF-8' ) == '--' )
606. {
607. $this->preprocessLongOption( $args, $i );
608. // Update number of args, changed by preprocessLongOption()
609. $numArgs = count ( $args );
610. }
612. // Check for parameter
613. if ( iconv_substr ( $args[$i], 0, 1, 'UTF-8' ) === '-' )
614. {
615. if ( !$this-> hasOption ( preg_replace ( '/^-*/', '', $args[$i] ) ) )
616. {
617. throw new ezcConsoleOptionNotExistsException ( $args[$i] );
618. }
619. $this->processOption( $args, $i );
620. }
621. // Must be the arguments
622. else
623. {
624. break;
625. }
626. }
628. // Move pointer over argument sign
629. isset( $args[$i] ) && $args[$i] == '--' ? ++$i : $i;
631. return $i;
632. }
634. /**
635. * Resets all option and argument values.
636. *
637. * This method is called automatically by {@link process()}, if this method
638. * is called twice or more, and may also be used to manually reset the
639. * values of all registered {@ezcConsoleOption} and {@link }
640. * ezcConsoleArgument} objects.
641. */
642. public function reset ()
643. {
644. foreach ( $this->options as $option )
645. {
646. $option->value = false;
647. }
648. if ( $this->argumentDefinition !== null )
649. {
650. foreach ( $this->argumentDefinition as $argument )
651. {
652. $argument->value = null;
653. }
654. }
655. $this->arguments = array();
656. }
658. /**
659. * Returns true if an option with the given name exists, otherwise false.
660. *
661. * Checks if an option with the given name is registered.
662. *
663. * @param string $name Short or long name of the option.
664. * @return bool True if option exists, otherwise false.
665. */
666. public function hasOption ( $name )
667. {
668. try
669. {
670. $param = $this-> getOption ( $name );
671. }
672. catch ( ezcConsoleOptionNotExistsException $e )
673. {
674. return false;
675. }
676. return true;
677. }
679. /**
680. * Returns an array of all registered options.
681. *
682. * Returns an array of all registered options in the following format:
683. * <code>
684. * array(
685. * 0 => ezcConsoleOption,
686. * 1 => ezcConsoleOption,
687. * 2 => ezcConsoleOption,
688. * ...
689. * );
690. * </code>
691. *
692. * @return array(string=>ezcConsoleOption) Registered options.
693. */
694. public function getOptions ()
695. {
696. return $this->options;
697. }
699. /**
700. * Returns the values of all submitted options.
701. *
702. * Returns an array of all values submitted to the options. The array is
703. * indexed by the parameters short name (excluding the '-' prefix). The array
704. * does not contain any parameter, which value is 'false' (meaning: the
705. * parameter was not submitted).
706. *
707. * @param bool $longnames Wheather to use longnames for indexing.
708. * @return array(string=>mixed)
709. */
710. public function getOptionValues ( $longnames = false )
711. {
712. $res = array();
713. foreach ( $this->options as $param )
714. {
715. if ( $param->value !== false )
716. {
717. $res[( $longnames === true ) ? $param->long : $param->short] = $param->value;
718. }
719. }
720. return $res;
721. }
723. /**
724. * Returns arguments provided to the program.
725. *
726. * This method returns all arguments provided to a program in an
727. * int indexed array. Arguments are sorted in the way
728. * they are submitted to the program. You can disable arguments
729. * through the 'arguments' flag of a parameter, if you want
730. * to disallow arguments.
731. *
732. * Arguments are either the last part of the program call (if the
733. * last parameter is not a 'multiple' one) or divided via the '--'
734. * method which is commonly used on Unix (if the last parameter
735. * accepts multiple values this is required).
736. *
737. * @return array(string) Arguments.
738. */
739. public function getArguments ()
740. {
741. return $this->arguments;
742. }
744. /**
745. * Get help information for your options.
746. *
747. * This method returns an array of help information for your options,
748. * indexed by int. Each help info has 2 fields:
749. *
750. * 0 => The options names ("<short> / <long>")
751. * 1 => The help text (depending on the $long parameter)
752. *
753. * The $long options determines if you want to get the short or long help
754. * texts. The array returned can be used by {@link ezcConsoleTable}.
755. *
756. * If using the second options, you can filter the options shown in the
757. * help output (e.g. to show short help for related options). Provide
758. * as simple number indexed array of short and/or long values to set a filter.
759. *
760. * The $paramGrouping option can be used to group options in the help
761. * output. The structure of this array parameter is as follows:
762. *
763. * <code>
764. * array(
765. * 'First section' => array(
766. * 'input',
767. * 'output'
768. * 'overwrite',
769. * ),
770. * 'Second section' => array(
771. * 'v',
772. * 'h',
773. * ),
774. * )
775. * </code>
776. *
777. * As can be seen, short option names are possible as well as long ones.
778. * The key of the first array level is the name of the section, which is
779. * assigned to an array of options to group under this section. The $params
780. * parameter still influences if an option is displayed at all.
781. *
782. * @param bool $long
783. * @param array(string) $params
784. * @param array(string=>array(string)) $paramGrouping
785. * @return array(array(string)) Table structure as explained.
786. *
787. * @apichange In future versions, the default values of $params will change
788. * to null instead of an empty array. Giving an empty array for
789. * these will then be taken literally.
790. */
791. public function getHelp ( $long = false, array $params = array(), array $paramGrouping = null )
792. {
793. // New handling
794. $params = ( $params === array() || $params === null ? null : $params );
796. $help = array();
797. if ( $paramGrouping === null )
798. {
799. // Original handling
800. $help = $this->getOptionHelpWithoutGrouping( $long, $params );
801. }
802. else
803. {
804. $help = $this->getOptionHelpWithGrouping( $long, $params, $paramGrouping );
805. }
807. if ( $this->argumentDefinition !== null )
808. {
809. $help[] = array( "Arguments:", '' );
811. $argumentsHelp = $this->helpGenerator->generateArgumentHelp( $long );
812. if ( $argumentsHelp === array() )
813. {
814. $help[] = array( '', "No arguments available." );
815. }
816. else
817. {
818. $help = array_merge ( $help, $argumentsHelp );
819. }
820. }
822. return $help;
823. }
825. /**
826. * Creates the option help array in the original, ungrouped way.
827. *
828. * Creates the original help array generated by {@link getHelp()}. The
829. * $long and $params options are the same as they are for this method.
830. *
831. * @param bool $long
832. * @param array $params
833. * @return array
834. */
835. private function getOptionHelpWithoutGrouping( $long, $params )
836. {
837. return $this->helpGenerator->generateUngroupedOptionHelp(
838. $long,
839. $params
840. );
841. }
843. /**
844. * Generates options helo array with ordering and grouping.
845. *
846. * @param mixed $long
847. * @param mixed $params
848. * @param mixed $paramGrouping
849. * @return array()
850. */
851. private function getOptionHelpWithGrouping( $long, $params, $paramGrouping )
852. {
853. $rawHelp = $this->helpGenerator->generateGroupedOptionHelp(
854. $paramGrouping,
855. $long,
856. $params
857. );
859. $help = array();
860. $first = true;
861. foreach ( $rawHelp as $category => $optionsHelp )
862. {
863. if ( !$first )
864. {
865. $help[] = array( '', '' );
866. }
867. else
868. {
869. $first = false;
870. }
872. $help[] = array( $category, '' );
873. $help = array_merge ( $help, $optionsHelp );
874. }
875. return $help;
876. }
879. /**
880. * Get help information for your options as a table.
881. *
882. * This method provides the information returned by
883. * {@link ezcConsoleInput::getHelp()} in a table.
884. *
885. * The $paramGrouping option can be used to group options in the help
886. * output. The structure of this array parameter is as follows:
887. *
888. * <code>
889. * array(
890. * 'First section' => array(
891. * 'input',
892. * 'output'
893. * 'overwrite',
894. * ),
895. * 'Second section' => array(
896. * 'v',
897. * 'h',
898. * ),
899. * )
900. * </code>
901. *
902. * As can be seen, short option names are possible as well as long ones.
903. * The key of the first array level is the name of the section, which is
904. * assigned to an array of options to group under this section. The $params
905. * parameter still influences if an option as displayed at all.
906. *
907. * @param ezcConsoleTable $table The table object to fill.
908. * @param bool $long Set this to true for getting the
909. * long help version.
910. * @param array(string) $params Set of option names to generate help
911. * for, default is all.
912. * @param array(string=>array(string)) $paramGrouping
913. * @return ezcConsoleTable The filled table.
914. */
915. public function getHelpTable ( ezcConsoleTable $table, $long = false, array $params = array(), $paramGrouping = null )
916. {
917. $help = $this-> getHelp ( $long, $params, $paramGrouping );
918. $i = 0;
919. foreach ( $help as $row )
920. {
921. $table[$i][0]->content = $row[0];
922. $table[$i++][1]->content = $row[1];
923. }
924. return $table;
925. }
927. /**
928. * Returns a standard help output for your program.
929. *
930. * This method generates a help text as it's commonly known from Unix
931. * command line programs. The output will contain the synopsis, your
932. * provided program description and the selected parameter help
933. * as also provided by {@link ezcConsoleInput::getHelp()}. The returned
934. * string can directly be printed to the console.
935. *
936. * The $paramGrouping option can be used to group options in the help
937. * output. The structure of this array parameter is as follows:
938. *
939. * <code>
940. * array(
941. * 'First section' => array(
942. * 'input',
943. * 'output'
944. * 'overwrite',
945. * ),
946. * 'Second section' => array(
947. * 'v',
948. * 'h',
949. * ),
950. * )
951. * </code>
952. *
953. * As can be seen, short option names are possible as well as long ones.
954. * The key of the first array level is the name of the section, which is
955. * assigned to an array of options to group under this section. The $params
956. * parameter still influences if an option as displayed at all.
957. *
958. * @param string $programDesc The description of your program.
959. * @param int $width The width to adjust the output text to.
960. * @param bool $long Set this to true for getting the long
961. * help version.
962. * @param array(string) $params Set of option names to generate help
963. * for, default is all.
964. * @param array(string=>array(string)) $paramGrouping
965. * @return string The generated help text.
966. */
967. public function getHelpText ( $programDesc, $width = 80, $long = false, array $params = null, $paramGrouping = null )
968. {
969. $help = $this->getHelp( $long, ( $params == null ? array() : $params ), $paramGrouping );
971. // Determine max length of first column text.
972. $maxLength = 0;
973. foreach ( $help as $row )
974. {
975. $maxLength = max ( $maxLength, iconv_strlen ( $row[0], 'UTF-8' ) );
976. }
978. // Width of left column
979. $leftColWidth = $maxLength + 2;
980. // Width of righ column
981. $rightColWidth = $width - $leftColWidth;
983. $res = 'Usage: ' . $this-> getSynopsis ( $params ) . PHP_EOL;
984. $res .= $this->stringTool-> wordwrap ( $programDesc, $width, PHP_EOL );
985. $res .= PHP_EOL . PHP_EOL;
986. foreach ( $help as $row )
987. {
988. $rowParts = explode (
989. "\n",
990. $this->stringTool-> wordwrap ( $row[1], $rightColWidth )
991. );
993. $res .= $this->stringTool->strPad( $row[0], $leftColWidth, ' ' );
994. $res .= $rowParts[0] . PHP_EOL;
995. // @TODO: Fix function call in loop header
996. for ( $i = 1; $i < sizeof ( $rowParts ); $i++ )
997. {
998. $res .= str_repeat ( ' ', $leftColWidth ) . $rowParts[$i] . PHP_EOL;
999. }
1000. }
1001. return $res;
1002. }
1004. /**
1005. * Returns the synopsis string for the program.
1006. *
1007. * This gives you a synopsis definition for the options and arguments
1008. * defined with this instance of ezcConsoleInput. You can filter the
1009. * options named in the synopsis by submitting their short names in an
1010. * array as the parameter of this method. If the parameter $optionNames
1011. * is set, only those options are listed in the synopsis.
1012. *
1013. * @param array(string) $optionNames
1014. * @return string
1015. */
1016. public function getSynopsis ( array $optionNames = null )
1017. {
1018. return $this->helpGenerator->generateSynopsis( $optionNames );
1021. /**
1022. * Returns if a help option was set.
1023. * This method returns if an option was submitted, which was defined to be
1024. * a help option, using the isHelpOption flag.
1025. *
1026. * @return bool If a help option was set.
1027. */
1028. public function helpOptionSet ()
1029. {
1030. return $this-> helpOptionSet ;
1031. }
1033. /**
1034. * Property read access.
1035. *
1036. * @throws ezcBasePropertyNotFoundException
1037. * If the the desired property is not found.
1038. *
1039. * @param string $propertyName Name of the property.
1040. * @return mixed Value of the property or null.
1041. * @ignore
1042. */
1043. public function __get( $propertyName )
1044. {
1045. if ( !isset( $this->$propertyName ) )
1046. {
1047. throw new ezcBasePropertyNotFoundException ( $propertyName );
1048. }
1049. return $this-> properties [$propertyName];
1050. }
1052. /**
1053. * Property set access.
1054. *
1055. * @param string $propertyName
1056. * @param string $propertyValue
1057. * @ignore
1058. * @return void
1059. */
1060. public function __set( $propertyName, $propertyValue )
1061. {
1062. switch ( $propertyName )
1063. {
1064. case "argumentDefinition":
1065. if ( ( $propertyValue instanceof ezcConsoleArguments ) === false && $propertyValue !== null )
1066. {
1067. throw new ezcBaseValueException ( $propertyName, $propertyValue, "ezcConsoleArguments" );
1068. }
1069. break;
1070. default:
1071. throw new ezcBasePropertyNotFoundException ( $propertyName );
1072. }
1073. $this-> properties [$propertyName] = $propertyValue;
1074. }
1076. /**
1077. * Property isset access.
1078. *
1079. * @param string $propertyName Name of the property.
1080. * @return bool True if the property is set, otherwise false.
1081. * @ignore
1082. */
1083. public function __isset( $propertyName )
1084. {
1085. return array_key_exists ( $propertyName, $this-> properties );
1086. }
1088. /**
1089. * Returns the synopsis string for a single option and its dependencies.
1090. *
1091. * This method returns a part of the program synopsis, specifically for a
1092. * certain parameter. The method recursively adds depending parameters up
1093. * to the 2nd depth level to the synopsis. The second parameter is used
1094. * to store the short names of all options that have already been used in
1095. * the synopsis (to avoid adding an option twice). The 3rd parameter
1096. * determines the actual deps in the option dependency recursion to
1097. * terminate that after 2 recursions.
1098. *
1099. * @param ezcConsoleOption $option The option to include.
1100. * @param array(string) $usedOptions Array of used option short names.
1101. * @param int $depth Current recursion depth.
1102. * @return string The synopsis for this parameter.
1103. *
1104. * @apichange This method is deprecates. Implement your own {@link }
1105. * ezcConsoleInputHelpGenerator} instead, as soon as the
1106. * interface is made public.
1107. */
1108. protected function createOptionSynopsis ( ezcConsoleOption $option, &$usedOptions, $depth = 0 )
1109. {
1110. $synopsis = '';
1112. // Break after a nesting level of 2
1113. if ( $depth++ > 2 || ( in_array ( $option->short, $usedOptions['short'] ) && in_array ( $option->long, $usedOptions['long'] ) ) ) return $synopsis;
1115. $usedOptions['short'][] = $option->short;
1116. $usedOptions['long'][] = $option->long;
1118. $synopsis .= $option->short !== "" ? "-{$option->short}

" : "--{$option->long}";
- if ( isset( $option->default ) )
- {
- $synopsis .= " " . ( $option->type === ezcConsoleInput ::TYPE_STRING ? '"' : '' ) . $option->default . ( $option->type === ezcConsoleInput ::TYPE_STRING ? '"' : '' );
- }
- else if ( $option->type !== ezcConsoleInput ::TYPE_NONE )
- {
- $synopsis .= " ";
- switch ( $option->type )
- {
- case ezcConsoleInput ::TYPE_STRING:
- $synopsis .= "<string>";
- break;
- case ezcConsoleInput ::TYPE_INT:
- $synopsis .= "<int>";
- break;
- }
- }
- foreach ( $option->getDependencies() as $rule )
- {
- $deeperSynopsis = $this-> createOptionSynopsis ( $rule->option, $usedOptions, $depth );
- $synopsis .= ( iconv_strlen ( trim ( $deeperSynopsis ), 'UTF-8' ) > 0
- ? ' ' . $deeperSynopsis
- : ''
- );
- }
- if ( $option->arguments === false )
- {
- $allowsArgs = false;
- }
- // Make the whole thing optional?
- if ( $option->mandatory === false )
- {
- $synopsis = "[$synopsis]";
- }
- return $synopsis . ' ';
- }
- /**
- * Process an option.
- *
- * This method does the processing of a single option.
- *
- * @param array(string) $args The arguments array.
- * @param int $i The current position in the arguments array.
- * @return void
- *
- * @throws ezcConsoleOptionTooManyValuesException
- * If an option that expects only a single value was submitted
- * with multiple values.
- * @throws ezcConsoleOptionTypeViolationException
- * If an option was submitted with a value of the wrong type.
- * @throws ezcConsoleOptionMissingValueException
- * If an option thats expects a value was submitted without.
- */
- private function processOption( array $args, &$i )
- {
- $option = $this->getOption( preg_replace( '/^-+/', '', $args[$i++] ) );
- // Is the actual option a help option?
- if ( $option->isHelpOption === true )
- {
- $this-> helpOptionSet = true;
- }
- // No value expected
- if ( $option->type === ezcConsoleInput ::TYPE_NONE )
- {
- // No value expected
- if ( isset( $args[$i] ) && iconv_substr ( $args[$i], 0, 1, 'UTF-8' ) !== '-' && sizeof ( $args ) > ( $i + 1 ) )
- {
- // But one found
- throw new ezcConsoleOptionTypeViolationException ( $option, $args[$i] );
- }
- // Multiple occurance possible
- if ( $option->multiple === true )
- {
- $option->value[] = true;
- }
- else
- {
- $option->value = true;
- }
- // Everything fine, nothing to do
- return $i;
- }
- // Value expected, check for it
- if ( isset( $args[$i] ) && iconv_substr ( $args[$i], 0, 1, 'UTF-8' ) !== '-' )
- {
- // Type check
- if ( $this->isCorrectType( $option->type, $args[$i] ) === false )
- {
- throw new ezcConsoleOptionTypeViolationException ( $option, $args[$i] );
- }
- // Multiple values possible
- if ( $option->multiple === true )
- {
- $option->value[] = $args[$i];
- }
- // Only single value expected, check for multiple
- elseif ( isset( $option->value ) && $option->value !== false )
- {
- throw new ezcConsoleOptionTooManyValuesException ( $option );
- }
- else
- {
- $option->value = $args[$i];
- }
- $i++;
- }
- // Value found? If not, use default, if available
- if ( !isset( $option->value ) || $option->value === false || ( is_array ( $option->value ) && count ( $option->value ) === 0) )
- {
- throw new ezcConsoleOptionMissingValueException ( $option );
- }
- }
- /**
- * Process arguments given to the program.
- *
- * @param array(string) $args The arguments array.
- * @param int $i Current index in arguments array.
- * @return void
- */
- private function processArguments( array $args, &$i )
- {
- $numArgs = count( $args );
- if ( $this->argumentDefinition === null || $this->argumentsAllowed() === false )
- {
- // Old argument handling, also used of a set option sets disallowing arguments
- while ( $i < $numArgs )
- {
- $this->arguments[] = $args[$i++];
- }
- }
- else
- {
- $mandatory = true;
- foreach ( $this->argumentDefinition as $arg )
- {
- // Check if all followinga arguments are optional
- if ( $arg->mandatory === false )
- {
- $mandatory = false;
- }
- // Check if the current argument is present and mandatory
- if ( $mandatory === true )
- {
- if ( !isset( $args[$i] ) )
- {
- throw new ezcConsoleArgumentMandatoryViolationException ( $arg );
- }
- }
- else
- {
- // Arguments are optional, if no more left: return.
- if ( !isset( $args[$i] ) )
- {
- // Optional and no more arguments left, assign default
- $arg->value = $arg->default;
- continue;
- }
- }
- if ( $arg->multiple === true )
- {
- $arg->value = array();
- for ( $i = $i; $i < $numArgs; ++$i )
- {
- if ( $this->isCorrectType( $arg->type, $args[$i] ) === false )
- {
- throw new ezcConsoleArgumentTypeViolationException ( $arg, $args[$i] );
- }
- $arg->value = array_merge ( $arg->value, array( $args[$i] ) );
- // Keep old handling, too
- $this->arguments[] = $args[$i];
- }
- return;
- }
- else
- {
- if ( $this->isCorrectType( $arg->type, $args[$i] ) === false )
- {
- throw new ezcConsoleArgumentTypeViolationException ( $arg, $args[$i] );
- }
- $arg->value = $args[$i];
- // Keep old handling, too
- $this->arguments[] = $args[$i];
- }
- ++$i;
- }
- if ( $i < $numArgs )
- {
- throw new ezcConsoleTooManyArgumentsException ( $args, $i );
- }
- }
- }
- /**
- * Returns if arguments are allowed with the current option submition.
- *
- * @return bool If arguments allowed.
- */
- protected function argumentsAllowed ()
- {
- foreach ( $this->options as $id => $option )
- {
- if ( $option->value !== false && $option->arguments === false )
- {
- return false;
- }
- }
- return true;
- }
- /**
- * Check the rules that may be associated with an option.
- *
- * Options are allowed to have rules associated for dependencies to other
- * options and exclusion of other options or arguments. This method
- * processes the checks.
- *
- * @throws ezcConsoleException
- * in case validation fails.
- */
- private function checkRules()
- {
- // If a help option is set, skip rule checking
- if ( $this-> helpOptionSet === true )
- {
- return;
- }
- $this->validator->validateOptions(
- $this->options,
- ( $this->arguments !== array() )
- );
- }
- /**
- * Checks if a value is of a given type. Converts the value to the
- * correct PHP type on success.
- *
- * @param int $type The type to check for. One of self::TYPE_*.
- * @param string $val The value to check. Will possibly altered!
- * @return bool True on succesful check, otherwise false.
- */
- private function isCorrectType( $type, &$val )
- {
- $res = false;
- switch ( $type )
- {
- case ezcConsoleInput ::TYPE_STRING:
- $res = true;
- $val = preg_replace ( '/^(["\'])(.*)\1$/', '\2', $val );
- break;
- case ezcConsoleInput ::TYPE_INT:
- $res = preg_match ( '/^[0-9]+$/', $val ) ? true : false;
- if ( $res )
- {
- $val = ( int ) $val;
- }
- break;
- }
- return $res;
- }
- /**
- * Split parameter and value for long option names.
- *
- * This method checks for long options, if the value is passed using =. If
- * this is the case parameter and value get split and replaced in the
- * arguments array.
- *
- * @param array(string) $args The arguments array
- * @param int $i Current arguments array position
- * @return void
- */
- private function preprocessLongOption( array &$args, $i )
- {
- // Value given?
- if ( preg_match( '/^--\w+\=[^ ]/i', $args[$i] ) )
- {
- // Split param and value and replace current param
- $parts = explode ( '=', $args[$i], 2 );
- array_splice ( $args, $i, 1, $parts );
- }
- }
- }
- ?>
Documentation generated by phpDocumentor 1.4.3