BooleanUtils.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Stdlib;
  7. /**
  8. * Utility methods for the boolean data type
  9. *
  10. * @api
  11. * @since 100.0.2
  12. */
  13. class BooleanUtils
  14. {
  15. /**
  16. * Expressions that mean boolean TRUE
  17. *
  18. * @var array
  19. */
  20. private $trueValues;
  21. /**
  22. * Expressions that mean boolean FALSE
  23. *
  24. * @var array
  25. */
  26. private $falseValues;
  27. /**
  28. * @param array $trueValues
  29. * @param array $falseValues
  30. * @codingStandardsIgnoreStart
  31. */
  32. public function __construct(
  33. array $trueValues = [true, 1, 'true', '1'],
  34. array $falseValues = [false, 0, 'false', '0']
  35. ) {
  36. $this->trueValues = $trueValues;
  37. $this->falseValues = $falseValues;
  38. }
  39. // @codingStandardsIgnoreEnd
  40. /**
  41. * Retrieve boolean value for an expression
  42. *
  43. * @param mixed $value Boolean expression
  44. * @return bool
  45. * @throws \InvalidArgumentException
  46. */
  47. public function toBoolean($value)
  48. {
  49. /**
  50. * Built-in function filter_var() is not used, because such values as on/off are irrelevant in some contexts
  51. * @link http://www.php.net/manual/en/filter.filters.validate.php
  52. */
  53. if (in_array($value, $this->trueValues, true)) {
  54. return true;
  55. }
  56. if (in_array($value, $this->falseValues, true)) {
  57. return false;
  58. }
  59. $allowedValues = array_merge($this->trueValues, $this->falseValues);
  60. throw new \InvalidArgumentException(
  61. 'Boolean value is expected, supported values: ' . var_export($allowedValues, true)
  62. );
  63. }
  64. /**
  65. * Try to convert $value to boolean else return non processed $value
  66. *
  67. * @param mixed $value
  68. * @return mixed
  69. * @since 101.0.0
  70. */
  71. public function convert($value)
  72. {
  73. if (in_array($value, $this->trueValues, true)) {
  74. return true;
  75. } elseif (in_array($value, $this->falseValues, true)) {
  76. return false;
  77. } else {
  78. return $value;
  79. }
  80. }
  81. }