diff --git a/src/ncc/ThirdParty/beberlei/assert/Assert.php b/src/ncc/ThirdParty/beberlei/assert/Assert.php deleted file mode 100644 index 07a0f86..0000000 --- a/src/ncc/ThirdParty/beberlei/assert/Assert.php +++ /dev/null @@ -1,85 +0,0 @@ -notEmpty()->integer(); - * Assert::that($value)->nullOr()->string()->startsWith("Foo"); - * - * The assertion chain can be stateful, that means be careful when you reuse - * it. You should never pass around the chain. - */ - public static function that($value, $defaultMessage = null, string $defaultPropertyPath = null): AssertionChain - { - $assertionChain = new AssertionChain($value, $defaultMessage, $defaultPropertyPath); - - return $assertionChain->setAssertionClassName(static::$assertionClass); - } - - /** - * Start validation on a set of values, returns {@link AssertionChain}. - * - * @param mixed $values - * @param string|callable|null $defaultMessage - */ - public static function thatAll($values, $defaultMessage = null, string $defaultPropertyPath = null): AssertionChain - { - return static::that($values, $defaultMessage, $defaultPropertyPath)->all(); - } - - /** - * Start validation and allow NULL, returns {@link AssertionChain}. - * - * @param mixed $value - * @param string|callable|null $defaultMessage - */ - public static function thatNullOr($value, $defaultMessage = null, string $defaultPropertyPath = null): AssertionChain - { - return static::that($value, $defaultMessage, $defaultPropertyPath)->nullOr(); - } - - /** - * Create a lazy assertion object. - */ - public static function lazy(): LazyAssertion - { - $lazyAssertion = new LazyAssertion(); - - return $lazyAssertion - ->setAssertClass(\get_called_class()) - ->setExceptionClass(static::$lazyAssertionExceptionClass); - } -} diff --git a/src/ncc/ThirdParty/beberlei/assert/Assertion.php b/src/ncc/ThirdParty/beberlei/assert/Assertion.php deleted file mode 100644 index 3e171bc..0000000 --- a/src/ncc/ThirdParty/beberlei/assert/Assertion.php +++ /dev/null @@ -1,2797 +0,0 @@ - - * - * @method static bool allAlnum(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that value is alphanumeric for all values. - * @method static bool allBase64(string[] $value, string|callable $message = null, string $propertyPath = null) Assert that a constant is defined for all values. - * @method static bool allBetween(mixed[] $value, mixed $lowerLimit, mixed $upperLimit, string|callable $message = null, string $propertyPath = null) Assert that a value is greater or equal than a lower limit, and less than or equal to an upper limit for all values. - * @method static bool allBetweenExclusive(mixed[] $value, mixed $lowerLimit, mixed $upperLimit, string|callable $message = null, string $propertyPath = null) Assert that a value is greater than a lower limit, and less than an upper limit for all values. - * @method static bool allBetweenLength(mixed[] $value, int $minLength, int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string length is between min and max lengths for all values. - * @method static bool allBoolean(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that value is php boolean for all values. - * @method static bool allChoice(mixed[] $value, array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices for all values. - * @method static bool allChoicesNotEmpty(array[] $values, array $choices, string|callable $message = null, string $propertyPath = null) Determines if the values array has every choice as key and that this choice has content for all values. - * @method static bool allClassExists(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that the class exists for all values. - * @method static bool allContains(mixed[] $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string contains a sequence of chars for all values. - * @method static bool allCount(array[]|Countable[]|ResourceBundle[]|SimpleXMLElement[] $countable, int $count, string|callable $message = null, string $propertyPath = null) Assert that the count of countable is equal to count for all values. - * @method static bool allDate(string[] $value, string $format, string|callable $message = null, string $propertyPath = null) Assert that date is valid and corresponds to the given format for all values. - * @method static bool allDefined(mixed[] $constant, string|callable $message = null, string $propertyPath = null) Assert that a constant is defined for all values. - * @method static bool allDigit(mixed[] $value, string|callable $message = null, string $propertyPath = null) Validates if an integer or integerish is a digit for all values. - * @method static bool allDirectory(string[] $value, string|callable $message = null, string $propertyPath = null) Assert that a directory exists for all values. - * @method static bool allE164(string[] $value, string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid E164 Phone Number for all values. - * @method static bool allEmail(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that value is an email address (using input_filter/FILTER_VALIDATE_EMAIL) for all values. - * @method static bool allEndsWith(mixed[] $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string ends with a sequence of chars for all values. - * @method static bool allEq(mixed[] $value, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are equal (using ==) for all values. - * @method static bool allEqArraySubset(mixed[] $value, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that the array contains the subset for all values. - * @method static bool allExtensionLoaded(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that extension is loaded for all values. - * @method static bool allExtensionVersion(string[] $extension, string $operator, mixed $version, string|callable $message = null, string $propertyPath = null) Assert that extension is loaded and a specific version is installed for all values. - * @method static bool allFalse(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that the value is boolean False for all values. - * @method static bool allFile(string[] $value, string|callable $message = null, string $propertyPath = null) Assert that a file exists for all values. - * @method static bool allFloat(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that value is a php float for all values. - * @method static bool allGreaterOrEqualThan(mixed[] $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater or equal than given limit for all values. - * @method static bool allGreaterThan(mixed[] $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater than given limit for all values. - * @method static bool allImplementsInterface(mixed[] $class, string $interfaceName, string|callable $message = null, string $propertyPath = null) Assert that the class implements the interface for all values. - * @method static bool allInArray(mixed[] $value, array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices. This is an alias of Assertion::choice() for all values. - * @method static bool allInteger(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that value is a php integer for all values. - * @method static bool allIntegerish(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that value is a php integer'ish for all values. - * @method static bool allInterfaceExists(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that the interface exists for all values. - * @method static bool allIp(string[] $value, int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 or IPv6 address for all values. - * @method static bool allIpv4(string[] $value, int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 address for all values. - * @method static bool allIpv6(string[] $value, int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv6 address for all values. - * @method static bool allIsArray(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that value is an array for all values. - * @method static bool allIsArrayAccessible(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that value is an array or an array-accessible object for all values. - * @method static bool allIsCallable(mixed[] $value, string|callable $message = null, string $propertyPath = null) Determines that the provided value is callable for all values. - * @method static bool allIsCountable(array[]|Countable[]|ResourceBundle[]|SimpleXMLElement[] $value, string|callable $message = null, string $propertyPath = null) Assert that value is countable for all values. - * @method static bool allIsInstanceOf(mixed[] $value, string $className, string|callable $message = null, string $propertyPath = null) Assert that value is instance of given class-name for all values. - * @method static bool allIsJsonString(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid json string for all values. - * @method static bool allIsObject(mixed[] $value, string|callable $message = null, string $propertyPath = null) Determines that the provided value is an object for all values. - * @method static bool allIsResource(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that value is a resource for all values. - * @method static bool allIsTraversable(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that value is an array or a traversable object for all values. - * @method static bool allKeyExists(mixed[] $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array for all values. - * @method static bool allKeyIsset(mixed[] $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object using isset() for all values. - * @method static bool allKeyNotExists(mixed[] $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key does not exist in an array for all values. - * @method static bool allLength(mixed[] $value, int $length, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string has a given length for all values. - * @method static bool allLessOrEqualThan(mixed[] $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less or equal than given limit for all values. - * @method static bool allLessThan(mixed[] $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less than given limit for all values. - * @method static bool allMax(mixed[] $value, mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that a number is smaller as a given limit for all values. - * @method static bool allMaxCount(array[]|Countable[]|ResourceBundle[]|SimpleXMLElement[] $countable, int $count, string|callable $message = null, string $propertyPath = null) Assert that the countable have at most $count elements for all values. - * @method static bool allMaxLength(mixed[] $value, int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string value is not longer than $maxLength chars for all values. - * @method static bool allMethodExists(string[] $value, mixed $object, string|callable $message = null, string $propertyPath = null) Determines that the named method is defined in the provided object for all values. - * @method static bool allMin(mixed[] $value, mixed $minValue, string|callable $message = null, string $propertyPath = null) Assert that a value is at least as big as a given limit for all values. - * @method static bool allMinCount(array[]|Countable[]|ResourceBundle[]|SimpleXMLElement[] $countable, int $count, string|callable $message = null, string $propertyPath = null) Assert that the countable have at least $count elements for all values. - * @method static bool allMinLength(mixed[] $value, int $minLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that a string is at least $minLength chars long for all values. - * @method static bool allNoContent(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that value is empty for all values. - * @method static bool allNotBlank(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that value is not blank for all values. - * @method static bool allNotContains(mixed[] $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string does not contains a sequence of chars for all values. - * @method static bool allNotEmpty(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that value is not empty for all values. - * @method static bool allNotEmptyKey(mixed[] $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object and its value is not empty for all values. - * @method static bool allNotEq(mixed[] $value1, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not equal (using ==) for all values. - * @method static bool allNotInArray(mixed[] $value, array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is not in array of choices for all values. - * @method static bool allNotIsInstanceOf(mixed[] $value, string $className, string|callable $message = null, string $propertyPath = null) Assert that value is not instance of given class-name for all values. - * @method static bool allNotNull(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that value is not null for all values. - * @method static bool allNotRegex(mixed[] $value, string $pattern, string|callable $message = null, string $propertyPath = null) # Assert that value does not match a regex for all values. - * @method static bool allNotSame(mixed[] $value1, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not the same (using ===) for all values. - * @method static bool allNull(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that value is null for all values. - * @method static bool allNumeric(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that value is numeric for all values. - * @method static bool allObjectOrClass(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that the value is an object, or a class that exists for all values. - * @method static bool allPhpVersion(string[] $operator, mixed $version, string|callable $message = null, string $propertyPath = null) Assert on PHP version for all values. - * @method static bool allPropertiesExist(mixed[] $value, array $properties, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the properties all exist for all values. - * @method static bool allPropertyExists(mixed[] $value, string $property, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the property exists for all values. - * @method static bool allRange(mixed[] $value, mixed $minValue, mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that value is in range of numbers for all values. - * @method static bool allReadable(string[] $value, string|callable $message = null, string $propertyPath = null) Assert that the value is something readable for all values. - * @method static bool allRegex(mixed[] $value, string $pattern, string|callable $message = null, string $propertyPath = null) Assert that value matches a regex for all values. - * @method static bool allSame(mixed[] $value, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are the same (using ===) for all values. - * @method static bool allSatisfy(mixed[] $value, callable $callback, string|callable $message = null, string $propertyPath = null) Assert that the provided value is valid according to a callback for all values. - * @method static bool allScalar(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that value is a PHP scalar for all values. - * @method static bool allStartsWith(mixed[] $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string starts with a sequence of chars for all values. - * @method static bool allString(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that value is a string for all values. - * @method static bool allSubclassOf(mixed[] $value, string $className, string|callable $message = null, string $propertyPath = null) Assert that value is subclass of given class-name for all values. - * @method static bool allTrue(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that the value is boolean True for all values. - * @method static bool allUniqueValues(array[] $values, string|callable $message = null, string $propertyPath = null) Assert that values in array are unique (using strict equality) for all values. - * @method static bool allUrl(mixed[] $value, string|callable $message = null, string $propertyPath = null) Assert that value is an URL for all values. - * @method static bool allUuid(string[] $value, string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid UUID for all values. - * @method static bool allVersion(string[] $version1, string $operator, string $version2, string|callable $message = null, string $propertyPath = null) Assert comparison of two versions for all values. - * @method static bool allWriteable(string[] $value, string|callable $message = null, string $propertyPath = null) Assert that the value is something writeable for all values. - * @method static bool nullOrAlnum(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is alphanumeric or that the value is null. - * @method static bool nullOrBase64(string|null $value, string|callable $message = null, string $propertyPath = null) Assert that a constant is defined or that the value is null. - * @method static bool nullOrBetween(mixed|null $value, mixed $lowerLimit, mixed $upperLimit, string|callable $message = null, string $propertyPath = null) Assert that a value is greater or equal than a lower limit, and less than or equal to an upper limit or that the value is null. - * @method static bool nullOrBetweenExclusive(mixed|null $value, mixed $lowerLimit, mixed $upperLimit, string|callable $message = null, string $propertyPath = null) Assert that a value is greater than a lower limit, and less than an upper limit or that the value is null. - * @method static bool nullOrBetweenLength(mixed|null $value, int $minLength, int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string length is between min and max lengths or that the value is null. - * @method static bool nullOrBoolean(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is php boolean or that the value is null. - * @method static bool nullOrChoice(mixed|null $value, array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices or that the value is null. - * @method static bool nullOrChoicesNotEmpty(array|null $values, array $choices, string|callable $message = null, string $propertyPath = null) Determines if the values array has every choice as key and that this choice has content or that the value is null. - * @method static bool nullOrClassExists(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that the class exists or that the value is null. - * @method static bool nullOrContains(mixed|null $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string contains a sequence of chars or that the value is null. - * @method static bool nullOrCount(array|Countable|ResourceBundle|SimpleXMLElement|null $countable, int $count, string|callable $message = null, string $propertyPath = null) Assert that the count of countable is equal to count or that the value is null. - * @method static bool nullOrDate(string|null $value, string $format, string|callable $message = null, string $propertyPath = null) Assert that date is valid and corresponds to the given format or that the value is null. - * @method static bool nullOrDefined(mixed|null $constant, string|callable $message = null, string $propertyPath = null) Assert that a constant is defined or that the value is null. - * @method static bool nullOrDigit(mixed|null $value, string|callable $message = null, string $propertyPath = null) Validates if an integer or integerish is a digit or that the value is null. - * @method static bool nullOrDirectory(string|null $value, string|callable $message = null, string $propertyPath = null) Assert that a directory exists or that the value is null. - * @method static bool nullOrE164(string|null $value, string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid E164 Phone Number or that the value is null. - * @method static bool nullOrEmail(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is an email address (using input_filter/FILTER_VALIDATE_EMAIL) or that the value is null. - * @method static bool nullOrEndsWith(mixed|null $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string ends with a sequence of chars or that the value is null. - * @method static bool nullOrEq(mixed|null $value, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are equal (using ==) or that the value is null. - * @method static bool nullOrEqArraySubset(mixed|null $value, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that the array contains the subset or that the value is null. - * @method static bool nullOrExtensionLoaded(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that extension is loaded or that the value is null. - * @method static bool nullOrExtensionVersion(string|null $extension, string $operator, mixed $version, string|callable $message = null, string $propertyPath = null) Assert that extension is loaded and a specific version is installed or that the value is null. - * @method static bool nullOrFalse(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that the value is boolean False or that the value is null. - * @method static bool nullOrFile(string|null $value, string|callable $message = null, string $propertyPath = null) Assert that a file exists or that the value is null. - * @method static bool nullOrFloat(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is a php float or that the value is null. - * @method static bool nullOrGreaterOrEqualThan(mixed|null $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater or equal than given limit or that the value is null. - * @method static bool nullOrGreaterThan(mixed|null $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater than given limit or that the value is null. - * @method static bool nullOrImplementsInterface(mixed|null $class, string $interfaceName, string|callable $message = null, string $propertyPath = null) Assert that the class implements the interface or that the value is null. - * @method static bool nullOrInArray(mixed|null $value, array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices. This is an alias of Assertion::choice() or that the value is null. - * @method static bool nullOrInteger(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is a php integer or that the value is null. - * @method static bool nullOrIntegerish(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is a php integer'ish or that the value is null. - * @method static bool nullOrInterfaceExists(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that the interface exists or that the value is null. - * @method static bool nullOrIp(string|null $value, int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 or IPv6 address or that the value is null. - * @method static bool nullOrIpv4(string|null $value, int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 address or that the value is null. - * @method static bool nullOrIpv6(string|null $value, int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv6 address or that the value is null. - * @method static bool nullOrIsArray(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is an array or that the value is null. - * @method static bool nullOrIsArrayAccessible(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is an array or an array-accessible object or that the value is null. - * @method static bool nullOrIsCallable(mixed|null $value, string|callable $message = null, string $propertyPath = null) Determines that the provided value is callable or that the value is null. - * @method static bool nullOrIsCountable(array|Countable|ResourceBundle|SimpleXMLElement|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is countable or that the value is null. - * @method static bool nullOrIsInstanceOf(mixed|null $value, string $className, string|callable $message = null, string $propertyPath = null) Assert that value is instance of given class-name or that the value is null. - * @method static bool nullOrIsJsonString(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid json string or that the value is null. - * @method static bool nullOrIsObject(mixed|null $value, string|callable $message = null, string $propertyPath = null) Determines that the provided value is an object or that the value is null. - * @method static bool nullOrIsResource(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is a resource or that the value is null. - * @method static bool nullOrIsTraversable(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is an array or a traversable object or that the value is null. - * @method static bool nullOrKeyExists(mixed|null $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array or that the value is null. - * @method static bool nullOrKeyIsset(mixed|null $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object using isset() or that the value is null. - * @method static bool nullOrKeyNotExists(mixed|null $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key does not exist in an array or that the value is null. - * @method static bool nullOrLength(mixed|null $value, int $length, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string has a given length or that the value is null. - * @method static bool nullOrLessOrEqualThan(mixed|null $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less or equal than given limit or that the value is null. - * @method static bool nullOrLessThan(mixed|null $value, mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less than given limit or that the value is null. - * @method static bool nullOrMax(mixed|null $value, mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that a number is smaller as a given limit or that the value is null. - * @method static bool nullOrMaxCount(array|Countable|ResourceBundle|SimpleXMLElement|null $countable, int $count, string|callable $message = null, string $propertyPath = null) Assert that the countable have at most $count elements or that the value is null. - * @method static bool nullOrMaxLength(mixed|null $value, int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string value is not longer than $maxLength chars or that the value is null. - * @method static bool nullOrMethodExists(string|null $value, mixed $object, string|callable $message = null, string $propertyPath = null) Determines that the named method is defined in the provided object or that the value is null. - * @method static bool nullOrMin(mixed|null $value, mixed $minValue, string|callable $message = null, string $propertyPath = null) Assert that a value is at least as big as a given limit or that the value is null. - * @method static bool nullOrMinCount(array|Countable|ResourceBundle|SimpleXMLElement|null $countable, int $count, string|callable $message = null, string $propertyPath = null) Assert that the countable have at least $count elements or that the value is null. - * @method static bool nullOrMinLength(mixed|null $value, int $minLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that a string is at least $minLength chars long or that the value is null. - * @method static bool nullOrNoContent(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is empty or that the value is null. - * @method static bool nullOrNotBlank(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is not blank or that the value is null. - * @method static bool nullOrNotContains(mixed|null $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string does not contains a sequence of chars or that the value is null. - * @method static bool nullOrNotEmpty(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is not empty or that the value is null. - * @method static bool nullOrNotEmptyKey(mixed|null $value, string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object and its value is not empty or that the value is null. - * @method static bool nullOrNotEq(mixed|null $value1, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not equal (using ==) or that the value is null. - * @method static bool nullOrNotInArray(mixed|null $value, array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is not in array of choices or that the value is null. - * @method static bool nullOrNotIsInstanceOf(mixed|null $value, string $className, string|callable $message = null, string $propertyPath = null) Assert that value is not instance of given class-name or that the value is null. - * @method static bool nullOrNotNull(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is not null or that the value is null. - * @method static bool nullOrNotRegex(mixed|null $value, string $pattern, string|callable $message = null, string $propertyPath = null) # Assert that value does not match a regex or that the value is null. - * @method static bool nullOrNotSame(mixed|null $value1, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not the same (using ===) or that the value is null. - * @method static bool nullOrNull(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is null or that the value is null. - * @method static bool nullOrNumeric(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is numeric or that the value is null. - * @method static bool nullOrObjectOrClass(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that the value is an object, or a class that exists or that the value is null. - * @method static bool nullOrPhpVersion(string|null $operator, mixed $version, string|callable $message = null, string $propertyPath = null) Assert on PHP version or that the value is null. - * @method static bool nullOrPropertiesExist(mixed|null $value, array $properties, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the properties all exist or that the value is null. - * @method static bool nullOrPropertyExists(mixed|null $value, string $property, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the property exists or that the value is null. - * @method static bool nullOrRange(mixed|null $value, mixed $minValue, mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that value is in range of numbers or that the value is null. - * @method static bool nullOrReadable(string|null $value, string|callable $message = null, string $propertyPath = null) Assert that the value is something readable or that the value is null. - * @method static bool nullOrRegex(mixed|null $value, string $pattern, string|callable $message = null, string $propertyPath = null) Assert that value matches a regex or that the value is null. - * @method static bool nullOrSame(mixed|null $value, mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are the same (using ===) or that the value is null. - * @method static bool nullOrSatisfy(mixed|null $value, callable $callback, string|callable $message = null, string $propertyPath = null) Assert that the provided value is valid according to a callback or that the value is null. - * @method static bool nullOrScalar(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is a PHP scalar or that the value is null. - * @method static bool nullOrStartsWith(mixed|null $string, string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string starts with a sequence of chars or that the value is null. - * @method static bool nullOrString(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is a string or that the value is null. - * @method static bool nullOrSubclassOf(mixed|null $value, string $className, string|callable $message = null, string $propertyPath = null) Assert that value is subclass of given class-name or that the value is null. - * @method static bool nullOrTrue(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that the value is boolean True or that the value is null. - * @method static bool nullOrUniqueValues(array|null $values, string|callable $message = null, string $propertyPath = null) Assert that values in array are unique (using strict equality) or that the value is null. - * @method static bool nullOrUrl(mixed|null $value, string|callable $message = null, string $propertyPath = null) Assert that value is an URL or that the value is null. - * @method static bool nullOrUuid(string|null $value, string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid UUID or that the value is null. - * @method static bool nullOrVersion(string|null $version1, string $operator, string $version2, string|callable $message = null, string $propertyPath = null) Assert comparison of two versions or that the value is null. - * @method static bool nullOrWriteable(string|null $value, string|callable $message = null, string $propertyPath = null) Assert that the value is something writeable or that the value is null. - */ -class Assertion -{ - const INVALID_FLOAT = 9; - const INVALID_INTEGER = 10; - const INVALID_DIGIT = 11; - const INVALID_INTEGERISH = 12; - const INVALID_BOOLEAN = 13; - const VALUE_EMPTY = 14; - const VALUE_NULL = 15; - const VALUE_NOT_NULL = 25; - const INVALID_STRING = 16; - const INVALID_REGEX = 17; - const INVALID_MIN_LENGTH = 18; - const INVALID_MAX_LENGTH = 19; - const INVALID_STRING_START = 20; - const INVALID_STRING_CONTAINS = 21; - const INVALID_CHOICE = 22; - const INVALID_NUMERIC = 23; - const INVALID_ARRAY = 24; - const INVALID_KEY_EXISTS = 26; - const INVALID_NOT_BLANK = 27; - const INVALID_INSTANCE_OF = 28; - const INVALID_SUBCLASS_OF = 29; - const INVALID_RANGE = 30; - const INVALID_ALNUM = 31; - const INVALID_TRUE = 32; - const INVALID_EQ = 33; - const INVALID_SAME = 34; - const INVALID_MIN = 35; - const INVALID_MAX = 36; - const INVALID_LENGTH = 37; - const INVALID_FALSE = 38; - const INVALID_STRING_END = 39; - const INVALID_UUID = 40; - const INVALID_COUNT = 41; - const INVALID_NOT_EQ = 42; - const INVALID_NOT_SAME = 43; - const INVALID_TRAVERSABLE = 44; - const INVALID_ARRAY_ACCESSIBLE = 45; - const INVALID_KEY_ISSET = 46; - const INVALID_VALUE_IN_ARRAY = 47; - const INVALID_E164 = 48; - const INVALID_BASE64 = 49; - const INVALID_NOT_REGEX = 50; - const INVALID_DIRECTORY = 101; - const INVALID_FILE = 102; - const INVALID_READABLE = 103; - const INVALID_WRITEABLE = 104; - const INVALID_CLASS = 105; - const INVALID_INTERFACE = 106; - const INVALID_FILE_NOT_EXISTS = 107; - const INVALID_EMAIL = 201; - const INTERFACE_NOT_IMPLEMENTED = 202; - const INVALID_URL = 203; - const INVALID_NOT_INSTANCE_OF = 204; - const VALUE_NOT_EMPTY = 205; - const INVALID_JSON_STRING = 206; - const INVALID_OBJECT = 207; - const INVALID_METHOD = 208; - const INVALID_SCALAR = 209; - const INVALID_LESS = 210; - const INVALID_LESS_OR_EQUAL = 211; - const INVALID_GREATER = 212; - const INVALID_GREATER_OR_EQUAL = 213; - const INVALID_DATE = 214; - const INVALID_CALLABLE = 215; - const INVALID_KEY_NOT_EXISTS = 216; - const INVALID_SATISFY = 217; - const INVALID_IP = 218; - const INVALID_BETWEEN = 219; - const INVALID_BETWEEN_EXCLUSIVE = 220; - const INVALID_EXTENSION = 222; - const INVALID_CONSTANT = 221; - const INVALID_VERSION = 223; - const INVALID_PROPERTY = 224; - const INVALID_RESOURCE = 225; - const INVALID_COUNTABLE = 226; - const INVALID_MIN_COUNT = 227; - const INVALID_MAX_COUNT = 228; - const INVALID_STRING_NOT_CONTAINS = 229; - const INVALID_UNIQUE_VALUES = 230; - - /** - * Exception to throw when an assertion failed. - * - * @var string - */ - protected static $exceptionClass = InvalidArgumentException::class; - - /** - * Assert that two values are equal (using ==). - * - * @param mixed $value - * @param mixed $value2 - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function eq($value, $value2, $message = null, string $propertyPath = null): bool - { - if ($value != $value2) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" does not equal expected value "%s".'), - static::stringify($value), - static::stringify($value2) - ); - - throw static::createException($value, $message, static::INVALID_EQ, $propertyPath, ['expected' => $value2]); - } - - return true; - } - - /** - * Assert that the array contains the subset. - * - * @param mixed $value - * @param mixed $value2 - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function eqArraySubset($value, $value2, $message = null, string $propertyPath = null): bool - { - static::isArray($value, $message, $propertyPath); - static::isArray($value2, $message, $propertyPath); - - $patched = \array_replace_recursive($value, $value2); - static::eq($patched, $value, $message, $propertyPath); - - return true; - } - - /** - * Assert that two values are the same (using ===). - * - * @param mixed $value - * @param mixed $value2 - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-template ExpectedType - * @psalm-param ExpectedType $value2 - * @psalm-assert =ExpectedType $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function same($value, $value2, $message = null, string $propertyPath = null): bool - { - if ($value !== $value2) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not the same as expected value "%s".'), - static::stringify($value), - static::stringify($value2) - ); - - throw static::createException($value, $message, static::INVALID_SAME, $propertyPath, ['expected' => $value2]); - } - - return true; - } - - /** - * Assert that two values are not equal (using ==). - * - * @param mixed $value1 - * @param mixed $value2 - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function notEq($value1, $value2, $message = null, string $propertyPath = null): bool - { - if ($value1 == $value2) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" was not expected to be equal to value "%s".'), - static::stringify($value1), - static::stringify($value2) - ); - throw static::createException($value1, $message, static::INVALID_NOT_EQ, $propertyPath, ['expected' => $value2]); - } - - return true; - } - - /** - * Assert that two values are not the same (using ===). - * - * @param mixed $value1 - * @param mixed $value2 - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-template ExpectedType - * @psalm-param ExpectedType $value2 - * @psalm-assert !=ExpectedType $value1 - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function notSame($value1, $value2, $message = null, string $propertyPath = null): bool - { - if ($value1 === $value2) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" was not expected to be the same as value "%s".'), - static::stringify($value1), - static::stringify($value2) - ); - throw static::createException($value1, $message, static::INVALID_NOT_SAME, $propertyPath, ['expected' => $value2]); - } - - return true; - } - - /** - * Assert that value is not in array of choices. - * - * @param mixed $value - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function notInArray($value, array $choices, $message = null, string $propertyPath = null): bool - { - if (true === \in_array($value, $choices)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" was not expected to be an element of the values: %s'), - static::stringify($value), - static::stringify($choices) - ); - throw static::createException($value, $message, static::INVALID_VALUE_IN_ARRAY, $propertyPath, ['choices' => $choices]); - } - - return true; - } - - /** - * Assert that value is a php integer. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert int $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function integer($value, $message = null, string $propertyPath = null): bool - { - if (!\is_int($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not an integer.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_INTEGER, $propertyPath); - } - - return true; - } - - /** - * Assert that value is a php float. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert float $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function float($value, $message = null, string $propertyPath = null): bool - { - if (!\is_float($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not a float.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_FLOAT, $propertyPath); - } - - return true; - } - - /** - * Validates if an integer or integerish is a digit. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert =numeric $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function digit($value, $message = null, string $propertyPath = null): bool - { - if (!\ctype_digit((string)$value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not a digit.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_DIGIT, $propertyPath); - } - - return true; - } - - /** - * Assert that value is a php integer'ish. - * - * @param mixed $value - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function integerish($value, $message = null, string $propertyPath = null): bool - { - if ( - \is_resource($value) || - \is_object($value) || - \is_bool($value) || - \is_null($value) || - \is_array($value) || - (\is_string($value) && '' == $value) || - ( - \strval(\intval($value)) !== \strval($value) && - \strval(\intval($value)) !== \strval(\ltrim($value, '0')) && - '' !== \strval(\intval($value)) && - '' !== \strval(\ltrim($value, '0')) - ) - ) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not an integer or a number castable to integer.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_INTEGERISH, $propertyPath); - } - - return true; - } - - /** - * Assert that value is php boolean. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert bool $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function boolean($value, $message = null, string $propertyPath = null): bool - { - if (!\is_bool($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not a boolean.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_BOOLEAN, $propertyPath); - } - - return true; - } - - /** - * Assert that value is a PHP scalar. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert scalar $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function scalar($value, $message = null, string $propertyPath = null): bool - { - if (!\is_scalar($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not a scalar.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_SCALAR, $propertyPath); - } - - return true; - } - - /** - * Assert that value is not empty. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert !empty $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function notEmpty($value, $message = null, string $propertyPath = null): bool - { - if (empty($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is empty, but non empty value was expected.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::VALUE_EMPTY, $propertyPath); - } - - return true; - } - - /** - * Assert that value is empty. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert empty $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function noContent($value, $message = null, string $propertyPath = null): bool - { - if (!empty($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not empty, but empty value was expected.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::VALUE_NOT_EMPTY, $propertyPath); - } - - return true; - } - - /** - * Assert that value is null. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert null $value - * - * @return bool - */ - public static function null($value, $message = null, string $propertyPath = null): bool - { - if (null !== $value) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not null, but null value was expected.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::VALUE_NOT_NULL, $propertyPath); - } - - return true; - } - - /** - * Assert that value is not null. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert !null $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function notNull($value, $message = null, string $propertyPath = null): bool - { - if (null === $value) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is null, but non null value was expected.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::VALUE_NULL, $propertyPath); - } - - return true; - } - - /** - * Assert that value is a string. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert string $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function string($value, $message = null, string $propertyPath = null) - { - if (!\is_string($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" expected to be string, type %s given.'), - static::stringify($value), - \gettype($value) - ); - - throw static::createException($value, $message, static::INVALID_STRING, $propertyPath); - } - - return true; - } - - /** - * Assert that value matches a regex. - * - * @param mixed $value - * @param string $pattern - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert =string $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function regex($value, $pattern, $message = null, string $propertyPath = null): bool - { - static::string($value, $message, $propertyPath); - - if (!\preg_match($pattern, $value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" does not match expression.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_REGEX, $propertyPath, ['pattern' => $pattern]); - } - - return true; - } - - /** - * Assert that value does not match a regex. - * - * @param mixed $value - * @param string $pattern - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert !=string $value - * - * @throws AssertionFailedException - */ - public static function notRegex($value, $pattern, $message = null, string $propertyPath = null): bool - { - static::string($value, $message, $propertyPath); - - if (\preg_match($pattern, $value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" matches expression.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_NOT_REGEX, $propertyPath, ['pattern' => $pattern]); - } - - return true; - } - - /** - * Assert that string has a given length. - * - * @param mixed $value - * @param int $length - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @psalm-assert =string $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function length($value, $length, $message = null, string $propertyPath = null, $encoding = 'utf8'): bool - { - static::string($value, $message, $propertyPath); - - if (\mb_strlen($value, $encoding) !== $length) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" has to be %d exactly characters long, but length is %d.'), - static::stringify($value), - $length, - \mb_strlen($value, $encoding) - ); - - throw static::createException($value, $message, static::INVALID_LENGTH, $propertyPath, ['length' => $length, 'encoding' => $encoding]); - } - - return true; - } - - /** - * Assert that a string is at least $minLength chars long. - * - * @param mixed $value - * @param int $minLength - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @psalm-assert =string $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function minLength($value, $minLength, $message = null, string $propertyPath = null, $encoding = 'utf8'): bool - { - static::string($value, $message, $propertyPath); - - if (\mb_strlen($value, $encoding) < $minLength) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is too short, it should have at least %d characters, but only has %d characters.'), - static::stringify($value), - $minLength, - \mb_strlen($value, $encoding) - ); - - throw static::createException($value, $message, static::INVALID_MIN_LENGTH, $propertyPath, ['min_length' => $minLength, 'encoding' => $encoding]); - } - - return true; - } - - /** - * Assert that string value is not longer than $maxLength chars. - * - * @param mixed $value - * @param int $maxLength - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @psalm-assert =string $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function maxLength($value, $maxLength, $message = null, string $propertyPath = null, $encoding = 'utf8'): bool - { - static::string($value, $message, $propertyPath); - - if (\mb_strlen($value, $encoding) > $maxLength) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is too long, it should have no more than %d characters, but has %d characters.'), - static::stringify($value), - $maxLength, - \mb_strlen($value, $encoding) - ); - - throw static::createException($value, $message, static::INVALID_MAX_LENGTH, $propertyPath, ['max_length' => $maxLength, 'encoding' => $encoding]); - } - - return true; - } - - /** - * Assert that string length is between min and max lengths. - * - * @param mixed $value - * @param int $minLength - * @param int $maxLength - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @psalm-assert =string $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function betweenLength($value, $minLength, $maxLength, $message = null, string $propertyPath = null, $encoding = 'utf8'): bool - { - static::string($value, $message, $propertyPath); - static::minLength($value, $minLength, $message, $propertyPath, $encoding); - static::maxLength($value, $maxLength, $message, $propertyPath, $encoding); - - return true; - } - - /** - * Assert that string starts with a sequence of chars. - * - * @param mixed $string - * @param string $needle - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @psalm-assert =string $string - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function startsWith($string, $needle, $message = null, string $propertyPath = null, $encoding = 'utf8'): bool - { - static::string($string, $message, $propertyPath); - - if (0 !== \mb_strpos($string, $needle, 0, $encoding)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" does not start with "%s".'), - static::stringify($string), - static::stringify($needle) - ); - - throw static::createException($string, $message, static::INVALID_STRING_START, $propertyPath, ['needle' => $needle, 'encoding' => $encoding]); - } - - return true; - } - - /** - * Assert that string ends with a sequence of chars. - * - * @param mixed $string - * @param string $needle - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @psalm-assert =string $string - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function endsWith($string, $needle, $message = null, string $propertyPath = null, $encoding = 'utf8'): bool - { - static::string($string, $message, $propertyPath); - - $stringPosition = \mb_strlen($string, $encoding) - \mb_strlen($needle, $encoding); - - if (\mb_strripos($string, $needle, 0, $encoding) !== $stringPosition) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" does not end with "%s".'), - static::stringify($string), - static::stringify($needle) - ); - - throw static::createException($string, $message, static::INVALID_STRING_END, $propertyPath, ['needle' => $needle, 'encoding' => $encoding]); - } - - return true; - } - - /** - * Assert that string contains a sequence of chars. - * - * @param mixed $string - * @param string $needle - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @psalm-assert =string $string - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function contains($string, $needle, $message = null, string $propertyPath = null, $encoding = 'utf8'): bool - { - static::string($string, $message, $propertyPath); - - if (false === \mb_strpos($string, $needle, 0, $encoding)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" does not contain "%s".'), - static::stringify($string), - static::stringify($needle) - ); - - throw static::createException($string, $message, static::INVALID_STRING_CONTAINS, $propertyPath, ['needle' => $needle, 'encoding' => $encoding]); - } - - return true; - } - - /** - * Assert that string does not contains a sequence of chars. - * - * @param mixed $string - * @param string $needle - * @param string|callable|null $message - * @param string|null $propertyPath - * @param string $encoding - * - * @psalm-assert =string $string - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function notContains($string, $needle, $message = null, string $propertyPath = null, $encoding = 'utf8'): bool - { - static::string($string, $message, $propertyPath); - - if (false !== \mb_strpos($string, $needle, 0, $encoding)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" contains "%s".'), - static::stringify($string), - static::stringify($needle) - ); - - throw static::createException($string, $message, static::INVALID_STRING_NOT_CONTAINS, $propertyPath, ['needle' => $needle, 'encoding' => $encoding]); - } - - return true; - } - - /** - * Assert that value is in array of choices. - * - * @param mixed $value - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function choice($value, array $choices, $message = null, string $propertyPath = null): bool - { - if (!\in_array($value, $choices, true)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not an element of the valid values: %s'), - static::stringify($value), - \implode(', ', \array_map([\get_called_class(), 'stringify'], $choices)) - ); - - throw static::createException($value, $message, static::INVALID_CHOICE, $propertyPath, ['choices' => $choices]); - } - - return true; - } - - /** - * Assert that value is in array of choices. - * - * This is an alias of {@see choice()}. - * - * @param mixed $value - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function inArray($value, array $choices, $message = null, string $propertyPath = null): bool - { - return static::choice($value, $choices, $message, $propertyPath); - } - - /** - * Assert that value is numeric. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert numeric $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function numeric($value, $message = null, string $propertyPath = null): bool - { - if (!\is_numeric($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not numeric.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_NUMERIC, $propertyPath); - } - - return true; - } - - /** - * Assert that value is a resource. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert resource $value - * - * @return bool - */ - public static function isResource($value, $message = null, string $propertyPath = null): bool - { - if (!\is_resource($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not a resource.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_RESOURCE, $propertyPath); - } - - return true; - } - - /** - * Assert that value is an array. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert array $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function isArray($value, $message = null, string $propertyPath = null): bool - { - if (!\is_array($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not an array.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_ARRAY, $propertyPath); - } - - return true; - } - - /** - * Assert that value is an array or a traversable object. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert iterable $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function isTraversable($value, $message = null, string $propertyPath = null): bool - { - if (!\is_array($value) && !$value instanceof Traversable) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not an array and does not implement Traversable.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_TRAVERSABLE, $propertyPath); - } - - return true; - } - - /** - * Assert that value is an array or an array-accessible object. - * - * @param mixed $value - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function isArrayAccessible($value, $message = null, string $propertyPath = null): bool - { - if (!\is_array($value) && !$value instanceof ArrayAccess) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not an array and does not implement ArrayAccess.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_ARRAY_ACCESSIBLE, $propertyPath); - } - - return true; - } - - /** - * Assert that value is countable. - * - * @param array|Countable|ResourceBundle|SimpleXMLElement $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert countable $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function isCountable($value, $message = null, string $propertyPath = null): bool - { - if (\function_exists('is_countable')) { - $assert = \is_countable($value); - } else { - $assert = \is_array($value) || $value instanceof Countable || $value instanceof ResourceBundle || $value instanceof SimpleXMLElement; - } - - if (!$assert) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not an array and does not implement Countable.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_COUNTABLE, $propertyPath); - } - - return true; - } - - /** - * Assert that key exists in an array. - * - * @param mixed $value - * @param string|int $key - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function keyExists($value, $key, $message = null, string $propertyPath = null): bool - { - static::isArray($value, $message, $propertyPath); - - if (!\array_key_exists($key, $value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Array does not contain an element with key "%s"'), - static::stringify($key) - ); - - throw static::createException($value, $message, static::INVALID_KEY_EXISTS, $propertyPath, ['key' => $key]); - } - - return true; - } - - /** - * Assert that key does not exist in an array. - * - * @param mixed $value - * @param string|int $key - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function keyNotExists($value, $key, $message = null, string $propertyPath = null): bool - { - static::isArray($value, $message, $propertyPath); - - if (\array_key_exists($key, $value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Array contains an element with key "%s"'), - static::stringify($key) - ); - - throw static::createException($value, $message, static::INVALID_KEY_NOT_EXISTS, $propertyPath, ['key' => $key]); - } - - return true; - } - - /** - * Assert that values in array are unique (using strict equality). - * - * @param mixed[] $values - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function uniqueValues(array $values, $message = null, string $propertyPath = null): bool - { - foreach ($values as $key => $value) { - if (\array_search($value, $values, true) !== $key) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" occurs more than once in array'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_UNIQUE_VALUES, $propertyPath, ['value' => $value]); - } - } - - return true; - } - - /** - * Assert that key exists in an array/array-accessible object using isset(). - * - * @param mixed $value - * @param string|int $key - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function keyIsset($value, $key, $message = null, string $propertyPath = null): bool - { - static::isArrayAccessible($value, $message, $propertyPath); - - if (!isset($value[$key])) { - $message = \sprintf( - static::generateMessage($message ?: 'The element with key "%s" was not found'), - static::stringify($key) - ); - - throw static::createException($value, $message, static::INVALID_KEY_ISSET, $propertyPath, ['key' => $key]); - } - - return true; - } - - /** - * Assert that key exists in an array/array-accessible object and its value is not empty. - * - * @param mixed $value - * @param string|int $key - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function notEmptyKey($value, $key, $message = null, string $propertyPath = null): bool - { - static::keyIsset($value, $key, $message, $propertyPath); - static::notEmpty($value[$key], $message, $propertyPath); - - return true; - } - - /** - * Assert that value is not blank. - * - * @param mixed $value - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function notBlank($value, $message = null, string $propertyPath = null): bool - { - if (false === $value || (empty($value) && '0' != $value) || (\is_string($value) && '' === \trim($value))) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is blank, but was expected to contain a value.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_NOT_BLANK, $propertyPath); - } - - return true; - } - - /** - * Assert that value is instance of given class-name. - * - * @param mixed $value - * @param string $className - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-template ExpectedType of object - * @psalm-param class-string $className - * @psalm-assert ExpectedType $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function isInstanceOf($value, $className, $message = null, string $propertyPath = null): bool - { - if (!($value instanceof $className)) { - $message = \sprintf( - static::generateMessage($message ?: 'Class "%s" was expected to be instanceof of "%s" but is not.'), - static::stringify($value), - $className - ); - - throw static::createException($value, $message, static::INVALID_INSTANCE_OF, $propertyPath, ['class' => $className]); - } - - return true; - } - - /** - * Assert that value is not instance of given class-name. - * - * @param mixed $value - * @param string $className - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-template ExpectedType of object - * @psalm-param class-string $className - * @psalm-assert !ExpectedType $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function notIsInstanceOf($value, $className, $message = null, string $propertyPath = null): bool - { - if ($value instanceof $className) { - $message = \sprintf( - static::generateMessage($message ?: 'Class "%s" was not expected to be instanceof of "%s".'), - static::stringify($value), - $className - ); - - throw static::createException($value, $message, static::INVALID_NOT_INSTANCE_OF, $propertyPath, ['class' => $className]); - } - - return true; - } - - /** - * Assert that value is subclass of given class-name. - * - * @param mixed $value - * @param string $className - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function subclassOf($value, $className, $message = null, string $propertyPath = null): bool - { - if (!\is_subclass_of($value, $className)) { - $message = \sprintf( - static::generateMessage($message ?: 'Class "%s" was expected to be subclass of "%s".'), - static::stringify($value), - $className - ); - - throw static::createException($value, $message, static::INVALID_SUBCLASS_OF, $propertyPath, ['class' => $className]); - } - - return true; - } - - /** - * Assert that value is in range of numbers. - * - * @param mixed $value - * @param mixed $minValue - * @param mixed $maxValue - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert =numeric $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function range($value, $minValue, $maxValue, $message = null, string $propertyPath = null): bool - { - static::numeric($value, $message, $propertyPath); - - if ($value < $minValue || $value > $maxValue) { - $message = \sprintf( - static::generateMessage($message ?: 'Number "%s" was expected to be at least "%d" and at most "%d".'), - static::stringify($value), - static::stringify($minValue), - static::stringify($maxValue) - ); - - throw static::createException($value, $message, static::INVALID_RANGE, $propertyPath, ['min' => $minValue, 'max' => $maxValue]); - } - - return true; - } - - /** - * Assert that a value is at least as big as a given limit. - * - * @param mixed $value - * @param mixed $minValue - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert =numeric $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function min($value, $minValue, $message = null, string $propertyPath = null): bool - { - static::numeric($value, $message, $propertyPath); - - if ($value < $minValue) { - $message = \sprintf( - static::generateMessage($message ?: 'Number "%s" was expected to be at least "%s".'), - static::stringify($value), - static::stringify($minValue) - ); - - throw static::createException($value, $message, static::INVALID_MIN, $propertyPath, ['min' => $minValue]); - } - - return true; - } - - /** - * Assert that a number is smaller as a given limit. - * - * @param mixed $value - * @param mixed $maxValue - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert =numeric $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function max($value, $maxValue, $message = null, string $propertyPath = null): bool - { - static::numeric($value, $message, $propertyPath); - - if ($value > $maxValue) { - $message = \sprintf( - static::generateMessage($message ?: 'Number "%s" was expected to be at most "%s".'), - static::stringify($value), - static::stringify($maxValue) - ); - - throw static::createException($value, $message, static::INVALID_MAX, $propertyPath, ['max' => $maxValue]); - } - - return true; - } - - /** - * Assert that a file exists. - * - * @param string $value - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function file($value, $message = null, string $propertyPath = null): bool - { - static::string($value, $message, $propertyPath); - static::notEmpty($value, $message, $propertyPath); - - if (!\is_file($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'File "%s" was expected to exist.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_FILE, $propertyPath); - } - - return true; - } - - /** - * Assert that a directory exists. - * - * @param string $value - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function directory($value, $message = null, string $propertyPath = null): bool - { - static::string($value, $message, $propertyPath); - - if (!\is_dir($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Path "%s" was expected to be a directory.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_DIRECTORY, $propertyPath); - } - - return true; - } - - /** - * Assert that the value is something readable. - * - * @param string $value - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function readable($value, $message = null, string $propertyPath = null): bool - { - static::string($value, $message, $propertyPath); - - if (!\is_readable($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Path "%s" was expected to be readable.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_READABLE, $propertyPath); - } - - return true; - } - - /** - * Assert that the value is something writeable. - * - * @param string $value - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function writeable($value, $message = null, string $propertyPath = null): bool - { - static::string($value, $message, $propertyPath); - - if (!\is_writable($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Path "%s" was expected to be writeable.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_WRITEABLE, $propertyPath); - } - - return true; - } - - /** - * Assert that value is an email address (using input_filter/FILTER_VALIDATE_EMAIL). - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert =string $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function email($value, $message = null, string $propertyPath = null): bool - { - static::string($value, $message, $propertyPath); - - if (!\filter_var($value, FILTER_VALIDATE_EMAIL)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" was expected to be a valid e-mail address.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_EMAIL, $propertyPath); - } - - return true; - } - - /** - * Assert that value is an URL. - * - * This code snipped was taken from the Symfony project and modified to the special demands of this method. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert =string $value - * - * @return bool - * - * @throws AssertionFailedException - * - * @see https://github.com/symfony/Validator/blob/master/Constraints/UrlValidator.php - * @see https://github.com/symfony/Validator/blob/master/Constraints/Url.php - */ - public static function url($value, $message = null, string $propertyPath = null): bool - { - static::string($value, $message, $propertyPath); - - $protocols = ['http', 'https']; - - $pattern = '~^ - (%s):// # protocol - (([\.\pL\pN-]+:)?([\.\pL\pN-]+)@)? # basic auth - ( - ([\pL\pN\pS\-\.])+(\.?([\pL\pN]|xn\-\-[\pL\pN-]+)+\.?) # a domain name - | # or - \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} # an IP address - | # or - \[ - (?:(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){6})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:::(?:(?:(?:[0-9a-f]{1,4})):){5})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){4})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,1}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){3})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,2}(?:(?:[0-9a-f]{1,4})))?::(?:(?:(?:[0-9a-f]{1,4})):){2})(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,3}(?:(?:[0-9a-f]{1,4})))?::(?:(?:[0-9a-f]{1,4})):)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,4}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,5}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,6}(?:(?:[0-9a-f]{1,4})))?::)))) - \] # an IPv6 address - ) - (:[0-9]+)? # a port (optional) - (?:/ (?:[\pL\pN\-._\~!$&\'()*+,;=:@]|%%[0-9A-Fa-f]{2})* )* # a path - (?:\? (?:[\pL\pN\-._\~!$&\'\[\]()*+,;=:@/?]|%%[0-9A-Fa-f]{2})* )? # a query (optional) - (?:\# (?:[\pL\pN\-._\~!$&\'()*+,;=:@/?]|%%[0-9A-Fa-f]{2})* )? # a fragment (optional) - $~ixu'; - - $pattern = \sprintf($pattern, \implode('|', $protocols)); - - if (!\preg_match($pattern, $value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" was expected to be a valid URL starting with http or https'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_URL, $propertyPath); - } - - return true; - } - - /** - * Assert that value is alphanumeric. - * - * @param mixed $value - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function alnum($value, $message = null, string $propertyPath = null): bool - { - try { - static::regex($value, '(^([a-zA-Z]{1}[a-zA-Z0-9]*)$)', $message, $propertyPath); - } catch (Throwable $e) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not alphanumeric, starting with letters and containing only letters and numbers.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_ALNUM, $propertyPath); - } - - return true; - } - - /** - * Assert that the value is boolean True. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert true $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function true($value, $message = null, string $propertyPath = null): bool - { - if (true !== $value) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not TRUE.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_TRUE, $propertyPath); - } - - return true; - } - - /** - * Assert that the value is boolean False. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert false $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function false($value, $message = null, string $propertyPath = null): bool - { - if (false !== $value) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not FALSE.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_FALSE, $propertyPath); - } - - return true; - } - - /** - * Assert that the class exists. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert class-string $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function classExists($value, $message = null, string $propertyPath = null): bool - { - if (!\class_exists($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Class "%s" does not exist.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_CLASS, $propertyPath); - } - - return true; - } - - /** - * Assert that the interface exists. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert class-string $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function interfaceExists($value, $message = null, string $propertyPath = null): bool - { - if (!\interface_exists($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Interface "%s" does not exist.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_INTERFACE, $propertyPath); - } - - return true; - } - - /** - * Assert that the class implements the interface. - * - * @param mixed $class - * @param string $interfaceName - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function implementsInterface($class, $interfaceName, $message = null, string $propertyPath = null): bool - { - try { - $reflection = new ReflectionClass($class); - if (!$reflection->implementsInterface($interfaceName)) { - $message = \sprintf( - static::generateMessage($message ?: 'Class "%s" does not implement interface "%s".'), - static::stringify($class), - static::stringify($interfaceName) - ); - - throw static::createException($class, $message, static::INTERFACE_NOT_IMPLEMENTED, $propertyPath, ['interface' => $interfaceName]); - } - } catch (ReflectionException $e) { - $message = \sprintf( - static::generateMessage($message ?: 'Class "%s" failed reflection.'), - static::stringify($class) - ); - throw static::createException($class, $message, static::INTERFACE_NOT_IMPLEMENTED, $propertyPath, ['interface' => $interfaceName]); - } - - return true; - } - - /** - * Assert that the given string is a valid json string. - * - * NOTICE: - * Since this does a json_decode to determine its validity - * you probably should consider, when using the variable - * content afterwards, just to decode and check for yourself instead - * of using this assertion. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert =string $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function isJsonString($value, $message = null, string $propertyPath = null): bool - { - if (null === \json_decode($value) && JSON_ERROR_NONE !== \json_last_error()) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not a valid JSON string.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_JSON_STRING, $propertyPath); - } - - return true; - } - - /** - * Assert that the given string is a valid UUID. - * - * Uses code from {@link https://github.com/ramsey/uuid} that is MIT licensed. - * - * @param string $value - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function uuid($value, $message = null, string $propertyPath = null): bool - { - $value = \str_replace(['urn:', 'uuid:', '{', '}'], '', $value); - - if ('00000000-0000-0000-0000-000000000000' === $value) { - return true; - } - - if (!\preg_match('/^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$/', $value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not a valid UUID.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_UUID, $propertyPath); - } - - return true; - } - - /** - * Assert that the given string is a valid E164 Phone Number. - * - * @see https://en.wikipedia.org/wiki/E.164 - * - * @param string $value - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function e164($value, $message = null, string $propertyPath = null): bool - { - if (!\preg_match('/^\+?[1-9]\d{1,14}$/', $value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" is not a valid E164.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_E164, $propertyPath); - } - - return true; - } - - /** - * Assert that the count of countable is equal to count. - * - * @param array|Countable|ResourceBundle|SimpleXMLElement $countable - * @param int $count - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function count($countable, $count, $message = null, string $propertyPath = null): bool - { - if ($count !== \count($countable)) { - $message = \sprintf( - static::generateMessage($message ?: 'List does not contain exactly %d elements (%d given).'), - static::stringify($count), - static::stringify(\count($countable)) - ); - - throw static::createException($countable, $message, static::INVALID_COUNT, $propertyPath, ['count' => $count]); - } - - return true; - } - - /** - * Assert that the countable have at least $count elements. - * - * @param array|Countable|ResourceBundle|SimpleXMLElement $countable - * @param int $count - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function minCount($countable, $count, $message = null, string $propertyPath = null): bool - { - if ($count > \count($countable)) { - $message = \sprintf( - static::generateMessage($message ?: 'List should have at least %d elements, but has %d elements.'), - static::stringify($count), - static::stringify(\count($countable)) - ); - - throw static::createException($countable, $message, static::INVALID_MIN_COUNT, $propertyPath, ['count' => $count]); - } - - return true; - } - - /** - * Assert that the countable have at most $count elements. - * - * @param array|Countable|ResourceBundle|SimpleXMLElement $countable - * @param int $count - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function maxCount($countable, $count, $message = null, string $propertyPath = null): bool - { - if ($count < \count($countable)) { - $message = \sprintf( - static::generateMessage($message ?: 'List should have at most %d elements, but has %d elements.'), - static::stringify($count), - static::stringify(\count($countable)) - ); - - throw static::createException($countable, $message, static::INVALID_MAX_COUNT, $propertyPath, ['count' => $count]); - } - - return true; - } - - /** - * static call handler to implement: - * - "null or assertion" delegation - * - "all" delegation. - * - * @param string $method - * @param array $args - * - * @return bool|mixed - * - * @throws AssertionFailedException - */ - public static function __callStatic($method, $args) - { - if (0 === \strpos($method, 'nullOr')) { - if (!\array_key_exists(0, $args)) { - throw new BadMethodCallException('Missing the first argument.'); - } - - if (null === $args[0]) { - return true; - } - - $method = \substr($method, 6); - - return \call_user_func_array([\get_called_class(), $method], $args); - } - - if (0 === \strpos($method, 'all')) { - if (!\array_key_exists(0, $args)) { - throw new BadMethodCallException('Missing the first argument.'); - } - - static::isTraversable($args[0]); - - $method = \substr($method, 3); - $values = \array_shift($args); - $calledClass = \get_called_class(); - - foreach ($values as $value) { - \call_user_func_array([$calledClass, $method], \array_merge([$value], $args)); - } - - return true; - } - - throw new BadMethodCallException('No assertion Assertion#'.$method.' exists.'); - } - - /** - * Determines if the values array has every choice as key and that this choice has content. - * - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function choicesNotEmpty(array $values, array $choices, $message = null, string $propertyPath = null): bool - { - static::notEmpty($values, $message, $propertyPath); - - foreach ($choices as $choice) { - static::notEmptyKey($values, $choice, $message, $propertyPath); - } - - return true; - } - - /** - * Determines that the named method is defined in the provided object. - * - * @param string $value - * @param mixed $object - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function methodExists($value, $object, $message = null, string $propertyPath = null): bool - { - static::isObject($object, $message, $propertyPath); - - if (!\method_exists($object, $value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Expected "%s" does not exist in provided object.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_METHOD, $propertyPath, ['object' => \get_class($object)]); - } - - return true; - } - - /** - * Determines that the provided value is an object. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert object $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function isObject($value, $message = null, string $propertyPath = null): bool - { - if (!\is_object($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Provided "%s" is not a valid object.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_OBJECT, $propertyPath); - } - - return true; - } - - /** - * Determines if the value is less than given limit. - * - * @param mixed $value - * @param mixed $limit - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function lessThan($value, $limit, $message = null, string $propertyPath = null): bool - { - if ($value >= $limit) { - $message = \sprintf( - static::generateMessage($message ?: 'Provided "%s" is not less than "%s".'), - static::stringify($value), - static::stringify($limit) - ); - - throw static::createException($value, $message, static::INVALID_LESS, $propertyPath, ['limit' => $limit]); - } - - return true; - } - - /** - * Determines if the value is less or equal than given limit. - * - * @param mixed $value - * @param mixed $limit - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function lessOrEqualThan($value, $limit, $message = null, string $propertyPath = null): bool - { - if ($value > $limit) { - $message = \sprintf( - static::generateMessage($message ?: 'Provided "%s" is not less or equal than "%s".'), - static::stringify($value), - static::stringify($limit) - ); - - throw static::createException($value, $message, static::INVALID_LESS_OR_EQUAL, $propertyPath, ['limit' => $limit]); - } - - return true; - } - - /** - * Determines if the value is greater than given limit. - * - * @param mixed $value - * @param mixed $limit - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function greaterThan($value, $limit, $message = null, string $propertyPath = null): bool - { - if ($value <= $limit) { - $message = \sprintf( - static::generateMessage($message ?: 'Provided "%s" is not greater than "%s".'), - static::stringify($value), - static::stringify($limit) - ); - - throw static::createException($value, $message, static::INVALID_GREATER, $propertyPath, ['limit' => $limit]); - } - - return true; - } - - /** - * Determines if the value is greater or equal than given limit. - * - * @param mixed $value - * @param mixed $limit - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function greaterOrEqualThan($value, $limit, $message = null, string $propertyPath = null): bool - { - if ($value < $limit) { - $message = \sprintf( - static::generateMessage($message ?: 'Provided "%s" is not greater or equal than "%s".'), - static::stringify($value), - static::stringify($limit) - ); - - throw static::createException($value, $message, static::INVALID_GREATER_OR_EQUAL, $propertyPath, ['limit' => $limit]); - } - - return true; - } - - /** - * Assert that a value is greater or equal than a lower limit, and less than or equal to an upper limit. - * - * @param mixed $value - * @param mixed $lowerLimit - * @param mixed $upperLimit - * @param string|callable|null $message - * @param string $propertyPath - * - * @throws AssertionFailedException - */ - public static function between($value, $lowerLimit, $upperLimit, $message = null, string $propertyPath = null): bool - { - if ($lowerLimit > $value || $value > $upperLimit) { - $message = \sprintf( - static::generateMessage($message ?: 'Provided "%s" is neither greater than or equal to "%s" nor less than or equal to "%s".'), - static::stringify($value), - static::stringify($lowerLimit), - static::stringify($upperLimit) - ); - - throw static::createException($value, $message, static::INVALID_BETWEEN, $propertyPath, ['lower' => $lowerLimit, 'upper' => $upperLimit]); - } - - return true; - } - - /** - * Assert that a value is greater than a lower limit, and less than an upper limit. - * - * @param mixed $value - * @param mixed $lowerLimit - * @param mixed $upperLimit - * @param string|callable|null $message - * @param string $propertyPath - * - * @throws AssertionFailedException - */ - public static function betweenExclusive($value, $lowerLimit, $upperLimit, $message = null, string $propertyPath = null): bool - { - if ($lowerLimit >= $value || $value >= $upperLimit) { - $message = \sprintf( - static::generateMessage($message ?: 'Provided "%s" is neither greater than "%s" nor less than "%s".'), - static::stringify($value), - static::stringify($lowerLimit), - static::stringify($upperLimit) - ); - - throw static::createException($value, $message, static::INVALID_BETWEEN_EXCLUSIVE, $propertyPath, ['lower' => $lowerLimit, 'upper' => $upperLimit]); - } - - return true; - } - - /** - * Assert that extension is loaded. - * - * @param mixed $value - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function extensionLoaded($value, $message = null, string $propertyPath = null): bool - { - if (!\extension_loaded($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Extension "%s" is required.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_EXTENSION, $propertyPath); - } - - return true; - } - - /** - * Assert that date is valid and corresponds to the given format. - * - * @param string $value - * @param string $format supports all of the options date(), except for the following: - * N, w, W, t, L, o, B, a, A, g, h, I, O, P, Z, c, r - * @param string|callable|null $message - * - * @throws AssertionFailedException - * - * @see http://php.net/manual/function.date.php#refsect1-function.date-parameters - */ - public static function date($value, $format, $message = null, string $propertyPath = null): bool - { - static::string($value, $message, $propertyPath); - static::string($format, $message, $propertyPath); - - $dateTime = DateTime::createFromFormat('!'.$format, $value); - - if (false === $dateTime || $value !== $dateTime->format($format)) { - $message = \sprintf( - static::generateMessage($message ?: 'Date "%s" is invalid or does not match format "%s".'), - static::stringify($value), - static::stringify($format) - ); - - throw static::createException($value, $message, static::INVALID_DATE, $propertyPath, ['format' => $format]); - } - - return true; - } - - /** - * Assert that the value is an object, or a class that exists. - * - * @param mixed $value - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function objectOrClass($value, $message = null, string $propertyPath = null): bool - { - if (!\is_object($value)) { - static::classExists($value, $message, $propertyPath); - } - - return true; - } - - /** - * Assert that the value is an object or class, and that the property exists. - * - * @param mixed $value - * @param string $property - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function propertyExists($value, $property, $message = null, string $propertyPath = null): bool - { - static::objectOrClass($value); - - if (!\property_exists($value, $property)) { - $message = \sprintf( - static::generateMessage($message ?: 'Class "%s" does not have property "%s".'), - static::stringify($value), - static::stringify($property) - ); - - throw static::createException($value, $message, static::INVALID_PROPERTY, $propertyPath, ['property' => $property]); - } - - return true; - } - - /** - * Assert that the value is an object or class, and that the properties all exist. - * - * @param mixed $value - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function propertiesExist($value, array $properties, $message = null, string $propertyPath = null): bool - { - static::objectOrClass($value); - static::allString($properties, $message, $propertyPath); - - $invalidProperties = []; - foreach ($properties as $property) { - if (!\property_exists($value, $property)) { - $invalidProperties[] = $property; - } - } - - if ($invalidProperties) { - $message = \sprintf( - static::generateMessage($message ?: 'Class "%s" does not have these properties: %s.'), - static::stringify($value), - static::stringify(\implode(', ', $invalidProperties)) - ); - - throw static::createException($value, $message, static::INVALID_PROPERTY, $propertyPath, ['properties' => $properties]); - } - - return true; - } - - /** - * Assert comparison of two versions. - * - * @param string $version1 - * @param string $operator - * @param string $version2 - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function version($version1, $operator, $version2, $message = null, string $propertyPath = null): bool - { - static::notEmpty($operator, 'versionCompare operator is required and cannot be empty.'); - - if (true !== \version_compare($version1, $version2, $operator)) { - $message = \sprintf( - static::generateMessage($message ?: 'Version "%s" is not "%s" version "%s".'), - static::stringify($version1), - static::stringify($operator), - static::stringify($version2) - ); - - throw static::createException($version1, $message, static::INVALID_VERSION, $propertyPath, ['operator' => $operator, 'version' => $version2]); - } - - return true; - } - - /** - * Assert on PHP version. - * - * @param string $operator - * @param mixed $version - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function phpVersion($operator, $version, $message = null, string $propertyPath = null): bool - { - static::defined('PHP_VERSION'); - - return static::version(PHP_VERSION, $operator, $version, $message, $propertyPath); - } - - /** - * Assert that extension is loaded and a specific version is installed. - * - * @param string $extension - * @param string $operator - * @param mixed $version - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function extensionVersion($extension, $operator, $version, $message = null, string $propertyPath = null): bool - { - static::extensionLoaded($extension, $message, $propertyPath); - - return static::version(\phpversion($extension), $operator, $version, $message, $propertyPath); - } - - /** - * Determines that the provided value is callable. - * - * @param mixed $value - * @param string|callable|null $message - * @param string|null $propertyPath - * - * @psalm-assert callable $value - * - * @return bool - * - * @throws AssertionFailedException - */ - public static function isCallable($value, $message = null, string $propertyPath = null): bool - { - if (!\is_callable($value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Provided "%s" is not a callable.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_CALLABLE, $propertyPath); - } - - return true; - } - - /** - * Assert that the provided value is valid according to a callback. - * - * If the callback returns `false` the assertion will fail. - * - * @param mixed $value - * @param callable $callback - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function satisfy($value, $callback, $message = null, string $propertyPath = null): bool - { - static::isCallable($callback); - - if (false === \call_user_func($callback, $value)) { - $message = \sprintf( - static::generateMessage($message ?: 'Provided "%s" is invalid according to custom rule.'), - static::stringify($value) - ); - - throw static::createException($value, $message, static::INVALID_SATISFY, $propertyPath); - } - - return true; - } - - /** - * Assert that value is an IPv4 or IPv6 address - * (using input_filter/FILTER_VALIDATE_IP). - * - * @param string $value - * @param int|null $flag - * @param string|callable|null $message - * - * @throws AssertionFailedException - * - * @see http://php.net/manual/filter.filters.flags.php - */ - public static function ip($value, $flag = null, $message = null, string $propertyPath = null): bool - { - static::string($value, $message, $propertyPath); - if ($flag === null) { - $filterVarResult = \filter_var($value, FILTER_VALIDATE_IP); - } else { - $filterVarResult = \filter_var($value, FILTER_VALIDATE_IP, $flag); - } - if (!$filterVarResult) { - $message = \sprintf( - static::generateMessage($message ?: 'Value "%s" was expected to be a valid IP address.'), - static::stringify($value) - ); - throw static::createException($value, $message, static::INVALID_IP, $propertyPath, ['flag' => $flag]); - } - - return true; - } - - /** - * Assert that value is an IPv4 address - * (using input_filter/FILTER_VALIDATE_IP). - * - * @param string $value - * @param int|null $flag - * @param string|callable|null $message - * - * @throws AssertionFailedException - * - * @see http://php.net/manual/filter.filters.flags.php - */ - public static function ipv4($value, $flag = null, $message = null, string $propertyPath = null): bool - { - static::ip($value, $flag | FILTER_FLAG_IPV4, static::generateMessage($message ?: 'Value "%s" was expected to be a valid IPv4 address.'), $propertyPath); - - return true; - } - - /** - * Assert that value is an IPv6 address - * (using input_filter/FILTER_VALIDATE_IP). - * - * @param string $value - * @param int|null $flag - * @param string|callable|null $message - * - * @throws AssertionFailedException - * - * @see http://php.net/manual/filter.filters.flags.php - */ - public static function ipv6($value, $flag = null, $message = null, string $propertyPath = null): bool - { - static::ip($value, $flag | FILTER_FLAG_IPV6, static::generateMessage($message ?: 'Value "%s" was expected to be a valid IPv6 address.'), $propertyPath); - - return true; - } - - /** - * Assert that a constant is defined. - * - * @param mixed $constant - * @param string|callable|null $message - */ - public static function defined($constant, $message = null, string $propertyPath = null): bool - { - if (!\defined($constant)) { - $message = \sprintf(static::generateMessage($message ?: 'Value "%s" expected to be a defined constant.'), $constant); - - throw static::createException($constant, $message, static::INVALID_CONSTANT, $propertyPath); - } - - return true; - } - - /** - * Assert that a constant is defined. - * - * @param string $value - * @param string|callable|null $message - * - * @throws AssertionFailedException - */ - public static function base64($value, $message = null, string $propertyPath = null): bool - { - if (false === \base64_decode($value, true)) { - $message = \sprintf(static::generateMessage($message ?: 'Value "%s" is not a valid base64 string.'), $value); - - throw static::createException($value, $message, static::INVALID_BASE64, $propertyPath); - } - - return true; - } - - /** - * Helper method that handles building the assertion failure exceptions. - * They are returned from this method so that the stack trace still shows - * the assertions method. - * - * @param mixed $value - * @param string|callable|null $message - * @param int $code - * - * @return mixed - */ - protected static function createException($value, $message, $code, $propertyPath = null, array $constraints = []) - { - $exceptionClass = static::$exceptionClass; - - return new $exceptionClass($message, $code, $propertyPath, $value, $constraints); - } - - /** - * Make a string version of a value. - * - * @param mixed $value - */ - protected static function stringify($value): string - { - $result = \gettype($value); - - if (\is_bool($value)) { - $result = $value ? '' : ''; - } elseif (\is_scalar($value)) { - $val = (string)$value; - - if (\mb_strlen($val) > 100) { - $val = \mb_substr($val, 0, 97).'...'; - } - - $result = $val; - } elseif (\is_array($value)) { - $result = ''; - } elseif (\is_object($value)) { - $result = \get_class($value); - } elseif (\is_resource($value)) { - $result = \get_resource_type($value); - } elseif (null === $value) { - $result = ''; - } - - return $result; - } - - /** - * Generate the message. - * - * @param string|callable|null $message - */ - protected static function generateMessage($message): string - { - if (\is_callable($message)) { - $traces = \debug_backtrace(0); - - $parameters = []; - - try { - $reflection = new ReflectionClass($traces[1]['class']); - $method = $reflection->getMethod($traces[1]['function']); - foreach ($method->getParameters() as $index => $parameter) { - if ('message' !== $parameter->getName()) { - $parameters[$parameter->getName()] = \array_key_exists($index, $traces[1]['args']) - ? $traces[1]['args'][$index] - : $parameter->getDefaultValue(); - } - } - - $parameters['::assertion'] = \sprintf('%s%s%s', $traces[1]['class'], $traces[1]['type'], $traces[1]['function']); - - $message = \call_user_func_array($message, [$parameters]); - } // @codeCoverageIgnoreStart - catch (Throwable $exception) { - $message = \sprintf('Unable to generate message : %s', $exception->getMessage()); - } // @codeCoverageIgnoreEnd - } - - return (string)$message; - } -} diff --git a/src/ncc/ThirdParty/beberlei/assert/AssertionChain.php b/src/ncc/ThirdParty/beberlei/assert/AssertionChain.php deleted file mode 100644 index 0761b3d..0000000 --- a/src/ncc/ThirdParty/beberlei/assert/AssertionChain.php +++ /dev/null @@ -1,247 +0,0 @@ - - * - * @method AssertionChain alnum(string|callable $message = null, string $propertyPath = null) Assert that value is alphanumeric. - * @method AssertionChain base64(string|callable $message = null, string $propertyPath = null) Assert that a constant is defined. - * @method AssertionChain between(mixed $lowerLimit, mixed $upperLimit, string|callable $message = null, string $propertyPath = null) Assert that a value is greater or equal than a lower limit, and less than or equal to an upper limit. - * @method AssertionChain betweenExclusive(mixed $lowerLimit, mixed $upperLimit, string|callable $message = null, string $propertyPath = null) Assert that a value is greater than a lower limit, and less than an upper limit. - * @method AssertionChain betweenLength(int $minLength, int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string length is between min and max lengths. - * @method AssertionChain boolean(string|callable $message = null, string $propertyPath = null) Assert that value is php boolean. - * @method AssertionChain choice(array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices. - * @method AssertionChain choicesNotEmpty(array $choices, string|callable $message = null, string $propertyPath = null) Determines if the values array has every choice as key and that this choice has content. - * @method AssertionChain classExists(string|callable $message = null, string $propertyPath = null) Assert that the class exists. - * @method AssertionChain contains(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string contains a sequence of chars. - * @method AssertionChain count(int $count, string|callable $message = null, string $propertyPath = null) Assert that the count of countable is equal to count. - * @method AssertionChain date(string $format, string|callable $message = null, string $propertyPath = null) Assert that date is valid and corresponds to the given format. - * @method AssertionChain defined(string|callable $message = null, string $propertyPath = null) Assert that a constant is defined. - * @method AssertionChain digit(string|callable $message = null, string $propertyPath = null) Validates if an integer or integerish is a digit. - * @method AssertionChain directory(string|callable $message = null, string $propertyPath = null) Assert that a directory exists. - * @method AssertionChain e164(string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid E164 Phone Number. - * @method AssertionChain email(string|callable $message = null, string $propertyPath = null) Assert that value is an email address (using input_filter/FILTER_VALIDATE_EMAIL). - * @method AssertionChain endsWith(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string ends with a sequence of chars. - * @method AssertionChain eq(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are equal (using ==). - * @method AssertionChain eqArraySubset(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that the array contains the subset. - * @method AssertionChain extensionLoaded(string|callable $message = null, string $propertyPath = null) Assert that extension is loaded. - * @method AssertionChain extensionVersion(string $operator, mixed $version, string|callable $message = null, string $propertyPath = null) Assert that extension is loaded and a specific version is installed. - * @method AssertionChain false(string|callable $message = null, string $propertyPath = null) Assert that the value is boolean False. - * @method AssertionChain file(string|callable $message = null, string $propertyPath = null) Assert that a file exists. - * @method AssertionChain float(string|callable $message = null, string $propertyPath = null) Assert that value is a php float. - * @method AssertionChain greaterOrEqualThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater or equal than given limit. - * @method AssertionChain greaterThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater than given limit. - * @method AssertionChain implementsInterface(string $interfaceName, string|callable $message = null, string $propertyPath = null) Assert that the class implements the interface. - * @method AssertionChain inArray(array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices. This is an alias of Assertion::choice(). - * @method AssertionChain integer(string|callable $message = null, string $propertyPath = null) Assert that value is a php integer. - * @method AssertionChain integerish(string|callable $message = null, string $propertyPath = null) Assert that value is a php integer'ish. - * @method AssertionChain interfaceExists(string|callable $message = null, string $propertyPath = null) Assert that the interface exists. - * @method AssertionChain ip(int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 or IPv6 address. - * @method AssertionChain ipv4(int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 address. - * @method AssertionChain ipv6(int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv6 address. - * @method AssertionChain isArray(string|callable $message = null, string $propertyPath = null) Assert that value is an array. - * @method AssertionChain isArrayAccessible(string|callable $message = null, string $propertyPath = null) Assert that value is an array or an array-accessible object. - * @method AssertionChain isCallable(string|callable $message = null, string $propertyPath = null) Determines that the provided value is callable. - * @method AssertionChain isCountable(string|callable $message = null, string $propertyPath = null) Assert that value is countable. - * @method AssertionChain isInstanceOf(string $className, string|callable $message = null, string $propertyPath = null) Assert that value is instance of given class-name. - * @method AssertionChain isJsonString(string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid json string. - * @method AssertionChain isObject(string|callable $message = null, string $propertyPath = null) Determines that the provided value is an object. - * @method AssertionChain isResource(string|callable $message = null, string $propertyPath = null) Assert that value is a resource. - * @method AssertionChain isTraversable(string|callable $message = null, string $propertyPath = null) Assert that value is an array or a traversable object. - * @method AssertionChain keyExists(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array. - * @method AssertionChain keyIsset(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object using isset(). - * @method AssertionChain keyNotExists(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key does not exist in an array. - * @method AssertionChain length(int $length, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string has a given length. - * @method AssertionChain lessOrEqualThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less or equal than given limit. - * @method AssertionChain lessThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less than given limit. - * @method AssertionChain max(mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that a number is smaller as a given limit. - * @method AssertionChain maxCount(int $count, string|callable $message = null, string $propertyPath = null) Assert that the countable have at most $count elements. - * @method AssertionChain maxLength(int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string value is not longer than $maxLength chars. - * @method AssertionChain methodExists(mixed $object, string|callable $message = null, string $propertyPath = null) Determines that the named method is defined in the provided object. - * @method AssertionChain min(mixed $minValue, string|callable $message = null, string $propertyPath = null) Assert that a value is at least as big as a given limit. - * @method AssertionChain minCount(int $count, string|callable $message = null, string $propertyPath = null) Assert that the countable have at least $count elements. - * @method AssertionChain minLength(int $minLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that a string is at least $minLength chars long. - * @method AssertionChain noContent(string|callable $message = null, string $propertyPath = null) Assert that value is empty. - * @method AssertionChain notBlank(string|callable $message = null, string $propertyPath = null) Assert that value is not blank. - * @method AssertionChain notContains(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string does not contains a sequence of chars. - * @method AssertionChain notEmpty(string|callable $message = null, string $propertyPath = null) Assert that value is not empty. - * @method AssertionChain notEmptyKey(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object and its value is not empty. - * @method AssertionChain notEq(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not equal (using ==). - * @method AssertionChain notInArray(array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is not in array of choices. - * @method AssertionChain notIsInstanceOf(string $className, string|callable $message = null, string $propertyPath = null) Assert that value is not instance of given class-name. - * @method AssertionChain notNull(string|callable $message = null, string $propertyPath = null) Assert that value is not null. - * @method AssertionChain notRegex(string $pattern, string|callable $message = null, string $propertyPath = null) # Assert that value does not match a regex. - * @method AssertionChain notSame(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not the same (using ===). - * @method AssertionChain null(string|callable $message = null, string $propertyPath = null) Assert that value is null. - * @method AssertionChain numeric(string|callable $message = null, string $propertyPath = null) Assert that value is numeric. - * @method AssertionChain objectOrClass(string|callable $message = null, string $propertyPath = null) Assert that the value is an object, or a class that exists. - * @method AssertionChain phpVersion(mixed $version, string|callable $message = null, string $propertyPath = null) Assert on PHP version. - * @method AssertionChain propertiesExist(array $properties, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the properties all exist. - * @method AssertionChain propertyExists(string $property, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the property exists. - * @method AssertionChain range(mixed $minValue, mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that value is in range of numbers. - * @method AssertionChain readable(string|callable $message = null, string $propertyPath = null) Assert that the value is something readable. - * @method AssertionChain regex(string $pattern, string|callable $message = null, string $propertyPath = null) Assert that value matches a regex. - * @method AssertionChain same(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are the same (using ===). - * @method AssertionChain satisfy(callable $callback, string|callable $message = null, string $propertyPath = null) Assert that the provided value is valid according to a callback. - * @method AssertionChain scalar(string|callable $message = null, string $propertyPath = null) Assert that value is a PHP scalar. - * @method AssertionChain startsWith(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string starts with a sequence of chars. - * @method AssertionChain string(string|callable $message = null, string $propertyPath = null) Assert that value is a string. - * @method AssertionChain subclassOf(string $className, string|callable $message = null, string $propertyPath = null) Assert that value is subclass of given class-name. - * @method AssertionChain true(string|callable $message = null, string $propertyPath = null) Assert that the value is boolean True. - * @method AssertionChain uniqueValues(string|callable $message = null, string $propertyPath = null) Assert that values in array are unique (using strict equality). - * @method AssertionChain url(string|callable $message = null, string $propertyPath = null) Assert that value is an URL. - * @method AssertionChain uuid(string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid UUID. - * @method AssertionChain version(string $operator, string $version2, string|callable $message = null, string $propertyPath = null) Assert comparison of two versions. - * @method AssertionChain writeable(string|callable $message = null, string $propertyPath = null) Assert that the value is something writeable. - */ -class AssertionChain -{ - /** - * @var mixed - */ - private $value; - - /** - * @var string|callable|null - */ - private $defaultMessage; - - /** - * @var string|null - */ - private $defaultPropertyPath; - - /** - * Return each assertion as always valid. - * - * @var bool - */ - private $alwaysValid = false; - - /** - * Perform assertion on every element of array or traversable. - * - * @var bool - */ - private $all = false; - - /** @var string|Assertion Class to use for assertion calls */ - private $assertionClassName = 'Assert\Assertion'; - - /** - * AssertionChain constructor. - * - * @param mixed $value - * @param string|callable|null $defaultMessage - */ - public function __construct($value, $defaultMessage = null, string $defaultPropertyPath = null) - { - $this->value = $value; - $this->defaultMessage = $defaultMessage; - $this->defaultPropertyPath = $defaultPropertyPath; - } - - /** - * Call assertion on the current value in the chain. - * - * @param string $methodName - * @param array $args - */ - public function __call($methodName, $args): AssertionChain - { - if (true === $this->alwaysValid) { - return $this; - } - - try { - $method = new \ReflectionMethod($this->assertionClassName, $methodName); - } catch (\ReflectionException $exception) { - throw new \RuntimeException("Assertion '".$methodName."' does not exist."); - } - - \array_unshift($args, $this->value); - $params = $method->getParameters(); - - foreach ($params as $idx => $param) { - if (isset($args[$idx])) { - continue; - } - - switch ($param->getName()) { - case 'message': - $args[$idx] = $this->defaultMessage; - break; - case 'propertyPath': - $args[$idx] = $this->defaultPropertyPath; - break; - } - } - - if ($this->all) { - $methodName = 'all'.$methodName; - } - - \call_user_func_array([$this->assertionClassName, $methodName], $args); - - return $this; - } - - /** - * Switch chain into validation mode for an array of values. - */ - public function all(): AssertionChain - { - $this->all = true; - - return $this; - } - - /** - * Switch chain into mode allowing nulls, ignoring further assertions. - */ - public function nullOr(): AssertionChain - { - if (null === $this->value) { - $this->alwaysValid = true; - } - - return $this; - } - - /** - * @param string $className - * - * @return $this - */ - public function setAssertionClassName($className): AssertionChain - { - if (!\is_string($className)) { - throw new LogicException('Exception class name must be passed as a string'); - } - - if (Assertion::class !== $className && !\is_subclass_of($className, Assertion::class)) { - throw new LogicException($className.' is not (a subclass of) '.Assertion::class); - } - - $this->assertionClassName = $className; - - return $this; - } -} diff --git a/src/ncc/ThirdParty/beberlei/assert/AssertionFailedException.php b/src/ncc/ThirdParty/beberlei/assert/AssertionFailedException.php deleted file mode 100644 index 5522c3c..0000000 --- a/src/ncc/ThirdParty/beberlei/assert/AssertionFailedException.php +++ /dev/null @@ -1,32 +0,0 @@ -propertyPath = $propertyPath; - $this->value = $value; - $this->constraints = $constraints; - } - - /** - * User controlled way to define a sub-property causing - * the failure of a currently asserted objects. - * - * Useful to transport information about the nature of the error - * back to higher layers. - * - * @return string|null - */ - public function getPropertyPath() - { - return $this->propertyPath; - } - - /** - * Get the value that caused the assertion to fail. - * - * @return mixed - */ - public function getValue() - { - return $this->value; - } - - /** - * Get the constraints that applied to the failed assertion. - */ - public function getConstraints(): array - { - return $this->constraints; - } -} diff --git a/src/ncc/ThirdParty/beberlei/assert/LICENSE b/src/ncc/ThirdParty/beberlei/assert/LICENSE deleted file mode 100644 index 43672e7..0000000 --- a/src/ncc/ThirdParty/beberlei/assert/LICENSE +++ /dev/null @@ -1,11 +0,0 @@ -Copyright (c) 2011-2013, Benjamin Eberlei -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -- Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. -- Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. diff --git a/src/ncc/ThirdParty/beberlei/assert/LazyAssertion.php b/src/ncc/ThirdParty/beberlei/assert/LazyAssertion.php deleted file mode 100644 index 80f507a..0000000 --- a/src/ncc/ThirdParty/beberlei/assert/LazyAssertion.php +++ /dev/null @@ -1,228 +0,0 @@ - - * - * @method LazyAssertion alnum(string|callable $message = null, string $propertyPath = null) Assert that value is alphanumeric. - * @method LazyAssertion base64(string|callable $message = null, string $propertyPath = null) Assert that a constant is defined. - * @method LazyAssertion between(mixed $lowerLimit, mixed $upperLimit, string|callable $message = null, string $propertyPath = null) Assert that a value is greater or equal than a lower limit, and less than or equal to an upper limit. - * @method LazyAssertion betweenExclusive(mixed $lowerLimit, mixed $upperLimit, string|callable $message = null, string $propertyPath = null) Assert that a value is greater than a lower limit, and less than an upper limit. - * @method LazyAssertion betweenLength(int $minLength, int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string length is between min and max lengths. - * @method LazyAssertion boolean(string|callable $message = null, string $propertyPath = null) Assert that value is php boolean. - * @method LazyAssertion choice(array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices. - * @method LazyAssertion choicesNotEmpty(array $choices, string|callable $message = null, string $propertyPath = null) Determines if the values array has every choice as key and that this choice has content. - * @method LazyAssertion classExists(string|callable $message = null, string $propertyPath = null) Assert that the class exists. - * @method LazyAssertion contains(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string contains a sequence of chars. - * @method LazyAssertion count(int $count, string|callable $message = null, string $propertyPath = null) Assert that the count of countable is equal to count. - * @method LazyAssertion date(string $format, string|callable $message = null, string $propertyPath = null) Assert that date is valid and corresponds to the given format. - * @method LazyAssertion defined(string|callable $message = null, string $propertyPath = null) Assert that a constant is defined. - * @method LazyAssertion digit(string|callable $message = null, string $propertyPath = null) Validates if an integer or integerish is a digit. - * @method LazyAssertion directory(string|callable $message = null, string $propertyPath = null) Assert that a directory exists. - * @method LazyAssertion e164(string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid E164 Phone Number. - * @method LazyAssertion email(string|callable $message = null, string $propertyPath = null) Assert that value is an email address (using input_filter/FILTER_VALIDATE_EMAIL). - * @method LazyAssertion endsWith(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string ends with a sequence of chars. - * @method LazyAssertion eq(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are equal (using ==). - * @method LazyAssertion eqArraySubset(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that the array contains the subset. - * @method LazyAssertion extensionLoaded(string|callable $message = null, string $propertyPath = null) Assert that extension is loaded. - * @method LazyAssertion extensionVersion(string $operator, mixed $version, string|callable $message = null, string $propertyPath = null) Assert that extension is loaded and a specific version is installed. - * @method LazyAssertion false(string|callable $message = null, string $propertyPath = null) Assert that the value is boolean False. - * @method LazyAssertion file(string|callable $message = null, string $propertyPath = null) Assert that a file exists. - * @method LazyAssertion float(string|callable $message = null, string $propertyPath = null) Assert that value is a php float. - * @method LazyAssertion greaterOrEqualThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater or equal than given limit. - * @method LazyAssertion greaterThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is greater than given limit. - * @method LazyAssertion implementsInterface(string $interfaceName, string|callable $message = null, string $propertyPath = null) Assert that the class implements the interface. - * @method LazyAssertion inArray(array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is in array of choices. This is an alias of Assertion::choice(). - * @method LazyAssertion integer(string|callable $message = null, string $propertyPath = null) Assert that value is a php integer. - * @method LazyAssertion integerish(string|callable $message = null, string $propertyPath = null) Assert that value is a php integer'ish. - * @method LazyAssertion interfaceExists(string|callable $message = null, string $propertyPath = null) Assert that the interface exists. - * @method LazyAssertion ip(int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 or IPv6 address. - * @method LazyAssertion ipv4(int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv4 address. - * @method LazyAssertion ipv6(int $flag = null, string|callable $message = null, string $propertyPath = null) Assert that value is an IPv6 address. - * @method LazyAssertion isArray(string|callable $message = null, string $propertyPath = null) Assert that value is an array. - * @method LazyAssertion isArrayAccessible(string|callable $message = null, string $propertyPath = null) Assert that value is an array or an array-accessible object. - * @method LazyAssertion isCallable(string|callable $message = null, string $propertyPath = null) Determines that the provided value is callable. - * @method LazyAssertion isCountable(string|callable $message = null, string $propertyPath = null) Assert that value is countable. - * @method LazyAssertion isInstanceOf(string $className, string|callable $message = null, string $propertyPath = null) Assert that value is instance of given class-name. - * @method LazyAssertion isJsonString(string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid json string. - * @method LazyAssertion isObject(string|callable $message = null, string $propertyPath = null) Determines that the provided value is an object. - * @method LazyAssertion isResource(string|callable $message = null, string $propertyPath = null) Assert that value is a resource. - * @method LazyAssertion isTraversable(string|callable $message = null, string $propertyPath = null) Assert that value is an array or a traversable object. - * @method LazyAssertion keyExists(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array. - * @method LazyAssertion keyIsset(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object using isset(). - * @method LazyAssertion keyNotExists(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key does not exist in an array. - * @method LazyAssertion length(int $length, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string has a given length. - * @method LazyAssertion lessOrEqualThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less or equal than given limit. - * @method LazyAssertion lessThan(mixed $limit, string|callable $message = null, string $propertyPath = null) Determines if the value is less than given limit. - * @method LazyAssertion max(mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that a number is smaller as a given limit. - * @method LazyAssertion maxCount(int $count, string|callable $message = null, string $propertyPath = null) Assert that the countable have at most $count elements. - * @method LazyAssertion maxLength(int $maxLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string value is not longer than $maxLength chars. - * @method LazyAssertion methodExists(mixed $object, string|callable $message = null, string $propertyPath = null) Determines that the named method is defined in the provided object. - * @method LazyAssertion min(mixed $minValue, string|callable $message = null, string $propertyPath = null) Assert that a value is at least as big as a given limit. - * @method LazyAssertion minCount(int $count, string|callable $message = null, string $propertyPath = null) Assert that the countable have at least $count elements. - * @method LazyAssertion minLength(int $minLength, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that a string is at least $minLength chars long. - * @method LazyAssertion noContent(string|callable $message = null, string $propertyPath = null) Assert that value is empty. - * @method LazyAssertion notBlank(string|callable $message = null, string $propertyPath = null) Assert that value is not blank. - * @method LazyAssertion notContains(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string does not contains a sequence of chars. - * @method LazyAssertion notEmpty(string|callable $message = null, string $propertyPath = null) Assert that value is not empty. - * @method LazyAssertion notEmptyKey(string|int $key, string|callable $message = null, string $propertyPath = null) Assert that key exists in an array/array-accessible object and its value is not empty. - * @method LazyAssertion notEq(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not equal (using ==). - * @method LazyAssertion notInArray(array $choices, string|callable $message = null, string $propertyPath = null) Assert that value is not in array of choices. - * @method LazyAssertion notIsInstanceOf(string $className, string|callable $message = null, string $propertyPath = null) Assert that value is not instance of given class-name. - * @method LazyAssertion notNull(string|callable $message = null, string $propertyPath = null) Assert that value is not null. - * @method LazyAssertion notRegex(string $pattern, string|callable $message = null, string $propertyPath = null) # Assert that value does not match a regex. - * @method LazyAssertion notSame(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are not the same (using ===). - * @method LazyAssertion null(string|callable $message = null, string $propertyPath = null) Assert that value is null. - * @method LazyAssertion numeric(string|callable $message = null, string $propertyPath = null) Assert that value is numeric. - * @method LazyAssertion objectOrClass(string|callable $message = null, string $propertyPath = null) Assert that the value is an object, or a class that exists. - * @method LazyAssertion phpVersion(mixed $version, string|callable $message = null, string $propertyPath = null) Assert on PHP version. - * @method LazyAssertion propertiesExist(array $properties, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the properties all exist. - * @method LazyAssertion propertyExists(string $property, string|callable $message = null, string $propertyPath = null) Assert that the value is an object or class, and that the property exists. - * @method LazyAssertion range(mixed $minValue, mixed $maxValue, string|callable $message = null, string $propertyPath = null) Assert that value is in range of numbers. - * @method LazyAssertion readable(string|callable $message = null, string $propertyPath = null) Assert that the value is something readable. - * @method LazyAssertion regex(string $pattern, string|callable $message = null, string $propertyPath = null) Assert that value matches a regex. - * @method LazyAssertion same(mixed $value2, string|callable $message = null, string $propertyPath = null) Assert that two values are the same (using ===). - * @method LazyAssertion satisfy(callable $callback, string|callable $message = null, string $propertyPath = null) Assert that the provided value is valid according to a callback. - * @method LazyAssertion scalar(string|callable $message = null, string $propertyPath = null) Assert that value is a PHP scalar. - * @method LazyAssertion startsWith(string $needle, string|callable $message = null, string $propertyPath = null, string $encoding = 'utf8') Assert that string starts with a sequence of chars. - * @method LazyAssertion string(string|callable $message = null, string $propertyPath = null) Assert that value is a string. - * @method LazyAssertion subclassOf(string $className, string|callable $message = null, string $propertyPath = null) Assert that value is subclass of given class-name. - * @method LazyAssertion true(string|callable $message = null, string $propertyPath = null) Assert that the value is boolean True. - * @method LazyAssertion uniqueValues(string|callable $message = null, string $propertyPath = null) Assert that values in array are unique (using strict equality). - * @method LazyAssertion url(string|callable $message = null, string $propertyPath = null) Assert that value is an URL. - * @method LazyAssertion uuid(string|callable $message = null, string $propertyPath = null) Assert that the given string is a valid UUID. - * @method LazyAssertion version(string $operator, string $version2, string|callable $message = null, string $propertyPath = null) Assert comparison of two versions. - * @method LazyAssertion writeable(string|callable $message = null, string $propertyPath = null) Assert that the value is something writeable. - * @method LazyAssertion all() Switch chain into validation mode for an array of values. - * @method LazyAssertion nullOr() Switch chain into mode allowing nulls, ignoring further assertions. - */ -class LazyAssertion -{ - private $currentChainFailed = false; - private $alwaysTryAll = false; - private $thisChainTryAll = false; - private $currentChain; - private $errors = []; - - /** @var string The class to use as AssertionChain factory */ - private $assertClass = Assert::class; - - /** @var string|LazyAssertionException The class to use for exceptions */ - private $exceptionClass = LazyAssertionException::class; - - /** - * @param mixed $value - * @param string|callable|null $defaultMessage - * - * @return static - */ - public function that($value, string $propertyPath = null, $defaultMessage = null) - { - $this->currentChainFailed = false; - $this->thisChainTryAll = false; - $assertClass = $this->assertClass; - $this->currentChain = $assertClass::that($value, $defaultMessage, $propertyPath); - - return $this; - } - - /** - * @return static - */ - public function tryAll() - { - if (!$this->currentChain) { - $this->alwaysTryAll = true; - } - - $this->thisChainTryAll = true; - - return $this; - } - - /** - * @param string $method - * @param array $args - * - * @return static - */ - public function __call($method, $args) - { - if (false === $this->alwaysTryAll - && false === $this->thisChainTryAll - && true === $this->currentChainFailed - ) { - return $this; - } - - try { - \call_user_func_array([$this->currentChain, $method], $args); - } catch (AssertionFailedException $e) { - $this->errors[] = $e; - $this->currentChainFailed = true; - } - - return $this; - } - - /** - * @throws LazyAssertionException - */ - public function verifyNow(): bool - { - if ($this->errors) { - throw \call_user_func([$this->exceptionClass, 'fromErrors'], $this->errors); - } - - return true; - } - - /** - * @param string $className - * - * @return static - */ - public function setAssertClass(string $className): LazyAssertion - { - if (Assert::class !== $className && !\is_subclass_of($className, Assert::class)) { - throw new LogicException($className.' is not (a subclass of) '.Assert::class); - } - - $this->assertClass = $className; - - return $this; - } - - /** - * @param string $className - * - * @return static - */ - public function setExceptionClass(string $className): LazyAssertion - { - if (LazyAssertionException::class !== $className && !\is_subclass_of($className, LazyAssertionException::class)) { - throw new LogicException($className.' is not (a subclass of) '.LazyAssertionException::class); - } - - $this->exceptionClass = $className; - - return $this; - } -} diff --git a/src/ncc/ThirdParty/beberlei/assert/LazyAssertionException.php b/src/ncc/ThirdParty/beberlei/assert/LazyAssertionException.php deleted file mode 100644 index 212b247..0000000 --- a/src/ncc/ThirdParty/beberlei/assert/LazyAssertionException.php +++ /dev/null @@ -1,53 +0,0 @@ -getPropertyPath(), $error->getMessage()); - } - - return new static($message, $errors); - } - - public function __construct($message, array $errors) - { - parent::__construct($message, 0, null, null); - - $this->errors = $errors; - } - - /** - * @return InvalidArgumentException[] - */ - public function getErrorExceptions(): array - { - return $this->errors; - } -} diff --git a/src/ncc/ThirdParty/beberlei/assert/README.md b/src/ncc/ThirdParty/beberlei/assert/README.md deleted file mode 100644 index 518156c..0000000 --- a/src/ncc/ThirdParty/beberlei/assert/README.md +++ /dev/null @@ -1,346 +0,0 @@ -# Assert - -[![Build Status](https://img.shields.io/travis/beberlei/assert.svg?style=for-the-badge&logo=travis)](https://travis-ci.org/beberlei/assert) -[![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/beberlei/assert.svg?style=for-the-badge&logo=scrutinizer)](https://scrutinizer-ci.com/g/beberlei/assert/) -[![GitHub issues](https://img.shields.io/github/issues/beberlei/assert.svg?style=for-the-badge&logo=github)](https://github.com/beberlei/assert/issues) - -[![PHP Version](https://img.shields.io/packagist/php-v/beberlei/assert.svg?style=for-the-badge)](https://github.com/beberlei/assert) -[![Stable Version](https://img.shields.io/packagist/v/beberlei/assert.svg?style=for-the-badge&label=Latest)](https://packagist.org/packages/beberlei/assert) - -[![Total Downloads](https://img.shields.io/packagist/dt/beberlei/assert.svg?style=for-the-badge&label=Total+downloads)](https://packagist.org/packages/beberlei/assert) -[![Monthly Downloads](https://img.shields.io/packagist/dm/beberlei/assert.svg?style=for-the-badge&label=Monthly+downloads)](https://packagist.org/packages/beberlei/assert) -[![Daily Downloads](https://img.shields.io/packagist/dd/beberlei/assert.svg?style=for-the-badge&label=Daily+downloads)](https://packagist.org/packages/beberlei/assert) - -A simple php library which contains assertions and guard methods for input validation (not filtering!) in business-model, libraries and application low-level code. -The library can be used to implement pre-/post-conditions on input data. - -Idea is to reduce the amount of code for implementing assertions in your model and also simplify the code paths to implement assertions. When assertions fail, an exception is thrown, removing the -necessity for if-clauses in your code. - -The library is not using Symfony or Zend Validators for a reason: The checks have to be low-level, fast, non-object-oriented code to be used everywhere necessary. Using any of the two libraries -requires instantiation of several objects, using a locale component, translations, you name it. Its too much bloat. - -## Installation - -Using Composer: - -```sh -composer require beberlei/assert -``` - -## Example usages - -```php -= self::MAX_BLOB_SIZE) { - return $this->putLargeBlob($containerName, $blobName, $localFileName, $metadata, $leaseId, $additionalHeaders); - } - - // Put the data to Windows Azure Storage - return $this->putBlobData($containerName, $blobName, file_get_contents($localFileName), $metadata, $leaseId, $additionalHeaders); -} -``` - -### NullOr helper - -A helper method (`Assertion::nullOr*`) is provided to check if a value is null OR holds for the assertion: - -```php -notEmpty()->integer(); -Assert::that($value)->nullOr()->string()->startsWith("Foo"); -Assert::that($values)->all()->float(); -``` - -There are also two shortcut function `Assert::thatNullOr()` and `Assert::thatAll()` enabling -the "nullOr" or "all" helper respectively. - -### Lazy Assertions - -There are many cases in web development, especially when involving forms, you want to collect several errors -instead of aborting directly on the first error. This is what lazy assertions are for. Their API -works exactly like the fluent ``Assert::that()`` API, but instead of throwing an Exception directly, -they collect all errors and only trigger the exception when the method -``verifyNow()`` is called on the ``Assert\SoftAssertion`` object. - -```php -that(10, 'foo')->string() - ->that(null, 'bar')->notEmpty() - ->that('string', 'baz')->isArray() - ->verifyNow(); -``` - -The method ``that($value, $propertyPath)`` requires a property path (name), so that you know how to differentiate -the errors afterwards. - -On failure ``verifyNow()`` will throw an exception -``Assert\\LazyAssertionException`` with a combined message: - - The following 3 assertions failed: - 1) foo: Value "10" expected to be string, type integer given. - 2) bar: Value "" is empty, but non empty value was expected. - 3) baz: Value "string" is not an array. - -You can also retrieve all the ``AssertionFailedException``s by calling ``getErrorExceptions()``. -This can be useful for example to build a failure response for the user. - -For those looking to capture multiple errors on a single value when using a lazy assertion chain, -you may follow your call to ``that`` with ``tryAll`` to run all assertions against the value, and -capture all of the resulting failed assertion error messages. Here's an example: - -```php -Assert::lazy() - ->that(10, 'foo')->tryAll()->integer()->between(5, 15) - ->that(null, 'foo')->tryAll()->notEmpty()->string() - ->verifyNow(); -``` - -The above shows how to use this functionality to finely tune the behavior of reporting failures, but to make -catching all failures even easier, you may also call ``tryAll`` before making any assertions like below. This -helps to reduce method calls, and has the same behavior as above. - -```php -Assert::lazy()->tryAll() - ->that(10, 'foo')->integer()->between(5, 15) - ->that(null, 'foo')->notEmpty()->string() - ->verifyNow(); -``` - -### Functional Constructors - -The following functions exist as aliases to `Assert` static constructors: - -- `Assert\that()` -- `Assert\thatAll()` -- `Assert\thatNullOr()` -- `Assert\lazy()` - -Using the functional or static constructors is entirely personal preference. - -**Note:** The functional constructors will not work with an [`Assertion` extension](#your-own-assertion-class). -However it is trivial to recreate these functions in a way that point to the extended class. - -## List of assertions - -```php -getValue(); // the value that caused the failure - $e->getConstraints(); // the additional constraints of the assertion. -} -``` - -``Assert\AssertionFailedException`` is just an interface and the default -implementation is ``Assert\InvalidArgumentException`` which extends the SPL -``InvalidArgumentException``. You can change the exception being used on a -package based level. - -### Customised exception messages - -You can pass a callback as the message parameter, allowing you to construct your own -message only if an assertion fails, rather than every time you run the test. - -The callback will be supplied with an array of parameters that are for the assertion. - -As some assertions call other assertions, your callback will need to example the array -to determine what assertion failed. - -The array will contain a key called `::assertion` that indicates which assertion -failed. - -The callback should return the string that will be used as the exception -message. - -## Your own Assertion class - -To shield your library from possible bugs, misinterpretations or BC breaks -inside Assert you should introduce a library/project based assertion subclass, -where you can override the exception thrown as well. - -In addition, you can override the ``Assert\Assertion::stringify()`` method to -provide your own interpretations of the types during error handling. - -```php -notEmpty()->integer(); - * \Assert\that($value)->nullOr()->string()->startsWith("Foo"); - * - * The assertion chain can be stateful, that means be careful when you reuse - * it. You should never pass around the chain. - */ -function that($value, $defaultMessage = null, string $defaultPropertyPath = null): AssertionChain -{ - return Assert::that($value, $defaultMessage, $defaultPropertyPath); -} - -/** - * Start validation on a set of values, returns {@link AssertionChain}. - * - * @param mixed $values - * @param string|callable|null $defaultMessage - * @param string $defaultPropertyPath - */ -function thatAll($values, $defaultMessage = null, string $defaultPropertyPath = null): AssertionChain -{ - return Assert::thatAll($values, $defaultMessage, $defaultPropertyPath); -} - -/** - * Start validation and allow NULL, returns {@link AssertionChain}. - * - * @param mixed $value - * @param string|callable|null $defaultMessage - * @param string $defaultPropertyPath - * - * @deprecated In favour of Assert::thatNullOr($value, $defaultMessage = null, $defaultPropertyPath = null) - */ -function thatNullOr($value, $defaultMessage = null, string $defaultPropertyPath = null): AssertionChain -{ - return Assert::thatNullOr($value, $defaultMessage, $defaultPropertyPath); -} - -/** - * Create a lazy assertion object. - */ -function lazy(): LazyAssertion -{ - return Assert::lazy(); -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Action/ExitAction.php b/src/ncc/ThirdParty/php-school/cli-menu/Action/ExitAction.php deleted file mode 100644 index caa272f..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Action/ExitAction.php +++ /dev/null @@ -1,17 +0,0 @@ - - */ -class ExitAction -{ - public function __invoke(CliMenu $menu) : void - { - $menu->close(); - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Action/GoBackAction.php b/src/ncc/ThirdParty/php-school/cli-menu/Action/GoBackAction.php deleted file mode 100644 index a0f2644..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Action/GoBackAction.php +++ /dev/null @@ -1,20 +0,0 @@ - - */ -class GoBackAction -{ - public function __invoke(CliMenu $menu) : void - { - if ($parent = $menu->getParent()) { - $menu->closeThis(); - $parent->open(); - } - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Builder/CliMenuBuilder.php b/src/ncc/ThirdParty/php-school/cli-menu/Builder/CliMenuBuilder.php deleted file mode 100644 index 37d7f69..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Builder/CliMenuBuilder.php +++ /dev/null @@ -1,659 +0,0 @@ - - * @author Aydin Hassan - */ -class CliMenuBuilder -{ - /** - * @var CliMenu - */ - private $menu; - - /** - * @var string - */ - private $goBackButtonText = 'Go Back'; - - /** - * @var string - */ - private $exitButtonText = 'Exit'; - - /** - * @var MenuStyle - */ - private $style; - - /** - * @var Terminal - */ - private $terminal; - - /** - * @var bool - */ - private $disableDefaultItems = false; - - /** - * @var bool - */ - private $disabled = false; - - /** - * Whether or not to auto create keyboard shortcuts for items - * when they contain square brackets. Eg: [M]y item - * - * @var bool - */ - private $autoShortcuts = false; - - /** - * Regex to auto match for shortcuts defaults to looking - * for a single character encased in square brackets - * - * @var string - */ - private $autoShortcutsRegex = '/\[(.)\]/'; - - /** - * @var array - */ - private $extraItemStyles = []; - - /** - * @var bool - */ - private $subMenu = false; - - public function __construct(Terminal $terminal = null) - { - $this->terminal = $terminal ?? TerminalFactory::fromSystem(); - $this->style = new MenuStyle($this->terminal); - $this->menu = new CliMenu(null, [], $this->terminal, $this->style); - } - - public static function newSubMenu(Terminal $terminal) : self - { - $instance = new self($terminal); - $instance->subMenu = true; - - return $instance; - } - - public function setTitle(string $title) : self - { - $this->menu->setTitle($title); - - return $this; - } - - public function addMenuItem(MenuItemInterface $item) : self - { - $this->menu->addItem($item); - - $this->processItemShortcut($item); - - return $this; - } - - public function addItem( - string $text, - callable $itemCallable, - bool $showItemExtra = false, - bool $disabled = false - ) : self { - $this->addMenuItem(new SelectableItem($text, $itemCallable, $showItemExtra, $disabled)); - - return $this; - } - - public function addItems(array $items) : self - { - foreach ($items as $item) { - $this->addItem(...$item); - } - - return $this; - } - - public function addCheckboxItem( - string $text, - callable $itemCallable, - bool $showItemExtra = false, - bool $disabled = false - ) : self { - $this->addMenuItem(new CheckboxItem($text, $itemCallable, $showItemExtra, $disabled)); - - return $this; - } - - public function addCheckboxItems(array $items): self - { - foreach ($items as $item) { - $this->addCheckboxItem(...$item); - } - - return $this; - } - - public function addRadioItem( - string $text, - callable $itemCallable, - bool $showItemExtra = false, - bool $disabled = false - ) : self { - $this->addMenuItem(new RadioItem($text, $itemCallable, $showItemExtra, $disabled)); - - return $this; - } - - public function addRadioItems(array $items): self - { - foreach ($items as $item) { - $this->addRadioItem(...$item); - } - - return $this; - } - - public function addStaticItem(string $text) : self - { - $this->addMenuItem(new StaticItem($text)); - - return $this; - } - - public function addLineBreak(string $breakChar = ' ', int $lines = 1) : self - { - $this->addMenuItem(new LineBreakItem($breakChar, $lines)); - - return $this; - } - - public function addAsciiArt(string $art, string $position = AsciiArtItem::POSITION_CENTER, string $alt = '') : self - { - $this->addMenuItem(new AsciiArtItem($art, $position, $alt)); - - return $this; - } - - public function addSubMenu(string $text, \Closure $callback) : self - { - $builder = self::newSubMenu($this->terminal); - - if ($this->autoShortcuts) { - $builder->enableAutoShortcuts($this->autoShortcutsRegex); - } - - each($this->extraItemStyles, function (int $i, array $extraItemStyle) use ($builder) { - $builder->registerItemStyle($extraItemStyle['class'], $extraItemStyle['style']); - }); - - $callback($builder); - - $menu = $builder->build(); - $menu->setParent($this->menu); - - $this->menu->addItem($item = new MenuMenuItem( - $text, - $menu, - $builder->isMenuDisabled() - )); - - $this->processItemShortcut($item); - - return $this; - } - - public function addSubMenuFromBuilder(string $text, CliMenuBuilder $builder) : self - { - $menu = $builder->build(); - $menu->setParent($this->menu); - - $this->menu->addItem($item = new MenuMenuItem( - $text, - $menu, - $builder->isMenuDisabled() - )); - - $this->processItemShortcut($item); - - return $this; - } - - public function enableAutoShortcuts(string $regex = null) : self - { - $this->autoShortcuts = true; - - if (null !== $regex) { - $this->autoShortcutsRegex = $regex; - } - - return $this; - } - - private function extractShortcut(string $title) : ?string - { - preg_match($this->autoShortcutsRegex, $title, $match); - - if (!isset($match[1])) { - return null; - } - - if (mb_strlen($match[1]) > 1) { - throw InvalidShortcutException::fromShortcut($match[1]); - } - - return isset($match[1]) ? strtolower($match[1]) : null; - } - - private function processItemShortcut(MenuItemInterface $item) : void - { - $this->processIndividualShortcut($item, function (CliMenu $menu) use ($item) { - $menu->executeAsSelected($item); - }); - } - - private function processSplitItemShortcuts(SplitItem $splitItem) : void - { - foreach ($splitItem->getItems() as $item) { - $this->processIndividualShortcut($item, function (CliMenu $menu) use ($splitItem, $item) { - $current = $splitItem->getSelectedItemIndex(); - - $splitItem->setSelectedItemIndex( - (int) array_search($item, $splitItem->getItems(), true) - ); - - $menu->executeAsSelected($splitItem); - - if ($current !== null) { - $splitItem->setSelectedItemIndex($current); - } - }); - } - } - - private function processIndividualShortcut(MenuItemInterface $item, callable $callback) : void - { - if (!$this->autoShortcuts) { - return; - } - - if ($shortcut = $this->extractShortcut($item->getText())) { - $this->menu->addCustomControlMapping( - $shortcut, - $callback - ); - } - } - - public function addSplitItem(\Closure $callback) : self - { - $builder = new SplitItemBuilder($this->menu); - - if ($this->autoShortcuts) { - $builder->enableAutoShortcuts($this->autoShortcutsRegex); - } - - each($this->extraItemStyles, function (int $i, array $extraItemStyle) use ($builder) { - $builder->registerItemStyle($extraItemStyle['class'], $extraItemStyle['style']); - }); - - $callback($builder); - - $this->menu->addItem($splitItem = $builder->build()); - - $this->processSplitItemShortcuts($splitItem); - - return $this; - } - - /** - * Disable a submenu - * - * @throws \InvalidArgumentException - */ - public function disableMenu() : self - { - if (!$this->subMenu) { - throw new \InvalidArgumentException( - 'You can\'t disable the root menu' - ); - } - - $this->disabled = true; - - return $this; - } - - public function isMenuDisabled() : bool - { - return $this->disabled; - } - - public function setGoBackButtonText(string $goBackButtonTest) : self - { - $this->goBackButtonText = $goBackButtonTest; - - return $this; - } - - public function setExitButtonText(string $exitButtonText) : self - { - $this->exitButtonText = $exitButtonText; - - return $this; - } - - public function setBackgroundColour(string $colour, string $fallback = null) : self - { - $this->style->setBg($colour, $fallback); - - return $this; - } - - public function setForegroundColour(string $colour, string $fallback = null) : self - { - $this->style->setFg($colour, $fallback); - - return $this; - } - - public function setWidth(int $width) : self - { - $this->style->setWidth($width); - - return $this; - } - - public function setPadding(int $topBottom, int $leftRight = null) : self - { - $this->style->setPadding($topBottom, $leftRight); - - return $this; - } - - public function setPaddingTopBottom(int $topBottom) : self - { - $this->style->setPaddingTopBottom($topBottom); - - return $this; - } - - public function setPaddingLeftRight(int $leftRight) : self - { - $this->style->setPaddingLeftRight($leftRight); - - return $this; - } - - public function setMarginAuto() : self - { - $this->style->setMarginAuto(); - - return $this; - } - - public function setMargin(int $margin) : self - { - $this->style->setMargin($margin); - - return $this; - } - - public function setItemExtra(string $extra) : self - { - $this->style->setItemExtra($extra); - $this->getSelectableStyle()->setItemExtra($extra); - - // if we customise item extra, it means we most likely want to display it - $this->displayExtra(); - - return $this; - } - - public function setTitleSeparator(string $separator) : self - { - $this->style->setTitleSeparator($separator); - - return $this; - } - - /** - * @param int|string|null $right - * @param int|string|null $bottom - * @param int|string|null $left - */ - public function setBorder(int $top, $right = null, $bottom = null, $left = null, string $colour = null) : self - { - $this->style->setBorder($top, $right, $bottom, $left, $colour); - - return $this; - } - - public function setBorderTopWidth(int $width) : self - { - $this->style->setBorderTopWidth($width); - - return $this; - } - - public function setBorderRightWidth(int $width) : self - { - $this->style->setBorderRightWidth($width); - - return $this; - } - - public function setBorderBottomWidth(int $width) : self - { - $this->style->setBorderBottomWidth($width); - - return $this; - } - - public function setBorderLeftWidth(int $width) : self - { - $this->style->setBorderLeftWidth($width); - - return $this; - } - - public function setBorderColour(string $colour, string $fallback = null) : self - { - $this->style->setBorderColour($colour, $fallback); - - return $this; - } - - public function getStyle() : MenuStyle - { - return $this->style; - } - - public function getTerminal() : Terminal - { - return $this->terminal; - } - - private function getDefaultItems() : array - { - $actions = []; - if ($this->subMenu) { - $actions[] = new SelectableItem($this->goBackButtonText, new GoBackAction); - } - - $actions[] = new SelectableItem($this->exitButtonText, new ExitAction); - return $actions; - } - - public function disableDefaultItems() : self - { - $this->disableDefaultItems = true; - - return $this; - } - - public function displayExtra() : self - { - $this->style->setDisplaysExtra(true); - $this->getSelectableStyle()->setDisplaysExtra(true); - $this->getCheckboxStyle()->setDisplaysExtra(true); - $this->getRadioStyle()->setDisplaysExtra(true); - - return $this; - } - - private function itemsHaveExtra(array $items) : bool - { - return !empty(array_filter($items, function (MenuItemInterface $item) { - return $item->showsItemExtra(); - })); - } - - public function build() : CliMenu - { - if (!$this->disableDefaultItems) { - $this->menu->addItems($this->getDefaultItems()); - } - - if (!$this->style->getDisplaysExtra()) { - $this->style->setDisplaysExtra($this->itemsHaveExtra($this->menu->getItems())); - } - - if (!$this->subMenu) { - $this->menu->propagateStyles(); - } - - return $this->menu; - } - - public function getDefaultStyle() : DefaultStyle - { - $style = $this->menu->getItemStyle(DefaultStyle::class); - assert($style instanceof DefaultStyle); - return $style; - } - - public function setDefaultStyle(DefaultStyle $style) : self - { - $this->menu->setItemStyle($style, DefaultStyle::class); - - return $this; - } - - public function modifyDefaultStyle(callable $itemCallable) : self - { - $itemCallable($this->getDefaultStyle()); - - return $this; - } - - public function getSelectableStyle() : SelectableStyle - { - $style = $this->menu->getItemStyle(SelectableStyle::class); - assert($style instanceof SelectableStyle); - return $style; - } - - public function setSelectableStyle(SelectableStyle $style) : self - { - $this->menu->setItemStyle($style, SelectableStyle::class); - - return $this; - } - - public function modifySelectableStyle(callable $itemCallable) : self - { - $itemCallable($this->getSelectableStyle()); - - return $this; - } - - public function getCheckboxStyle() : CheckboxStyle - { - $style = $this->menu->getItemStyle(CheckboxStyle::class); - assert($style instanceof CheckboxStyle); - return $style; - } - - public function setCheckboxStyle(CheckboxStyle $style) : self - { - $this->menu->setItemStyle($style, CheckboxStyle::class); - - return $this; - } - - public function modifyCheckboxStyle(callable $itemCallable) : self - { - $itemCallable($this->getCheckboxStyle()); - - return $this; - } - - public function getRadioStyle() : RadioStyle - { - $style = $this->menu->getItemStyle(RadioStyle::class); - assert($style instanceof RadioStyle); - return $style; - } - - public function setRadioStyle(RadioStyle $style) : self - { - $this->menu->setItemStyle($style, RadioItem::class); - - return $this; - } - - public function modifyRadioStyle(callable $itemCallable) : self - { - $itemCallable($this->getRadioStyle()); - - return $this; - } - - public function modifyStyle(string $styleClass, callable $itemCallable) : self - { - $itemCallable($this->menu->getItemStyle($styleClass)); - - return $this; - } - - public function registerItemStyle(string $itemClass, ItemStyle $itemStyle) : self - { - $this->menu->getStyleLocator() - ->registerItemStyle($itemClass, $itemStyle); - - $this->extraItemStyles[] = ['class' => $itemClass, 'style' => $itemStyle]; - - return $this; - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Builder/SplitItemBuilder.php b/src/ncc/ThirdParty/php-school/cli-menu/Builder/SplitItemBuilder.php deleted file mode 100644 index f2f8468..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Builder/SplitItemBuilder.php +++ /dev/null @@ -1,169 +0,0 @@ - - */ -class SplitItemBuilder -{ - /** - * @var CliMenu - */ - private $menu; - - /** - * @var SplitItem - */ - private $splitItem; - - /** - * Whether or not to auto create keyboard shortcuts for items - * when they contain square brackets. Eg: [M]y item - * - * @var bool - */ - private $autoShortcuts = false; - - /** - * Regex to auto match for shortcuts defaults to looking - * for a single character encased in square brackets - * - * @var string - */ - private $autoShortcutsRegex = '/\[(.)\]/'; - - /** - * @var array - */ - private $extraItemStyles = []; - - public function __construct(CliMenu $menu) - { - $this->menu = $menu; - $this->splitItem = new SplitItem(); - } - - public function addItem( - string $text, - callable $itemCallable, - bool $showItemExtra = false, - bool $disabled = false - ) : self { - $this->splitItem->addItem(new SelectableItem($text, $itemCallable, $showItemExtra, $disabled)); - - return $this; - } - - public function addCheckboxItem( - string $text, - callable $itemCallable, - bool $showItemExtra = false, - bool $disabled = false - ) : self { - $this->splitItem->addItem(new CheckboxItem($text, $itemCallable, $showItemExtra, $disabled)); - - return $this; - } - - public function addRadioItem( - string $text, - callable $itemCallable, - bool $showItemExtra = false, - bool $disabled = false - ) : self { - $this->splitItem->addItem(new RadioItem($text, $itemCallable, $showItemExtra, $disabled)); - - return $this; - } - - public function addStaticItem(string $text) : self - { - $this->splitItem->addItem(new StaticItem($text)); - - return $this; - } - - public function addLineBreak(string $breakChar = ' ', int $lines = 1) : self - { - $this->splitItem->addItem(new LineBreakItem($breakChar, $lines)); - - return $this; - } - - public function addSubMenu(string $text, \Closure $callback) : self - { - $builder = CliMenuBuilder::newSubMenu($this->menu->getTerminal()); - - if ($this->autoShortcuts) { - $builder->enableAutoShortcuts($this->autoShortcutsRegex); - } - - each($this->extraItemStyles, function (int $i, array $extraItemStyle) use ($builder) { - $builder->registerItemStyle($extraItemStyle['class'], $extraItemStyle['style']); - }); - - $callback($builder); - - $menu = $builder->build(); - $menu->setParent($this->menu); - - $this->splitItem->addItem(new MenuMenuItem( - $text, - $menu, - $builder->isMenuDisabled() - )); - - return $this; - } - - public function addMenuItem(MenuItemInterface $item) : self - { - $this->splitItem->addItem($item); - - return $this; - } - - public function setGutter(int $gutter) : self - { - $this->splitItem->setGutter($gutter); - - return $this; - } - - public function enableAutoShortcuts(string $regex = null) : self - { - $this->autoShortcuts = true; - - if (null !== $regex) { - $this->autoShortcutsRegex = $regex; - } - - return $this; - } - - public function registerItemStyle(string $itemClass, ItemStyle $itemStyle) : self - { - $this->extraItemStyles[] = ['class' => $itemClass, 'style' => $itemStyle]; - - return $this; - } - - public function build() : SplitItem - { - return $this->splitItem; - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/CHANGELOG.md b/src/ncc/ThirdParty/php-school/cli-menu/CHANGELOG.md deleted file mode 100644 index 3431d49..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/CHANGELOG.md +++ /dev/null @@ -1,161 +0,0 @@ -# Change Log -All notable changes to this project will be documented in this file. -Updates should follow the [Keep a CHANGELOG](http://keepachangelog.com/) principles. - -## [Unreleased][unreleased] -### Added - -### Changed - -### Fixed - -### Removed - -## [4.3.0] -### Fixed - - PHP 8.1 Support (#252, #249) - -### Added - - declare(strict_types=1) everywhere - -## [4.2.0] -### Added - - Yes/no confirmation dialogue (#248) - - Ability to add multiple checkbox and radio items (#241) - -## [4.1.0] -### Added - - Ability to modify password length for password input (#235) - - Improve the formatting of disabled menu items in different terminals (#236) - - Support for PHP8 (#240) - -## [4.0.0] -### Added - - Add PHP 7.4 support (#183) - - CheckboxItem & RadioItem (#186, #189, #193, #194, #226) - - Ability to force display extra (#187) - - Individual style objects for each item type (#211, #212, #213, #214, #216, #230) - - Method getStyle() to interface ncc\PhpSchool\CliMenu\MenuItem\MenuItemInterface - -### Fixed - - Fixed item extra rendering outside of menu (#66, £184, #187) - - Fix unresponsive menu upon closing and reopening (#198) - - Menu styles incorrectly propagating to submenus (#201, #210) - - Various issues with the menu width, when the terminal was too small (#223, #220, #219) - -### Removed - - Remove rebinding $this in builder closures so we can access the real $this (#191, #192, #196) - - Marker methods from ncc\PhpSchool\CliMenu\MenuStyle: - #getSelectedMarker() - #setSelectedMarker() - #getUnselectedMarker() - #setUnselectedMarker() - #getMarker() - - ncc\PhpSchool\CliMenu\MenuItem\SelectableTrait - - Marker methods from ncc\PhpSchool\CliMenu\Builder\CliMenuBuilder: - #setUnselectedMarker() - #setSelectedMarker() - -## [3.2.0] -### Added - - Allow ESC key to "cancel" editing an input (#174) - - Methods for disabling the default VIM mappings and setting your own (#172) - - Ability to set custom validator on Text and Number inputs (#177) - - Ability to turn on automatic item shortcuts (#176) - -## [3.1.0] -### Changed - - Update dependencies + fix some static analysis issues - -## [3.0.0] -### Changed - - Optimise redrawing to reduce flickering (#83) - - Use parent menu terminal when creating sub menus to reduce object graph (#94) - - Do not print right margin. Causes menu to wrap even when row fits in terminal (#116) - - CliMenu throws a \RuntimeException if it is opened with no items added (#146, #130) - - Sub Menus are configured via closures (#155) - - Remove restriction of 1 character length for markers (#141) - - Remove the mandatory space after markers for now they can be of any length (#154) - -### Added - - Added type hints everywhere (#79) - - Added phpstan to the travis build (#79) - - Input dialogue system for prompting users. Comes with text, number and password inputs (#81) - - Added ability to pass already prepared CliMenuBuilder instance to CliMenuBuilder#addSubMenuFromBuilder (#85, 155) - - Added CliMenu#addItems & CliMenu#setItems to add multiple items and replace them (#86) - - Added custom control mapping - link any key to a callable to immediately execute it (#87) - - Added MenuMenuItem#getSubMenu (#92) - - Added alternate text to AsciiArtItem to display if the ascii art is too large for the current terminal (#93) - - Added the ability to pass existing MenuStyle instance to dialogues and inputs for consistent themes and reduced object graph (#99) - - Added CSS like borders (#100) - - Added option to auto center menu with CliMenuBuilder#setMarginAuto (#103) - - Added option to auto center menu with CliMenuBuilder#setMarginAuto (#103) - - Added support for 256 colours with automatic and manual fallback to 8 colours (#104) - - Added clear option to CliMenu#redraw useful for when reducing the terminal width (#117) - - Added ability to set top/bottom and left/right padding independently (#121) - - Added a new Split Item item type which allows displaying multiple items on one line (#127) - - Added setText methods to various items so they can be modified at runtime (#153) - - Added MenuStyle#hasChangedFromDefaults to check if a MenuStyle has been modified (#149) - - Added CliMenu#setTitle and CliMenu#setStyle (#155) - - Added CliMenuBuilder#getStyle to get the current style object for the menu - -### Fixed - - Fixed sub menu go back button freezing menu (#88) - - Fixed centering ascii art items with trailing white space (#102) - - Enable cursor when exiting menu (#110) - - Fixed (#71) - changed padding calculation when row too long to stop php notices (#112) - - Fixed wordwrap helper (#134) - - Fixed selected item issues when adding/setting/removing items (#156) - - Fix infinite loop when no selectable items in menu (#159, #144) - -### Removed - - Dropped PHP 5.x and PHP 7.0 support (#79) - - Removed the Terminal namespace which has been migrated to php-school/terminal (#81) - - Removed MenuStyle::getDefaultStyleValues (#149) - - Removed CliMenuBuilder#setTerminal (#149) - - Removed CliMenuBuilder#getSubMenu (#155) - - Removed CliMenuBuilder#getMenuStyle (#155) - - Removed CliMenuBuilder#end (#155) - -## [2.1.0] -### Changed - - Use new static for submenu to allow subclassing (#68) - -### Added - - Add emacs style up/down shortcuts ctrl+n and ctrl+p (#67) - -## [2.0.2] -### Fixed - - Don't output ascii art if the terminal width is too small (#63) - -## [2.0.1] -### Fixed - - Reset array keys after removing an item from the menu (#61) - -## [2.0.0] -### Fixed - - PHPUnit deprecations - updated to createMock() - -### Changed - - Require ext-posix (#50) - - Make MenuStyle easier to construct by only allowing changes to be made via setters (#45) - -### Added - - Added getStyle() to CliMenu to get access to the style object from the menu itself (#42) - - Added redraw method to CliMenu which can redraw the menu immediately with any style changes. See - examples/crazy-redraw.php for an example (#43) - - Added tests for child menu style inheritance (#44) - - Add getter getItems() to get all items from the menu (#46) - - Add method removeItem(ItemInterface $item) to remove an item from the menu (#46) - - Ability to toggle item extra while the menu is open - see examples/toggle-item-extra.php (#46) - - Added dialogues flash and confirm - they both display some text on top of the menu, flash is dismissed with - any key press where the confirm requires enter to be pressed on the provided button. - See examples/confirm.php and examples/flash.php (#49) - -### Removed - - Removed windows terminal - many required terminal features are unavailable (#50) - - Individual component instantiation restrictions (#41) - - ## [1.2.0] - ### Added - - Added ability to disable menu items and sub-menus, they will appear dimmed and will be un-selectable (#40) diff --git a/src/ncc/ThirdParty/php-school/cli-menu/CliMenu.php b/src/ncc/ThirdParty/php-school/cli-menu/CliMenu.php deleted file mode 100644 index 6f45262..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/CliMenu.php +++ /dev/null @@ -1,786 +0,0 @@ - - */ -class CliMenu -{ - /** - * @var Terminal - */ - protected $terminal; - - /** - * @var MenuStyle - */ - protected $style; - - /** - * @var Locator - */ - private $itemStyleLocator; - - /** - * @var ?string - */ - protected $title; - - /** - * @var MenuItemInterface[] - */ - protected $items = []; - - /** - * @var int|null - */ - protected $selectedItem; - - /** - * @var bool - */ - protected $open = false; - - /** - * @var CliMenu|null - */ - protected $parent; - - /** - * @var array - */ - protected $defaultControlMappings = [ - '^P' => InputCharacter::UP, - 'k' => InputCharacter::UP, - '^K' => InputCharacter::DOWN, - 'j' => InputCharacter::DOWN, - "\r" => InputCharacter::ENTER, - ' ' => InputCharacter::ENTER, - 'l' => InputCharacter::LEFT, - 'm' => InputCharacter::RIGHT, - ]; - - /** - * @var array - */ - protected $customControlMappings = []; - - /** - * @var Frame - */ - private $currentFrame; - - public function __construct( - ?string $title, - array $items, - Terminal $terminal = null, - MenuStyle $style = null - ) { - $this->title = $title; - $this->items = $items; - $this->terminal = $terminal ?: TerminalFactory::fromSystem(); - $this->style = $style ?: new MenuStyle($this->terminal); - - $this->itemStyleLocator = new Locator(); - - $this->selectFirstItem(); - } - - /** - * Configure the terminal to work with CliMenu - */ - protected function configureTerminal() : void - { - $this->assertTerminalIsValidTTY(); - - $this->terminal->disableCanonicalMode(); - $this->terminal->disableEchoBack(); - $this->terminal->disableCursor(); - $this->terminal->clear(); - } - - /** - * Revert changes made to the terminal - */ - protected function tearDownTerminal() : void - { - $this->terminal->restoreOriginalConfiguration(); - $this->terminal->enableCanonicalMode(); - $this->terminal->enableEchoBack(); - $this->terminal->enableCursor(); - } - - private function assertTerminalIsValidTTY() : void - { - if (!$this->terminal->isInteractive()) { - throw new InvalidTerminalException('Terminal is not interactive (TTY)'); - } - } - - public function setTitle(string $title) : void - { - $this->title = $title; - } - - public function getTitle() : ?string - { - return $this->title; - } - - public function setParent(CliMenu $parent) : void - { - $this->parent = $parent; - } - - public function getParent() : ?CliMenu - { - return $this->parent; - } - - public function getTerminal() : Terminal - { - return $this->terminal; - } - - public function isOpen() : bool - { - return $this->open; - } - - /** - * Add a new Item to the menu - */ - public function addItem(MenuItemInterface $item) : void - { - $this->items[] = $item; - - $this->selectFirstItem(); - } - - /** - * Add multiple Items to the menu - */ - public function addItems(array $items) : void - { - foreach ($items as $item) { - $this->items[] = $item; - } - - $this->selectFirstItem(); - } - - /** - * Set Items of the menu - */ - public function setItems(array $items) : void - { - $this->selectedItem = null; - $this->items = $items; - - $this->selectFirstItem(); - } - - /** - * Set the selected pointer to the first selectable item - */ - private function selectFirstItem() : void - { - if (null === $this->selectedItem) { - foreach ($this->items as $key => $item) { - if ($item->canSelect()) { - $this->selectedItem = $key; - break; - } - } - } - } - - /** - * Disables the built-in VIM control mappings - */ - public function disableDefaultControlMappings() : void - { - $this->defaultControlMappings = []; - } - - /** - * Set default control mappings - */ - public function setDefaultControlMappings(array $defaultControlMappings) : void - { - $this->defaultControlMappings = $defaultControlMappings; - } - - /** - * Adds a custom control mapping - */ - public function addCustomControlMapping(string $input, callable $callable) : void - { - if (isset($this->defaultControlMappings[$input]) || isset($this->customControlMappings[$input])) { - throw new \InvalidArgumentException('Cannot rebind this input'); - } - - $this->customControlMappings[$input] = $callable; - } - - public function getCustomControlMappings() : array - { - return $this->customControlMappings; - } - - /** - * Shorthand function to add multiple custom control mapping at once - */ - public function addCustomControlMappings(array $map) : void - { - foreach ($map as $input => $callable) { - $this->addCustomControlMapping($input, $callable); - } - } - - /** - * Removes a custom control mapping - */ - public function removeCustomControlMapping(string $input) : void - { - if (!isset($this->customControlMappings[$input])) { - throw new \InvalidArgumentException('This input is not registered'); - } - - unset($this->customControlMappings[$input]); - } - - /** - * Display menu and capture input - */ - private function display() : void - { - $this->draw(); - - $reader = new NonCanonicalReader($this->terminal); - $reader->addControlMappings($this->defaultControlMappings); - - while ($this->isOpen()) { - $char = $reader->readCharacter(); - if (!$char->isHandledControl()) { - $rawChar = $char->get(); - if (isset($this->customControlMappings[$rawChar])) { - $this->customControlMappings[$rawChar]($this); - } - continue; - } - - switch ($char->getControl()) { - case InputCharacter::UP: - case InputCharacter::DOWN: - $this->moveSelectionVertically($char->getControl()); - $this->draw(); - break; - case InputCharacter::LEFT: - case InputCharacter::RIGHT: - $this->moveSelectionHorizontally($char->getControl()); - $this->draw(); - break; - case InputCharacter::ENTER: - $this->executeCurrentItem(); - break; - } - } - } - - /** - * Move the selection in a given direction, up / down - */ - protected function moveSelectionVertically(string $direction) : void - { - $itemKeys = array_keys($this->items); - - $increments = 0; - - do { - $increments++; - - if ($increments > count($itemKeys)) { - //full cycle detected, there must be no selected items - //in the menu, so stop trying to select one. - return; - } - - $direction === 'UP' - ? $this->selectedItem-- - : $this->selectedItem++; - - if ($this->selectedItem !== null && !array_key_exists($this->selectedItem, $this->items)) { - $this->selectedItem = $direction === 'UP' - ? (int) end($itemKeys) - : (int) reset($itemKeys); - } - } while (!$this->canSelect()); - } - - /** - * Move the selection in a given direction, left / right - */ - protected function moveSelectionHorizontally(string $direction) : void - { - if (!$this->items[$this->selectedItem] instanceof SplitItem) { - return; - } - - /** @var SplitItem $item */ - $item = $this->items[$this->selectedItem]; - $itemKeys = array_keys($item->getItems()); - $selectedItemIndex = $item->getSelectedItemIndex(); - - if (null === $selectedItemIndex) { - $selectedItemIndex = 0; - } - - do { - $direction === 'LEFT' - ? $selectedItemIndex-- - : $selectedItemIndex++; - - if (!array_key_exists($selectedItemIndex, $item->getItems())) { - $selectedItemIndex = $direction === 'LEFT' - ? (int) end($itemKeys) - : (int) reset($itemKeys); - } - } while (!$item->canSelectIndex($selectedItemIndex)); - - $item->setSelectedItemIndex($selectedItemIndex); - } - - /** - * Can the currently selected item actually be selected? - * - * For example: - * selectable item -> yes - * static item -> no - * split item with only static items -> no - * split item with at least one selectable item -> yes - * - * @return bool - */ - private function canSelect() : bool - { - return $this->items[$this->selectedItem]->canSelect(); - } - - /** - * Retrieve the item the user actually selected - * - */ - public function getSelectedItem() : MenuItemInterface - { - if (null === $this->selectedItem) { - throw new \RuntimeException('No selected item'); - } - - $item = $this->items[$this->selectedItem]; - return $item instanceof SplitItem - ? $item->getSelectedItem() - : $item; - } - - public function setSelectedItem(MenuItemInterface $item) : void - { - $key = array_search($item, $this->items, true); - - if (false === $key) { - throw new \InvalidArgumentException('Item does not exist in menu'); - } - - $this->selectedItem = (int) $key; - } - - public function getSelectedItemIndex() : int - { - if (null === $this->selectedItem) { - throw new \RuntimeException('No selected item'); - } - - return $this->selectedItem; - } - - public function getItemByIndex(int $index) : MenuItemInterface - { - if (!isset($this->items[$index])) { - throw new \RuntimeException('Item with index does not exist'); - } - - return $this->items[$index]; - } - - public function executeAsSelected(MenuItemInterface $item) : void - { - $current = $this->items[$this->selectedItem]; - $this->setSelectedItem($item); - $this->executeCurrentItem(); - $this->setSelectedItem($current); - } - - /** - * Execute the current item - */ - protected function executeCurrentItem() : void - { - $item = $this->getSelectedItem(); - - if ($item->canSelect()) { - $callable = $item->getSelectAction(); - if ($callable) { - $callable($this); - } - } - } - - /** - * If true we clear the whole terminal screen, useful - * for example when reducing the width of the menu, to not - * leave leftovers of the previous wider menu. - * - * Redraw the menu - */ - public function redraw(bool $clear = false) : void - { - if ($clear) { - $this->terminal->clear(); - } - - $this->assertOpen(); - $this->draw(); - } - - private function assertOpen() : void - { - if (!$this->isOpen()) { - throw new MenuNotOpenException; - } - } - - /** - * Draw the menu to STDOUT - */ - protected function draw() : void - { - $frame = new Frame; - - $frame->newLine(2); - - if ($this->style->getBorderTopWidth() > 0) { - $frame->addRows($this->style->getBorderTopRows()); - } - - if ($this->style->getPaddingTopBottom() > 0) { - $frame->addRows($this->style->getPaddingTopBottomRows()); - } - - if ($this->title) { - $frame->addRows($this->drawMenuItem(new StaticItem($this->title))); - $frame->addRows($this->drawMenuItem(new LineBreakItem($this->style->getTitleSeparator()))); - } - - array_map(function ($item, $index) use ($frame) { - $frame->addRows($this->drawMenuItem($item, $index === $this->selectedItem)); - }, $this->items, array_keys($this->items)); - - - if ($this->style->getPaddingTopBottom() > 0) { - $frame->addRows($this->style->getPaddingTopBottomRows()); - } - - if ($this->style->getBorderBottomWidth() > 0) { - $frame->addRows($this->style->getBorderBottomRows()); - } - - $frame->newLine(2); - - $this->terminal->moveCursorToTop(); - foreach ($frame->getRows() as $row) { - if ($row == "\n") { - $this->terminal->clearLine(); - } - $this->terminal->write($row); - } - $this->terminal->clearDown(); - - $this->currentFrame = $frame; - } - - /** - * Draw a menu item - */ - protected function drawMenuItem(MenuItemInterface $item, bool $selected = false) : array - { - $rows = $item->getRows($this->style, $selected); - - if ($item instanceof SplitItem) { - $selected = false; - } - - $invertedColoursSetCode = $selected - ? $this->style->getInvertedColoursSetCode() - : ''; - $invertedColoursUnsetCode = $selected - ? $this->style->getInvertedColoursUnsetCode() - : ''; - - if ($this->style->getBorderLeftWidth() || $this->style->getBorderRightWidth()) { - $borderColour = $this->style->getBorderColourCode(); - } else { - $borderColour = ''; - } - - return array_map(function ($row) use ($invertedColoursSetCode, $invertedColoursUnsetCode, $borderColour) { - return sprintf( - "%s%s%s%s%s%s%s%s%s%s%s%s\n", - str_repeat(' ', $this->style->getMargin()), - $borderColour, - str_repeat(' ', $this->style->getBorderLeftWidth()), - $this->style->getColoursSetCode(), - $invertedColoursSetCode, - str_repeat(' ', $this->style->getPaddingLeftRight()), - $row, - str_repeat(' ', $this->style->getRightHandPadding(mb_strlen(s::stripAnsiEscapeSequence($row)))), - $invertedColoursUnsetCode, - $borderColour, - str_repeat(' ', $this->style->getBorderRightWidth()), - $this->style->getColoursResetCode() - ); - }, $rows); - } - - /** - * @throws InvalidTerminalException - */ - public function open() : void - { - if ($this->isOpen()) { - return; - } - - if (count($this->items) === 0) { - throw new \RuntimeException('Menu must have at least 1 item before it can be opened'); - } - - $this->configureTerminal(); - $this->open = true; - $this->display(); - } - - /** - * Close the menu - * - * @throws InvalidTerminalException - */ - public function close() : void - { - $menu = $this; - - do { - $menu->closeThis(); - $menu = $menu->getParent(); - } while (null !== $menu); - - $this->tearDownTerminal(); - } - - public function closeThis() : void - { - $this->terminal->clean(); - $this->terminal->moveCursorToTop(); - $this->open = false; - } - - /** - * @return MenuItemInterface[] - */ - public function getItems() : array - { - return $this->items; - } - - public function removeItem(MenuItemInterface $item) : void - { - $key = array_search($item, $this->items, true); - - if (false === $key) { - throw new \InvalidArgumentException('Item does not exist in menu'); - } - - unset($this->items[$key]); - $this->items = array_values($this->items); - - if ($this->selectedItem === $key) { - $this->selectedItem = null; - $this->selectFirstItem(); - } - } - - public function getStyle() : MenuStyle - { - return $this->style; - } - - public function setStyle(MenuStyle $style) : void - { - $this->style = $style; - } - - public function setItemStyle(ItemStyle $style, string $styleClass) : void - { - $this->itemStyleLocator->setStyle($style, $styleClass); - } - - public function getItemStyle(string $styleClass) : ItemStyle - { - return $this->itemStyleLocator->getStyle($styleClass); - } - - public function getItemStyleForItem(MenuItemInterface $item) : ItemStyle - { - return $this->itemStyleLocator->getStyleForMenuItem($item); - } - - public function getStyleLocator() : Locator - { - return $this->itemStyleLocator; - } - - public function importStyles(CliMenu $menu) : void - { - if (!$this->style->hasChangedFromDefaults()) { - $this->style = $menu->style; - } - - $this->itemStyleLocator->importFrom($menu->itemStyleLocator); - } - - public function getCurrentFrame() : Frame - { - return $this->currentFrame; - } - - public function flash(string $text, MenuStyle $style = null) : Flash - { - $this->guardSingleLine($text); - - $style = $style ?? (new MenuStyle($this->terminal)) - ->setBg('yellow') - ->setFg('red'); - - return new Flash($this, $style, $this->terminal, $text); - } - - public function confirm(string $text, MenuStyle $style = null) : Confirm - { - $this->guardSingleLine($text); - - $style = $style ?? (new MenuStyle($this->terminal)) - ->setBg('yellow') - ->setFg('red'); - - return new Confirm($this, $style, $this->terminal, $text); - } - - public function cancellableConfirm(string $text, MenuStyle $style = null) : CancellableConfirm - { - $this->guardSingleLine($text); - - $style = $style ?? (new MenuStyle($this->terminal)) - ->setBg('yellow') - ->setFg('red'); - - return new CancellableConfirm($this, $style, $this->terminal, $text); - } - - public function askNumber(MenuStyle $style = null) : Number - { - $this->assertOpen(); - - $style = $style ?? (new MenuStyle($this->terminal)) - ->setBg('yellow') - ->setFg('red'); - - return new Number(new InputIO($this, $this->terminal), $style); - } - - public function askText(MenuStyle $style = null) : Text - { - $this->assertOpen(); - - $style = $style ?? (new MenuStyle($this->terminal)) - ->setBg('yellow') - ->setFg('red'); - - return new Text(new InputIO($this, $this->terminal), $style); - } - - public function askPassword(MenuStyle $style = null) : Password - { - $this->assertOpen(); - - $style = $style ?? (new MenuStyle($this->terminal)) - ->setBg('yellow') - ->setFg('red'); - - return new Password(new InputIO($this, $this->terminal), $style); - } - - private function guardSingleLine(string $text) : void - { - if (strpos($text, "\n") !== false) { - throw new \InvalidArgumentException; - } - } - - public function propagateStyles() : void - { - collect($this->items) - ->filter(function (int $k, MenuItemInterface $item) { - return $this->itemStyleLocator->hasStyleForMenuItem($item); - }) - ->filter(function (int $k, MenuItemInterface $item) { - return !$item->getStyle()->hasChangedFromDefaults(); - }) - ->each(function (int $k, $item) { - $item->setStyle(clone $this->getItemStyleForItem($item)); - }); - - - collect($this->items) - ->filter(function (int $k, MenuItemInterface $item) { - return $item instanceof PropagatesStyles; - }) - ->each(function (int $k, $item) { - $item->propagateStyles($this); - }); - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/CancellableConfirm.php b/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/CancellableConfirm.php deleted file mode 100644 index f60293f..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/CancellableConfirm.php +++ /dev/null @@ -1,114 +0,0 @@ - - */ -class CancellableConfirm extends Dialogue -{ - /** - * @var bool - */ - private $confirm = true; - - /** - * Display confirmation with a button with the given text - */ - public function display(string $confirmText = 'OK', string $cancelText = 'Cancel') : bool - { - $this->drawDialog($confirmText, $cancelText); - - $reader = new NonCanonicalReader($this->terminal); - - while ($char = $reader->readCharacter()) { - if ($char->isControl() && $char->getControl() === InputCharacter::ENTER) { - $this->parentMenu->redraw(); - return $this->confirm; - } elseif ($char->isControl() && $char->getControl() === InputCharacter::TAB || - ($char->isControl() && $char->getControl() === InputCharacter::RIGHT && $this->confirm) || - ($char->isControl() && $char->getControl() === InputCharacter::LEFT && !$this->confirm) - ) { - $this->confirm = !$this->confirm; - $this->drawDialog($confirmText, $cancelText); - } - } - - return true; - } - - private function drawDialog(string $confirmText = 'OK', string $cancelText = 'Cancel'): void - { - $this->assertMenuOpen(); - - $this->terminal->moveCursorToRow($this->y); - - $promptWidth = mb_strlen($this->text) + 4; - - $buttonLength = mb_strlen($confirmText) + 6; - $buttonLength += mb_strlen($cancelText) + 7; - - $confirmButton = sprintf( - '%s%s < %s > %s%s', - $this->style->getOptionCode($this->confirm ? 'bold' : 'dim'), - $this->style->getInvertedColoursSetCode(), - $confirmText, - $this->style->getInvertedColoursUnsetCode(), - $this->style->getOptionCode($this->confirm ? 'bold' : 'dim', false) - ); - - $cancelButton = sprintf( - '%s%s < %s > %s%s', - $this->style->getOptionCode($this->confirm ? 'dim' : 'bold'), - $this->style->getInvertedColoursSetCode(), - $cancelText, - $this->style->getInvertedColoursUnsetCode(), - $this->style->getOptionCode($this->confirm ? 'dim' : 'bold', false) - ); - - $buttonRow = $confirmButton . " " . $cancelButton; - - if ($promptWidth < $buttonLength) { - $pad = ($buttonLength - $promptWidth) / 2; - $this->text = sprintf( - '%s%s%s', - str_repeat(' ', intval(round($pad, 0, 2) + $this->style->getPaddingLeftRight())), - $this->text, - str_repeat(' ', intval(round($pad, 0, 1) + $this->style->getPaddingLeftRight())) - ); - $promptWidth = mb_strlen($this->text) + 4; - } - - $leftFill = (int) (($promptWidth / 2) - ($buttonLength / 2)); - - $this->emptyRow(); - - $this->write(sprintf( - "%s%s%s%s%s\n", - $this->style->getColoursSetCode(), - str_repeat(' ', $this->style->getPaddingLeftRight()), - $this->text, - str_repeat(' ', $this->style->getPaddingLeftRight()), - $this->style->getColoursResetCode() - )); - - $this->emptyRow(); - - $this->write(sprintf( - "%s%s%s%s%s\n", - $this->style->getColoursSetCode(), - str_repeat(' ', $leftFill), - $buttonRow, - str_repeat(' ', (int) ceil($promptWidth - $leftFill - $buttonLength)), - $this->style->getColoursResetCode() - )); - - $this->emptyRow(); - - $this->terminal->moveCursorToTop(); - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Confirm.php b/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Confirm.php deleted file mode 100644 index b95c23b..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Confirm.php +++ /dev/null @@ -1,73 +0,0 @@ - - */ -class Confirm extends Dialogue -{ - - /** - * Display confirmation with a button with the given text - */ - public function display(string $confirmText = 'OK') : void - { - $this->assertMenuOpen(); - - $this->terminal->moveCursorToRow($this->y); - - $promptWidth = mb_strlen($this->text) + 4; - - $this->emptyRow(); - - $this->write(sprintf( - "%s%s%s%s%s\n", - $this->style->getColoursSetCode(), - str_repeat(' ', $this->style->getPaddingLeftRight()), - $this->text, - str_repeat(' ', $this->style->getPaddingLeftRight()), - $this->style->getColoursResetCode() - )); - - $this->emptyRow(); - - $confirmText = sprintf(' < %s > ', $confirmText); - $leftFill = (int) (($promptWidth / 2) - (mb_strlen($confirmText) / 2)); - - $this->write(sprintf( - "%s%s%s%s%s%s%s\n", - $this->style->getColoursSetCode(), - str_repeat(' ', $leftFill), - $this->style->getInvertedColoursSetCode(), - $confirmText, - $this->style->getInvertedColoursUnsetCode(), - str_repeat(' ', (int) ceil($promptWidth - $leftFill - mb_strlen($confirmText))), - $this->style->getColoursResetCode() - )); - - $this->write(sprintf( - "%s%s%s%s%s\n", - $this->style->getColoursSetCode(), - str_repeat(' ', $this->style->getPaddingLeftRight()), - str_repeat(' ', mb_strlen($this->text)), - str_repeat(' ', $this->style->getPaddingLeftRight()), - $this->style->getColoursResetCode() - )); - - $this->terminal->moveCursorToTop(); - - $reader = new NonCanonicalReader($this->terminal); - - while ($char = $reader->readCharacter()) { - if ($char->isControl() && $char->getControl() === InputCharacter::ENTER) { - $this->parentMenu->redraw(); - return; - } - } - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Dialogue.php b/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Dialogue.php deleted file mode 100644 index b4c0eab..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Dialogue.php +++ /dev/null @@ -1,121 +0,0 @@ - - */ -abstract class Dialogue -{ - /** - * @var MenuStyle - */ - protected $style; - - /** - * @var CliMenu - */ - protected $parentMenu; - - /** - * @var Terminal - */ - protected $terminal; - - /** - * @var string $text - */ - protected $text; - - /** - * @var bool $cancellable - */ - protected $cancellable; - - /** - * @var int - */ - protected $x; - - /** - * @var int - */ - protected $y; - - public function __construct( - CliMenu $parentMenu, - MenuStyle $menuStyle, - Terminal $terminal, - string $text - ) { - $this->style = $menuStyle; - $this->terminal = $terminal; - $this->text = $text; - $this->parentMenu = $parentMenu; - - $this->calculateCoordinates(); - } - - /** - * @throws MenuNotOpenException - */ - protected function assertMenuOpen() : void - { - if (!$this->parentMenu->isOpen()) { - throw new MenuNotOpenException; - } - } - - /** - * Calculate the co-ordinates to write the messages - */ - protected function calculateCoordinates() : void - { - //y - $textLines = count(explode("\n", $this->text)) + 2; - $this->y = (int) (ceil($this->parentMenu->getCurrentFrame()->count() / 2) - ceil($textLines / 2) + 1); - - //x - $parentStyle = $this->parentMenu->getStyle(); - $dialogueHalfLength = (int) ((mb_strlen($this->text) + ($this->style->getPaddingLeftRight() * 2)) / 2); - $widthHalfLength = (int) ceil($parentStyle->getWidth() / 2 + $parentStyle->getMargin()); - $this->x = $widthHalfLength - $dialogueHalfLength; - } - - /** - * Write an empty row - */ - protected function emptyRow() : void - { - $this->write( - sprintf( - "%s%s%s%s%s\n", - $this->style->getColoursSetCode(), - str_repeat(' ', $this->style->getPaddingLeftRight()), - str_repeat(' ', mb_strlen($this->text)), - str_repeat(' ', $this->style->getPaddingLeftRight()), - $this->style->getColoursResetCode() - ) - ); - } - - /** - * Write some text at a particular column - */ - protected function write(string $text, int $column = null) : void - { - $this->terminal->moveCursorToColumn($column ?: $this->x); - $this->terminal->write($text); - } - - public function getStyle() : MenuStyle - { - return $this->style; - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Flash.php b/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Flash.php deleted file mode 100644 index ed3ceac..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Dialogue/Flash.php +++ /dev/null @@ -1,43 +0,0 @@ - - */ -class Flash extends Dialogue -{ - /** - * Flash a message on top of the menu which - * disappears on any keystroke. - */ - public function display() : void - { - $this->assertMenuOpen(); - - $this->terminal->moveCursorToRow($this->y); - - $this->emptyRow(); - - $this->write(sprintf( - "%s%s%s%s%s\n", - $this->style->getColoursSetCode(), - str_repeat(' ', $this->style->getPaddingLeftRight()), - $this->text, - str_repeat(' ', $this->style->getPaddingLeftRight()), - $this->style->getColoursResetCode() - )); - - $this->emptyRow(); - - $this->terminal->moveCursorToTop(); - - $reader = new NonCanonicalReader($this->terminal); - $reader->readCharacter(); - - $this->parentMenu->redraw(); - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Exception/CannotShrinkMenuException.php b/src/ncc/ThirdParty/php-school/cli-menu/Exception/CannotShrinkMenuException.php deleted file mode 100644 index 8528ac5..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Exception/CannotShrinkMenuException.php +++ /dev/null @@ -1,21 +0,0 @@ - - */ -class InvalidShortcutException extends \RuntimeException -{ - public static function fromShortcut(string $shortcut) : self - { - return new self(sprintf('Shortcut key must be only one character. Got: "%s"', $shortcut)); - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Exception/InvalidTerminalException.php b/src/ncc/ThirdParty/php-school/cli-menu/Exception/InvalidTerminalException.php deleted file mode 100644 index a5b2e4f..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Exception/InvalidTerminalException.php +++ /dev/null @@ -1,12 +0,0 @@ - - */ -class InvalidTerminalException extends \Exception -{ - -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Exception/MenuNotOpenException.php b/src/ncc/ThirdParty/php-school/cli-menu/Exception/MenuNotOpenException.php deleted file mode 100644 index 321ad2a..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Exception/MenuNotOpenException.php +++ /dev/null @@ -1,12 +0,0 @@ - - */ -class MenuNotOpenException extends \RuntimeException -{ - -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Frame.php b/src/ncc/ThirdParty/php-school/cli-menu/Frame.php deleted file mode 100644 index da403a0..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Frame.php +++ /dev/null @@ -1,47 +0,0 @@ - - */ -class Frame implements \Countable -{ - /** - * @var array - */ - private $rows = []; - - public function newLine(int $count = 1) : void - { - foreach (range(1, $count) as $i) { - $this->rows[] = "\n"; - } - } - - public function addRows(array $rows = []) : void - { - foreach ($rows as $row) { - $this->rows[] = $row; - } - } - - public function addRow(string $row) : void - { - $this->rows[] = $row; - } - - public function count() : int - { - return count($this->rows); - } - - public function getRows() : array - { - return $this->rows; - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Input/Input.php b/src/ncc/ThirdParty/php-school/cli-menu/Input/Input.php deleted file mode 100644 index 236fdf7..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Input/Input.php +++ /dev/null @@ -1,32 +0,0 @@ - - */ -interface Input -{ - public function ask() : InputResult; - - public function validate(string $input) : bool; - - public function setPromptText(string $promptText) : Input; - - public function getPromptText() : string; - - public function setValidationFailedText(string $validationFailedText) : Input; - - public function getValidationFailedText() : string; - - public function setPlaceholderText(string $placeholderText) : Input; - - public function getPlaceholderText() : string; - - public function filter(string $value) : string; - - public function getStyle() : MenuStyle; -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Input/InputIO.php b/src/ncc/ThirdParty/php-school/cli-menu/Input/InputIO.php deleted file mode 100644 index 5208f23..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Input/InputIO.php +++ /dev/null @@ -1,256 +0,0 @@ - - */ -class InputIO -{ - /** - * @var CliMenu - */ - private $parentMenu; - - /** - * @var Terminal - */ - private $terminal; - - /** - * @var callable[][] - */ - private $callbacks = []; - - public function __construct(CliMenu $parentMenu, Terminal $terminal) - { - $this->terminal = $terminal; - $this->parentMenu = $parentMenu; - } - - public function collect(Input $input) : InputResult - { - $this->drawInput($input, $input->getPlaceholderText()); - - $inputValue = $input->getPlaceholderText(); - $havePlaceHolderValue = !empty($inputValue); - - $originalValue = $inputValue; - - $reader = new NonCanonicalReader($this->terminal); - - while ($char = $reader->readCharacter()) { - if ($char->isNotControl()) { - if ($havePlaceHolderValue) { - $inputValue = $char->get(); - $havePlaceHolderValue = false; - } else { - $inputValue .= $char->get(); - } - - $this->parentMenu->redraw(); - $this->drawInput($input, $inputValue); - continue; - } - - if ($char->isHandledControl()) { - switch ($char->getControl()) { - case InputCharacter::ESC: - $this->parentMenu->redraw(); - return new InputResult($originalValue); - case InputCharacter::ENTER: - if ($input->validate($inputValue)) { - $this->parentMenu->redraw(); - return new InputResult($inputValue); - } else { - $this->drawInputWithError($input, $inputValue); - continue 2; - } - - case InputCharacter::BACKSPACE: - $inputValue = substr($inputValue, 0, -1); - $this->parentMenu->redraw(); - $this->drawInput($input, $inputValue); - continue 2; - } - - if (!empty($this->callbacks[$char->getControl()])) { - foreach ($this->callbacks[$char->getControl()] as $callback) { - $inputValue = $callback($inputValue); - $this->drawInput($input, $inputValue); - } - } - } - } - } - - public function registerControlCallback(string $control, callable $callback) : void - { - if (!isset($this->callbacks[$control])) { - $this->callbacks[$control] = []; - } - - $this->callbacks[$control][] = $callback; - } - - private function getInputWidth(array $lines) : int - { - return max( - array_map( - function (string $line) { - return mb_strlen($line); - }, - $lines - ) - ) ? : 0; - } - - private function calculateYPosition() : int - { - $lines = 5; //1. empty 2. prompt text 3. empty 4. input 5. empty - - return (int) (ceil($this->parentMenu->getCurrentFrame()->count() / 2) - ceil($lines /2) + 1); - } - - private function calculateYPositionWithError() : int - { - $lines = 7; //1. empty 2. prompt text 3. empty 4. input 5. empty 6. error 7. empty - - return (int) (ceil($this->parentMenu->getCurrentFrame()->count() / 2) - ceil($lines /2) + 1); - } - - private function calculateXPosition(Input $input, string $userInput) : int - { - $width = $this->getInputWidth( - [ - $input->getPromptText(), - $input->getValidationFailedText(), - $userInput - ] - ); - - $parentStyle = $this->parentMenu->getStyle(); - $halfWidth = ($width + ($input->getStyle()->getPaddingLeftRight() * 2)) / 2; - $parentHalfWidth = ceil($parentStyle->getWidth() / 2 + $parentStyle->getMargin()); - - return (int) ($parentHalfWidth - $halfWidth); - } - - private function drawLine(Input $input, string $userInput, string $text) : void - { - $this->terminal->moveCursorToColumn($this->calculateXPosition($input, $userInput)); - - $line = sprintf( - "%s%s%s%s%s\n", - $input->getStyle()->getColoursSetCode(), - str_repeat(' ', $input->getStyle()->getPaddingLeftRight()), - $text, - str_repeat(' ', $input->getStyle()->getPaddingLeftRight()), - $input->getStyle()->getColoursResetCode() - ); - - $this->terminal->write($line); - } - - private function drawCenteredLine(Input $input, string $userInput, string $text) : void - { - $width = $this->getInputWidth( - [ - $input->getPromptText(), - $input->getValidationFailedText(), - $userInput - ] - ); - - $textLength = mb_strlen(StringUtil::stripAnsiEscapeSequence($text)); - $leftFill = (int) (($width / 2) - ($textLength / 2)); - $rightFill = (int) ceil($width - $leftFill - $textLength); - - $this->drawLine( - $input, - $userInput, - sprintf( - '%s%s%s', - str_repeat(' ', $leftFill), - $text, - str_repeat(' ', $rightFill) - ) - ); - } - - private function drawEmptyLine(Input $input, string $userInput) : void - { - $width = $this->getInputWidth( - [ - $input->getPromptText(), - $input->getValidationFailedText(), - $userInput - ] - ); - - $this->drawLine( - $input, - $userInput, - str_repeat(' ', $width) - ); - } - - private function drawInput(Input $input, string $userInput) : void - { - $this->terminal->moveCursorToRow($this->calculateYPosition()); - - $this->drawEmptyLine($input, $userInput); - $this->drawTitle($input, $userInput); - $this->drawEmptyLine($input, $userInput); - $this->drawInputField($input, $input->filter($userInput)); - $this->drawEmptyLine($input, $userInput); - } - - private function drawInputWithError(Input $input, string $userInput) : void - { - $this->terminal->moveCursorToRow($this->calculateYPositionWithError()); - - $this->drawEmptyLine($input, $userInput); - $this->drawTitle($input, $userInput); - $this->drawEmptyLine($input, $userInput); - $this->drawInputField($input, $input->filter($userInput)); - $this->drawEmptyLine($input, $userInput); - $this->drawCenteredLine( - $input, - $userInput, - $input->getValidationFailedText() - ); - $this->drawEmptyLine($input, $userInput); - } - - private function drawTitle(Input $input, string $userInput) : void - { - - $this->drawCenteredLine( - $input, - $userInput, - $input->getPromptText() - ); - } - - private function drawInputField(Input $input, string $userInput) : void - { - $this->drawCenteredLine( - $input, - $userInput, - sprintf( - '%s%s%s', - $input->getStyle()->getInvertedColoursSetCode(), - $userInput, - $input->getStyle()->getInvertedColoursUnsetCode() - ) - ); - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Input/InputResult.php b/src/ncc/ThirdParty/php-school/cli-menu/Input/InputResult.php deleted file mode 100644 index 061a1fb..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Input/InputResult.php +++ /dev/null @@ -1,25 +0,0 @@ - - */ -class InputResult -{ - /** - * @var string - */ - private $input; - - public function __construct(string $input) - { - $this->input = $input; - } - - public function fetch() : string - { - return $this->input; - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Input/Number.php b/src/ncc/ThirdParty/php-school/cli-menu/Input/Number.php deleted file mode 100644 index d20e044..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Input/Number.php +++ /dev/null @@ -1,130 +0,0 @@ - - */ -class Number implements Input -{ - /** - * @var InputIO - */ - private $inputIO; - - /** - * @var string - */ - private $promptText = 'Enter a number:'; - - /** - * @var string - */ - private $validationFailedText = 'Not a valid number, try again'; - - /** - * @var string - */ - private $placeholderText = ''; - - /** - * @var null|callable - */ - private $validator; - - /** - * @var MenuStyle - */ - private $style; - - public function __construct(InputIO $inputIO, MenuStyle $style) - { - $this->inputIO = $inputIO; - $this->style = $style; - } - - public function setPromptText(string $promptText) : Input - { - $this->promptText = $promptText; - - return $this; - } - - public function getPromptText() : string - { - return $this->promptText; - } - - public function setValidationFailedText(string $validationFailedText) : Input - { - $this->validationFailedText = $validationFailedText; - - return $this; - } - - public function getValidationFailedText() : string - { - return $this->validationFailedText; - } - - public function setPlaceholderText(string $placeholderText) : Input - { - $this->placeholderText = $placeholderText; - - return $this; - } - - public function getPlaceholderText() : string - { - return $this->placeholderText; - } - - public function setValidator(callable $validator) : Input - { - $this->validator = $validator; - - return $this; - } - - public function ask() : InputResult - { - $this->inputIO->registerControlCallback(InputCharacter::UP, function (string $input) { - return $this->validate($input) ? (string) ((int) $input + 1) : $input; - }); - - $this->inputIO->registerControlCallback(InputCharacter::DOWN, function (string $input) { - return $this->validate($input) ? (string) ((int) $input - 1) : $input; - }); - - return $this->inputIO->collect($this); - } - - public function validate(string $input) : bool - { - if ($this->validator) { - $validator = $this->validator; - - if ($validator instanceof \Closure) { - $validator = $validator->bindTo($this); - } - - return $validator($input); - } - - return (bool) preg_match('/^-?\d+$/', $input); - } - - public function filter(string $value) : string - { - return $value; - } - - public function getStyle() : MenuStyle - { - return $this->style; - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Input/Password.php b/src/ncc/ThirdParty/php-school/cli-menu/Input/Password.php deleted file mode 100644 index cb10fb3..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Input/Password.php +++ /dev/null @@ -1,131 +0,0 @@ - - */ -class Password implements Input -{ - /** - * @var InputIO - */ - private $inputIO; - - /** - * @var string - */ - private $promptText = 'Enter password:'; - - /** - * @var string - */ - private $validationFailedText = 'Invalid password, try again'; - - /** - * @var string - */ - private $placeholderText = ''; - - /** - * @var null|callable - */ - private $validator; - - /** - * @var MenuStyle - */ - private $style; - - /** - * @var int - */ - private $passwordLength = 16; - - public function __construct(InputIO $inputIO, MenuStyle $style) - { - $this->inputIO = $inputIO; - $this->style = $style; - } - - public function setPromptText(string $promptText) : Input - { - $this->promptText = $promptText; - - return $this; - } - - public function getPromptText() : string - { - return $this->promptText; - } - - public function setValidationFailedText(string $validationFailedText) : Input - { - $this->validationFailedText = $validationFailedText; - - return $this; - } - - public function getValidationFailedText() : string - { - return $this->validationFailedText; - } - - public function setPlaceholderText(string $placeholderText) : Input - { - $this->placeholderText = $placeholderText; - - return $this; - } - - public function getPlaceholderText() : string - { - return $this->placeholderText; - } - - public function setValidator(callable $validator) : Input - { - $this->validator = $validator; - - return $this; - } - - public function ask() : InputResult - { - return $this->inputIO->collect($this); - } - - public function validate(string $input) : bool - { - if ($this->validator) { - $validator = $this->validator; - - if ($validator instanceof \Closure) { - $validator = $validator->bindTo($this); - } - - return $validator($input); - } - - return mb_strlen($input) >= $this->passwordLength; - } - - public function filter(string $value) : string - { - return str_repeat('*', mb_strlen($value)); - } - - public function getStyle() : MenuStyle - { - return $this->style; - } - - public function setPasswordLength(int $length) : int - { - return $this->passwordLength = $length; - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Input/Text.php b/src/ncc/ThirdParty/php-school/cli-menu/Input/Text.php deleted file mode 100644 index 835f97e..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Input/Text.php +++ /dev/null @@ -1,121 +0,0 @@ - - */ -class Text implements Input -{ - /** - * @var InputIO - */ - private $inputIO; - - /** - * @var string - */ - private $promptText = 'Enter text:'; - - /** - * @var string - */ - private $validationFailedText = 'Invalid, try again'; - - /** - * @var string - */ - private $placeholderText = ''; - - /** - * @var null|callable - */ - private $validator; - - /** - * @var MenuStyle - */ - private $style; - - public function __construct(InputIO $inputIO, MenuStyle $style) - { - $this->inputIO = $inputIO; - $this->style = $style; - } - - public function setPromptText(string $promptText) : Input - { - $this->promptText = $promptText; - - return $this; - } - - public function getPromptText() : string - { - return $this->promptText; - } - - public function setValidationFailedText(string $validationFailedText) : Input - { - $this->validationFailedText = $validationFailedText; - - return $this; - } - - public function getValidationFailedText() : string - { - return $this->validationFailedText; - } - - public function setPlaceholderText(string $placeholderText) : Input - { - $this->placeholderText = $placeholderText; - - return $this; - } - - public function getPlaceholderText() : string - { - return $this->placeholderText; - } - - public function setValidator(callable $validator) : Input - { - $this->validator = $validator; - - return $this; - } - - public function ask() : InputResult - { - return $this->inputIO->collect($this); - } - - public function validate(string $input) : bool - { - if ($this->validator) { - $validator = $this->validator; - - if ($validator instanceof \Closure) { - $validator = $validator->bindTo($this); - } - - return $validator($input); - } - - return !empty($input); - } - - public function filter(string $value) : string - { - return $value; - } - - public function getStyle() : MenuStyle - { - return $this->style; - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/LICENSE b/src/ncc/ThirdParty/php-school/cli-menu/LICENSE deleted file mode 100644 index cbada9b..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015-2016 PHP School - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/AsciiArtItem.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/AsciiArtItem.php deleted file mode 100644 index 9828c0c..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/AsciiArtItem.php +++ /dev/null @@ -1,187 +0,0 @@ - - */ -class AsciiArtItem implements MenuItemInterface -{ - /** - * Possible positions of the ascii art - */ - const POSITION_CENTER = 'center'; - const POSITION_LEFT = 'left'; - const POSITION_RIGHT = 'right'; - - /** - * @var string - */ - private $text; - - /** - * @var string - */ - private $position; - - /** - * @var string - */ - private $alternateText; - - /** - * @var int - */ - private $artLength; - - /** - * @var DefaultStyle - */ - private $style; - - public function __construct(string $text, string $position = self::POSITION_CENTER, string $alt = '') - { - Assertion::inArray($position, [self::POSITION_CENTER, self::POSITION_RIGHT, self::POSITION_LEFT]); - - $this->setText($text); - $this->position = $position; - $this->alternateText = $alt; - - $this->style = new DefaultStyle(); - } - - /** - * The output text for the item - */ - public function getRows(MenuStyle $style, bool $selected = false) : array - { - if ($this->artLength > $style->getContentWidth()) { - $alternate = new StaticItem($this->alternateText); - return $alternate->getRows($style, false); - } - - $padding = $style->getContentWidth() - $this->artLength; - - return array_map(function ($row) use ($padding) { - switch ($this->position) { - case self::POSITION_LEFT: - break; - case self::POSITION_RIGHT: - $row = sprintf('%s%s', str_repeat(' ', $padding), $row); - break; - case self::POSITION_CENTER: - default: - $left = (int) ceil($padding / 2); - $row = sprintf('%s%s', str_repeat(' ', $left), $row); - break; - } - - return $row; - }, explode("\n", $this->text)); - } - - /** - * Can the item be selected - */ - public function canSelect() : bool - { - return false; - } - - /** - * Execute the items callable if required - */ - public function getSelectAction() : ?callable - { - return null; - } - - /** - * Return the raw string of text - */ - public function getText() : string - { - return $this->text; - } - - /** - * Set the raw string of text - */ - public function setText(string $text) : void - { - $this->text = implode("\n", array_map(function (string $line) { - return rtrim($line, ' '); - }, explode("\n", $text))); - - $this->calculateArtLength(); - } - - /** - * Calculate the length of the art - */ - private function calculateArtLength() : void - { - $this->artLength = (int) max(array_map('mb_strlen', explode("\n", $this->text))); - } - - /** - * Return the length of the art - */ - public function getArtLength() : int - { - return $this->artLength; - } - - public function getPosition() : string - { - return $this->position; - } - - public function getAlternateText() : string - { - return $this->alternateText; - } - - /** - * Whether or not the menu item is showing the menustyle extra value - */ - public function showsItemExtra() : bool - { - return false; - } - - /** - * Enable showing item extra - */ - public function showItemExtra() : void - { - //noop - } - - /** - * Disable showing item extra - */ - public function hideItemExtra() : void - { - //noop - } - - /** - * @return DefaultStyle - */ - public function getStyle() : ItemStyle - { - return $this->style; - } - - public function setStyle(DefaultStyle $style) : void - { - $this->style = $style; - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/CheckboxItem.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/CheckboxItem.php deleted file mode 100644 index 5816a18..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/CheckboxItem.php +++ /dev/null @@ -1,172 +0,0 @@ -text = $text; - $this->selectAction = $selectAction; - $this->showItemExtra = $showItemExtra; - $this->disabled = $disabled; - - $this->style = new CheckboxStyle(); - } - - /** - * The output text for the item - */ - public function getRows(MenuStyle $style, bool $selected = false) : array - { - return (new SelectableItemRenderer())->render($style, $this, $selected, $this->disabled); - } - - /** - * Return the raw string of text - */ - public function getText() : string - { - return $this->text; - } - - /** - * Set the raw string of text - */ - public function setText(string $text) : void - { - $this->text = $text; - } - - /** - * Execute the items callable if required - */ - public function getSelectAction() : ?callable - { - return function (CliMenu $cliMenu) { - $this->toggle(); - $cliMenu->redraw(); - - return ($this->selectAction)($cliMenu); - }; - } - - /** - * Can the item be selected - */ - public function canSelect() : bool - { - return !$this->disabled; - } - - /** - * Whether or not we are showing item extra - */ - public function showsItemExtra() : bool - { - return $this->showItemExtra; - } - - /** - * Enable showing item extra - */ - public function showItemExtra() : void - { - $this->showItemExtra = true; - } - - /** - * Disable showing item extra - */ - public function hideItemExtra() : void - { - $this->showItemExtra = false; - } - - /** - * Whether or not the item is checked - */ - public function getChecked() : bool - { - return $this->checked; - } - - /** - * Sets checked state to true - */ - public function setChecked() : void - { - $this->checked = true; - } - - /** - * Sets checked state to false - */ - public function setUnchecked() : void - { - $this->checked = false; - } - - /** - * Toggles checked state - */ - public function toggle() : void - { - $this->checked = !$this->checked; - } - - /** - * @return CheckboxStyle - */ - public function getStyle() : ItemStyle - { - return $this->style; - } - - public function setStyle(CheckboxStyle $style) : void - { - $this->style = $style; - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/LineBreakItem.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/LineBreakItem.php deleted file mode 100644 index 695994e..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/LineBreakItem.php +++ /dev/null @@ -1,126 +0,0 @@ - - */ -class LineBreakItem implements MenuItemInterface -{ - /** - * @var string - */ - private $breakChar; - - /** - * @var int - */ - private $lines; - - /** - * @var DefaultStyle - */ - private $style; - - public function __construct(string $breakChar = ' ', int $lines = 1) - { - $this->breakChar = $breakChar; - $this->lines = $lines; - - $this->style = new DefaultStyle(); - } - - /** - * The output text for the item - */ - public function getRows(MenuStyle $style, bool $selected = false) : array - { - return explode( - "\n", - rtrim(str_repeat(sprintf( - "%s\n", - mb_substr(str_repeat($this->breakChar, $style->getContentWidth()), 0, $style->getContentWidth()) - ), $this->lines)) - ); - } - - /** - * Can the item be selected - */ - public function canSelect() : bool - { - return false; - } - - /** - * Execute the items callable if required - */ - public function getSelectAction() : ?callable - { - return null; - } - - /** - * Return the raw string of text - */ - public function getText() : string - { - return $this->breakChar; - } - - /** - * Set the raw string of text - */ - public function setText(string $text) : void - { - $this->breakChar = $text; - } - - /** - * Whether or not the menu item is showing the menustyle extra value - */ - public function showsItemExtra() : bool - { - return false; - } - - public function getLines() : int - { - return $this->lines; - } - - /** - * Enable showing item extra - */ - public function showItemExtra() : void - { - //noop - } - - /** - * Disable showing item extra - */ - public function hideItemExtra() : void - { - //noop - } - - /** - * @return DefaultStyle - */ - public function getStyle() : ItemStyle - { - return $this->style; - } - - public function setStyle(DefaultStyle $style) : void - { - $this->style = $style; - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/MenuItemInterface.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/MenuItemInterface.php deleted file mode 100644 index d7126d6..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/MenuItemInterface.php +++ /dev/null @@ -1,55 +0,0 @@ - - */ -interface MenuItemInterface -{ - /** - * The output text for the item - */ - public function getRows(MenuStyle $style, bool $selected = false) : array; - - /** - * Return the raw string of text - */ - public function getText() : string; - - /** - * Can the item be selected - */ - public function canSelect() : bool; - - /** - * Execute the items callable if required - */ - public function getSelectAction() : ?callable; - - /** - * Whether or not the menu item is showing the menustyle extra value - */ - public function showsItemExtra() : bool; - - /** - * Enable showing item extra - */ - public function showItemExtra() : void; - - /** - * Disable showing item extra - */ - public function hideItemExtra() : void; - - /** - * Get the items style object. Can and - * should be subclassed to provide bespoke - * behaviour. - */ - public function getStyle() : ItemStyle; -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/MenuMenuItem.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/MenuMenuItem.php deleted file mode 100644 index 039841f..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/MenuMenuItem.php +++ /dev/null @@ -1,157 +0,0 @@ - - */ -class MenuMenuItem implements MenuItemInterface, PropagatesStyles -{ - /** - * @var string - */ - private $text; - - /** - * @var CliMenu - */ - private $subMenu; - - /** - * @var bool - */ - private $showItemExtra = false; - - /** - * @var bool - */ - private $disabled; - - /** - * @var SelectableStyle - */ - private $style; - - public function __construct( - string $text, - CliMenu $subMenu, - bool $disabled = false - ) { - $this->text = $text; - $this->subMenu = $subMenu; - $this->disabled = $disabled; - - $this->style = new SelectableStyle(); - } - - /** - * The output text for the item - */ - public function getRows(MenuStyle $style, bool $selected = false) : array - { - return (new SelectableItemRenderer())->render($style, $this, $selected, $this->disabled); - } - - /** - * Return the raw string of text - */ - public function getText() : string - { - return $this->text; - } - - /** - * Set the raw string of text - */ - public function setText(string $text) : void - { - $this->text = $text; - } - - /** - * Execute the items callable if required - */ - public function getSelectAction() : ?callable - { - return function (CliMenu $menu) { - $this->showSubMenu($menu); - }; - } - - /** - * Returns the sub menu - */ - public function getSubMenu() : CliMenu - { - return $this->subMenu; - } - - /** - * Display the sub menu - */ - public function showSubMenu(CliMenu $parentMenu) : void - { - $parentMenu->closeThis(); - $this->subMenu->open(); - } - - /** - * Can the item be selected - */ - public function canSelect() : bool - { - return !$this->disabled; - } - - /** - * Enable showing item extra - */ - public function showItemExtra() : void - { - $this->showItemExtra = true; - } - - /** - * Whether or not we are showing item extra - */ - public function showsItemExtra() : bool - { - return $this->showItemExtra; - } - - /** - * Disable showing item extra - */ - public function hideItemExtra() : void - { - $this->showItemExtra = false; - } - - /** - * @return SelectableStyle - */ - public function getStyle() : ItemStyle - { - return $this->style; - } - - public function setStyle(SelectableStyle $style) : void - { - $this->style = $style; - } - - /** - * @inheritDoc - */ - public function propagateStyles(CliMenu $parent): void - { - $this->getSubMenu()->importStyles($parent); - $this->getSubMenu()->propagateStyles(); - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/PropagatesStyles.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/PropagatesStyles.php deleted file mode 100644 index 1c73988..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/PropagatesStyles.php +++ /dev/null @@ -1,16 +0,0 @@ -text = $text; - $this->selectAction = $selectAction; - $this->showItemExtra = $showItemExtra; - $this->disabled = $disabled; - - $this->style = new RadioStyle(); - } - - /** - * The output text for the item - */ - public function getRows(MenuStyle $style, bool $selected = false) : array - { - return (new SelectableItemRenderer())->render($style, $this, $selected, $this->disabled); - } - - /** - * Return the raw string of text - */ - public function getText() : string - { - return $this->text; - } - - /** - * Set the raw string of text - */ - public function setText(string $text) : void - { - $this->text = $text; - } - - /** - * Execute the items callable if required - */ - public function getSelectAction() : ?callable - { - return function (CliMenu $cliMenu) { - $parentItem = $cliMenu->getItemByIndex($cliMenu->getSelectedItemIndex()); - - $siblings = $parentItem instanceof SplitItem - ? $parentItem->getItems() - : $cliMenu->getItems(); - - $filtered = array_filter( - $siblings, - function (MenuItemInterface $item) { - return $item instanceof self; - } - ); - - array_walk( - $filtered, - function (RadioItem $item) { - $item->setUnchecked(); - } - ); - - $this->setChecked(); - $cliMenu->redraw(); - - return ($this->selectAction)($cliMenu); - }; - } - - /** - * Can the item be selected - */ - public function canSelect() : bool - { - return !$this->disabled; - } - - /** - * Whether or not we are showing item extra - */ - public function showsItemExtra() : bool - { - return $this->showItemExtra; - } - - /** - * Enable showing item extra - */ - public function showItemExtra() : void - { - $this->showItemExtra = true; - } - - /** - * Disable showing item extra - */ - public function hideItemExtra() : void - { - $this->showItemExtra = false; - } - - /** - * Whether or not the item is checked - */ - public function getChecked() : bool - { - return $this->checked; - } - - /** - * Sets checked state to true - */ - public function setChecked() : void - { - $this->checked = true; - } - - /** - * Sets checked state to false - */ - public function setUnchecked() : void - { - $this->checked = false; - } - - /** - * Toggles checked state - */ - public function toggle() : void - { - $this->checked = !$this->checked; - } - - /** - * @return RadioStyle - */ - public function getStyle() : ItemStyle - { - return $this->style; - } - - public function setStyle(RadioStyle $style) : void - { - $this->style = $style; - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SelectableItem.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SelectableItem.php deleted file mode 100644 index c2f2663..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SelectableItem.php +++ /dev/null @@ -1,132 +0,0 @@ - - */ -class SelectableItem implements MenuItemInterface -{ - /** - * @var string - */ - private $text; - - /** - * @var callable - */ - private $selectAction; - - /** - * @var bool - */ - private $showItemExtra; - - /** - * @var bool - */ - private $disabled; - - /** - * @var SelectableStyle - */ - private $style; - - public function __construct( - string $text, - callable $selectAction, - bool $showItemExtra = false, - bool $disabled = false - ) { - $this->text = $text; - $this->selectAction = $selectAction; - $this->showItemExtra = $showItemExtra; - $this->disabled = $disabled; - - $this->style = new SelectableStyle(); - } - - /** - * The output text for the item - */ - public function getRows(MenuStyle $style, bool $selected = false) : array - { - return (new SelectableItemRenderer())->render($style, $this, $selected, $this->disabled); - } - - /** - * Return the raw string of text - */ - public function getText() : string - { - return $this->text; - } - - /** - * Set the raw string of text - */ - public function setText(string $text) : void - { - $this->text = $text; - } - - /** - * Execute the items callable if required - */ - public function getSelectAction() : ?callable - { - return $this->selectAction; - } - - /** - * Can the item be selected - */ - public function canSelect() : bool - { - return !$this->disabled; - } - - /** - * Whether or not we are showing item extra - */ - public function showsItemExtra() : bool - { - return $this->showItemExtra; - } - - /** - * Enable showing item extra - */ - public function showItemExtra() : void - { - $this->showItemExtra = true; - } - - /** - * Disable showing item extra - */ - public function hideItemExtra() : void - { - $this->showItemExtra = false; - } - - /** - * @return SelectableStyle - */ - public function getStyle() : ItemStyle - { - return $this->style; - } - - public function setStyle(SelectableStyle $style) : void - { - $this->style = $style; - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SelectableItemRenderer.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SelectableItemRenderer.php deleted file mode 100644 index 9ccc764..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SelectableItemRenderer.php +++ /dev/null @@ -1,66 +0,0 @@ -getStyle(); - $marker = $itemStyle->getMarker($item, $selected); - $availableTextWidth = $this->getAvailableTextWidth($menuStyle, $itemStyle); - - return mapWithKeys( - $this->wrapAndIndentText($marker, $item->getText(), $availableTextWidth), - function (int $key, string $row) use ($menuStyle, $item, $availableTextWidth, $disabled) { - $text = $disabled ? $menuStyle->getDisabledItemText($row) : $row; - - return $key === 0 && $item->showsItemExtra() - ? $this->lineWithExtra($text, $availableTextWidth, $item->getStyle()) - : $text; - } - ); - } - - public function wrapAndIndentText(string $marker, string $text, int $availableWidth) : array - { - return explode( - "\n", - s::wordwrap( - "{$marker}{$text}", - $availableWidth, - sprintf("\n%s", $this->emptyString(mb_strlen($marker))) - ) - ); - } - - public function lineWithExtra(string $text, int $availableWidth, ItemStyle $itemStyle) : string - { - return sprintf( - '%s%s %s', - $text, - $this->emptyString($availableWidth - s::length($text)), - $itemStyle->getItemExtra() - ); - } - - public function emptyString(int $numCharacters) : string - { - return str_repeat(' ', $numCharacters); - } - - public function getAvailableTextWidth(MenuStyle $menuStyle, ItemStyle $itemStyle) : int - { - return $itemStyle->getDisplaysExtra() - ? $menuStyle->getContentWidth() - (mb_strlen($itemStyle->getItemExtra()) + 2) - : $menuStyle->getContentWidth(); - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SplitItem.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SplitItem.php deleted file mode 100644 index 5f66695..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/SplitItem.php +++ /dev/null @@ -1,388 +0,0 @@ - - */ -class SplitItem implements MenuItemInterface, PropagatesStyles -{ - /** - * @var array - */ - private $items = []; - - /** - * @var int|null - */ - private $selectedItemIndex; - - /** - * @var bool - */ - private $canBeSelected = true; - - /** - * @var int - */ - private $gutter = 2; - - /** - * @var DefaultStyle - */ - private $style; - - /** - * @var array - */ - private static $blacklistedItems = [ - \ncc\PhpSchool\CliMenu\MenuItem\AsciiArtItem::class, - \ncc\PhpSchool\CliMenu\MenuItem\LineBreakItem::class, - \ncc\PhpSchool\CliMenu\MenuItem\SplitItem::class, - ]; - - public function __construct(array $items = []) - { - $this->addItems($items); - $this->setDefaultSelectedItem(); - - $this->style = new DefaultStyle(); - } - - public function getGutter() : int - { - return $this->gutter; - } - - public function setGutter(int $gutter) : void - { - Assertion::greaterOrEqualThan($gutter, 0); - $this->gutter = $gutter; - } - - public function addItem(MenuItemInterface $item) : self - { - foreach (self::$blacklistedItems as $bl) { - if ($item instanceof $bl) { - throw new \InvalidArgumentException("Cannot add a $bl to a SplitItem"); - } - } - $this->items[] = $item; - $this->setDefaultSelectedItem(); - return $this; - } - - public function addItems(array $items) : self - { - foreach ($items as $item) { - $this->addItem($item); - } - - return $this; - } - - public function setItems(array $items) : self - { - $this->items = []; - $this->addItems($items); - return $this; - } - - /** - * Select default item - */ - private function setDefaultSelectedItem() : void - { - foreach ($this->items as $index => $item) { - if ($item->canSelect()) { - $this->canBeSelected = true; - $this->selectedItemIndex = $index; - return; - } - } - - $this->canBeSelected = false; - $this->selectedItemIndex = null; - } - - /** - * The output text for the item - */ - public function getRows(MenuStyle $style, bool $selected = false) : array - { - $numberOfItems = count($this->items); - - if ($numberOfItems === 0) { - throw new \RuntimeException(sprintf('There should be at least one item added to: %s', __CLASS__)); - } - - if (!$selected) { - $this->setDefaultSelectedItem(); - } - - $largestItemExtra = $this->calculateItemExtra(); - - $length = $largestItemExtra > 0 - ? floor($style->getContentWidth() / $numberOfItems) - ($largestItemExtra + 2) - : floor($style->getContentWidth() / $numberOfItems); - - $length -= $this->gutter; - $length = (int) $length; - - $missingLength = $style->getContentWidth() % $numberOfItems; - - return $this->buildRows( - mapWithKeys($this->items, function (int $index, MenuItemInterface $item) use ($selected, $length, $style) { - $isSelected = $selected && $index === $this->selectedItemIndex; - - $marker = $item->getStyle()->getMarker($item, $isSelected); - - $itemExtra = ''; - if ($item->getStyle()->getDisplaysExtra()) { - $itemExtraVal = $item->getStyle()->getItemExtra(); - $itemExtra = $item->showsItemExtra() - ? sprintf(' %s', $itemExtraVal) - : sprintf(' %s', str_repeat(' ', mb_strlen($itemExtraVal))); - } - - return $this->buildCell( - explode( - "\n", - StringUtil::wordwrap( - sprintf('%s%s', $marker, $item->getText()), - $length, - sprintf("\n%s", str_repeat(' ', mb_strlen($marker))) - ) - ), - $length, - $style, - $isSelected, - $itemExtra - ); - }), - $missingLength, - $length, - $largestItemExtra - ); - } - - private function buildRows(array $cells, int $missingLength, int $length, int $largestItemExtra) : array - { - $extraPadLength = $largestItemExtra > 0 ? 2 + $largestItemExtra : 0; - - return array_map( - function ($i) use ($cells, $length, $missingLength, $extraPadLength) { - return $this->buildRow($cells, $i, $length, $missingLength, $extraPadLength); - }, - range(0, max(array_map('count', $cells)) - 1) - ); - } - - private function buildRow(array $cells, int $index, int $length, int $missingLength, int $extraPadLength) : string - { - return sprintf( - '%s%s', - implode( - '', - array_map( - function ($cell) use ($index, $length, $extraPadLength) { - return $cell[$index] ?? str_repeat(' ', $length + $this->gutter + $extraPadLength); - }, - $cells - ) - ), - str_repeat(' ', $missingLength) - ); - } - - private function buildCell( - array $content, - int $length, - MenuStyle $style, - bool $isSelected, - string $itemExtra - ) : array { - return array_map(function ($row, $index) use ($length, $style, $isSelected, $itemExtra) { - $invertedColoursSetCode = $isSelected - ? $style->getInvertedColoursSetCode() - : ''; - $invertedColoursUnsetCode = $isSelected - ? $style->getInvertedColoursUnsetCode() - : ''; - - return sprintf( - '%s%s%s%s%s%s', - $invertedColoursSetCode, - $row, - str_repeat(' ', $length - mb_strlen($row)), - $index === 0 ? $itemExtra : str_repeat(' ', mb_strlen($itemExtra)), - $invertedColoursUnsetCode, - str_repeat(' ', $this->gutter) - ); - }, $content, array_keys($content)); - } - - /** - * Is there an item with this index and can it be - * selected? - */ - public function canSelectIndex(int $index) : bool - { - return isset($this->items[$index]) && $this->items[$index]->canSelect(); - } - - /** - * Set the item index which should be selected. If the item does - * not exist then throw an exception. - */ - public function setSelectedItemIndex(int $index) : void - { - if (!isset($this->items[$index])) { - throw new \InvalidArgumentException(sprintf('Index: "%s" does not exist', $index)); - } - - $this->selectedItemIndex = $index; - } - - /** - * Get the currently select item index. - * May be null in case of no selectable item. - */ - public function getSelectedItemIndex() : ?int - { - return $this->selectedItemIndex; - } - - /** - * Get the currently selected item - if no items are selectable - * then throw an exception. - */ - public function getSelectedItem() : MenuItemInterface - { - if (null === $this->selectedItemIndex) { - throw new \RuntimeException('No item is selected'); - } - - return $this->items[$this->selectedItemIndex]; - } - - public function getItems() : array - { - return $this->items; - } - - /** - * Can the item be selected - * In this case, it indicates if at least 1 item inside the SplitItem can be selected - */ - public function canSelect() : bool - { - return $this->canBeSelected; - } - - /** - * Execute the items callable if required - */ - public function getSelectAction() : ?callable - { - return null; - } - - /** - * Whether or not the menu item is showing the menustyle extra value - */ - public function showsItemExtra() : bool - { - return false; - } - - /** - * Enable showing item extra - */ - public function showItemExtra() : void - { - //noop - } - - /** - * Disable showing item extra - */ - public function hideItemExtra() : void - { - //noop - } - - /** - * Nothing to return with SplitItem - */ - public function getText() : string - { - throw new \BadMethodCallException(sprintf('Not supported on: %s', __CLASS__)); - } - - /** - * Finds largest itemExtra value in items - */ - private function calculateItemExtra() : int - { - return max(array_map( - function (MenuItemInterface $item) { - return mb_strlen($item->getStyle()->getItemExtra()); - }, - array_filter($this->items, function (MenuItemInterface $item) { - return $item->getStyle()->getDisplaysExtra(); - }) - )); - } - - /** - * @return DefaultStyle - */ - public function getStyle(): ItemStyle - { - return $this->style; - } - - public function setStyle(DefaultStyle $style): void - { - $this->style = $style; - } - - /** - * @inheritDoc - */ - public function propagateStyles(CliMenu $parent): void - { - collect($this->items) - ->filter(function (int $k, MenuItemInterface $item) use ($parent) { - return $parent->getStyleLocator()->hasStyleForMenuItem($item); - }) - ->filter(function (int $k, MenuItemInterface $item) { - return !$item->getStyle()->hasChangedFromDefaults(); - }) - ->each(function (int $k, $item) use ($parent) { - $item->setStyle(clone $parent->getItemStyleForItem($item)); - }); - - collect($this->items) - ->filter(function (int $k, MenuItemInterface $item) { - return $item instanceof PropagatesStyles; - }) - ->each(function (int $k, $item) use ($parent) { - $item->propagateStyles($parent); - }); - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/StaticItem.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/StaticItem.php deleted file mode 100644 index 5c212be..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/MenuItem/StaticItem.php +++ /dev/null @@ -1,109 +0,0 @@ - - */ -class StaticItem implements MenuItemInterface -{ - /** - * @var string - */ - private $text; - - /** - * @var DefaultStyle - */ - private $style; - - public function __construct(string $text) - { - $this->text = $text; - - $this->style = new DefaultStyle(); - } - - /** - * The output text for the item - */ - public function getRows(MenuStyle $style, bool $selected = false) : array - { - return explode("\n", StringUtil::wordwrap($this->text, $style->getContentWidth())); - } - - /** - * Return the raw string of text - */ - public function getText() : string - { - return $this->text; - } - - /** - * Set the raw string of text - */ - public function setText(string $text) : void - { - $this->text = $text; - } - - /** - * Execute the items callable if required - */ - public function getSelectAction() : ?callable - { - return null; - } - - /** - * Can the item be selected - */ - public function canSelect() : bool - { - return false; - } - - /** - * Whether or not we are showing item extra - */ - public function showsItemExtra() : bool - { - return false; - } - - /** - * Enable showing item extra - */ - public function showItemExtra() : void - { - //noop - } - - /** - * Disable showing item extra - */ - public function hideItemExtra() : void - { - //noop - } - - /** - * @return DefaultStyle - */ - public function getStyle() : ItemStyle - { - return $this->style; - } - - public function setStyle(DefaultStyle $style) : void - { - $this->style = $style; - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/MenuStyle.php b/src/ncc/ThirdParty/php-school/cli-menu/MenuStyle.php deleted file mode 100644 index 4d9c371..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/MenuStyle.php +++ /dev/null @@ -1,852 +0,0 @@ - - */ -class MenuStyle -{ - /** - * @var Terminal - */ - protected $terminal; - - /** - * @var string - */ - protected $fg; - - /** - * @var string - */ - protected $bg; - - /** - * The width of the menu. Including borders and padding. - * Does not include margin. - * - * May not be the value that was requested in the - * circumstance that the terminal is smaller then the - * requested width. - * - * @var int - */ - protected $width; - - /** - * In case the requested width is wider than the terminal - * then we shrink the width to fit the terminal. We keep - * the requested size in case the margins are changed and - * we need to recalculate the width. - * - * @var int - */ - private $requestedWidth; - - /** - * @var int - */ - protected $margin = 0; - - /** - * @var int - */ - protected $paddingTopBottom = 0; - - /** - * @var int - */ - protected $paddingLeftRight = 0; - - /** - * @var array - */ - private $paddingTopBottomRows = []; - - /** - * @var int - */ - protected $contentWidth; - - /** - * @var string - */ - private $itemExtra; - - /** - * @var bool - */ - private $displaysExtra; - - /** - * @var string - */ - private $titleSeparator; - - /** - * @var string - */ - private $coloursSetCode; - - /** - * @var string - */ - private $invertedColoursSetCode = "\033[7m"; - - /** - * @var string - */ - private $invertedColoursUnsetCode = "\033[27m"; - - /** - * @var string - */ - private $coloursResetCode = "\033[0m"; - - /** - * @var int - */ - private $borderTopWidth = 0; - - /** - * @var int - */ - private $borderRightWidth = 0; - - /** - * @var int - */ - private $borderBottomWidth = 0; - - /** - * @var int - */ - private $borderLeftWidth = 0; - - /** - * @var string - */ - private $borderColour = 'white'; - - /** - * @var array - */ - private $borderTopRows = []; - - /** - * @var array - */ - private $borderBottomRows = []; - - /** - * @var bool - */ - private $marginAuto = false; - - /** - * @var bool - */ - private $debugMode = false; - - /** - * Default Values - * - * @var array - */ - private static $defaultStyleValues = [ - 'fg' => 'white', - 'bg' => 'blue', - 'width' => 100, - 'paddingTopBottom' => 1, - 'paddingLeftRight' => 2, - 'margin' => 2, - 'itemExtra' => '✔', - 'displaysExtra' => false, - 'titleSeparator' => '=', - 'borderTopWidth' => 0, - 'borderRightWidth' => 0, - 'borderBottomWidth' => 0, - 'borderLeftWidth' => 0, - 'borderColour' => 'white', - 'marginAuto' => false, - ]; - - /** - * @var array - */ - private static $availableForegroundColors = [ - 'black' => 30, - 'red' => 31, - 'green' => 32, - 'yellow' => 33, - 'blue' => 34, - 'magenta' => 35, - 'cyan' => 36, - 'white' => 37, - 'default' => 39, - ]; - - /** - * @var array - */ - private static $availableBackgroundColors = [ - 'black' => 40, - 'red' => 41, - 'green' => 42, - 'yellow' => 43, - 'blue' => 44, - 'magenta' => 45, - 'cyan' => 46, - 'white' => 47, - 'default' => 49, - ]; - - /** - * @var array - */ - private static $availableOptions = [ - 'bold' => ['set' => 1, 'unset' => 22], - 'dim' => ['set' => 2, 'unset' => 22], - 'underscore' => ['set' => 4, 'unset' => 24], - 'blink' => ['set' => 5, 'unset' => 25], - 'reverse' => ['set' => 7, 'unset' => 27], - 'conceal' => ['set' => 8, 'unset' => 28] - ]; - - /** - * Initialise style - */ - public function __construct(Terminal $terminal = null) - { - $this->terminal = $terminal ?: TerminalFactory::fromSystem(); - - $this->fg = self::$defaultStyleValues['fg']; - $this->bg = self::$defaultStyleValues['bg']; - - $this->generateColoursSetCode(); - - $this->setWidth(self::$defaultStyleValues['width']); - $this->setPaddingTopBottom(self::$defaultStyleValues['paddingTopBottom']); - $this->setPaddingLeftRight(self::$defaultStyleValues['paddingLeftRight']); - $this->setMargin(self::$defaultStyleValues['margin']); - $this->setItemExtra(self::$defaultStyleValues['itemExtra']); - $this->setDisplaysExtra(self::$defaultStyleValues['displaysExtra']); - $this->setTitleSeparator(self::$defaultStyleValues['titleSeparator']); - $this->setBorderTopWidth(self::$defaultStyleValues['borderTopWidth']); - $this->setBorderRightWidth(self::$defaultStyleValues['borderRightWidth']); - $this->setBorderBottomWidth(self::$defaultStyleValues['borderBottomWidth']); - $this->setBorderLeftWidth(self::$defaultStyleValues['borderLeftWidth']); - $this->setBorderColour(self::$defaultStyleValues['borderColour']); - } - - public function hasChangedFromDefaults() : bool - { - $currentValues = [ - $this->fg, - $this->bg, - $this->width, - $this->paddingTopBottom, - $this->paddingLeftRight, - $this->margin, - $this->itemExtra, - $this->displaysExtra, - $this->titleSeparator, - $this->borderTopWidth, - $this->borderRightWidth, - $this->borderBottomWidth, - $this->borderLeftWidth, - $this->borderColour, - $this->marginAuto, - ]; - - $defaultStyleValues = self::$defaultStyleValues; - if ($this->width !== $this->requestedWidth) { - $defaultStyleValues['width'] = $this->width; - } - - return $currentValues !== array_values($defaultStyleValues); - } - - /** - * Get text for a disabled menu item. - * - * This sets the foreground colour to the ansi bright equivalent, - * and on supported terminals, adds additional dim formatting. - * - * @return string - */ - public function getDisabledItemText(string $text) : string - { - return sprintf( - "\033[%sm\033[%sm%s\033[%sm\033[%sm", - self::$availableOptions['dim']['set'], - $this->getForegroundColourCode(true), - $text, - $this->getForegroundColourCode(), - self::$availableOptions['dim']['unset'] - ); - } - - /** - * Get the ansi escape sequence for the foreground colour. - * - * @param bool $bright Whether to modify to the ansi bright variation - * - * @return string - */ - private function getForegroundColourCode(bool $bright = false) : string - { - if (!ctype_digit($this->fg)) { - $fgCode = (int)self::$availableForegroundColors[$this->fg]; - $fgCode += ($bright ? 60 : 0); - } else { - $fgCode = sprintf("38;5;%s", ((int)$this->fg + ($bright ? 60 : 0))); - } - - return (string)$fgCode; - } - - /** - * Get the ansi escape sequence for the background colour. - * - * @param bool $bright Whether to modify to the ansi bright variation - * - * @return string - */ - private function getBackgroundColourCode(bool $bright = false) : string - { - if (!ctype_digit($this->bg)) { - $bgCode = (int)self::$availableBackgroundColors[$this->bg]; - $bgCode += ($bright ? 60 : 0); - } else { - $bgCode = sprintf("48;5;%s", ((int)$this->bg + ($bright ? 60 : 0))); - } - - return (string)$bgCode; - } - - /** - * Generates the ansi escape sequence to set the colours - */ - private function generateColoursSetCode() : void - { - $this->coloursSetCode = sprintf( - "\033[%s;%sm", - $this->getForegroundColourCode(), - $this->getBackgroundColourCode() - ); - } - - /** - * Get the colour code for Bg and Fg - */ - public function getColoursSetCode() : string - { - return $this->coloursSetCode; - } - - /** - * Get the inverted escape sequence (used for selected elements) - */ - public function getInvertedColoursSetCode() : string - { - return $this->invertedColoursSetCode; - } - - /** - * Get the inverted escape sequence (used for selected elements) - */ - public function getInvertedColoursUnsetCode() : string - { - return $this->invertedColoursUnsetCode; - } - - /** - * Get the escape sequence used to reset colours to default - */ - public function getColoursResetCode() : string - { - return $this->coloursResetCode; - } - - /** - * Calculate the contents width - * - * The content width is menu width minus borders and padding. - */ - protected function calculateContentWidth() : void - { - $this->contentWidth = $this->width - - ($this->paddingLeftRight * 2) - - ($this->borderRightWidth + $this->borderLeftWidth); - - if ($this->contentWidth < 0) { - $this->contentWidth = 0; - } - } - - public function getFg() : string - { - return $this->fg; - } - - public function setFg(string $fg, string $fallback = null) : self - { - $this->fg = ColourUtil::validateColour( - $this->terminal, - $fg, - $fallback - ); - $this->generateColoursSetCode(); - - return $this; - } - - public function getBg() : string - { - return $this->bg; - } - - public function setBg(string $bg, string $fallback = null) : self - { - $this->bg = ColourUtil::validateColour( - $this->terminal, - $bg, - $fallback - ); - - $this->generateColoursSetCode(); - $this->generatePaddingTopBottomRows(); - - return $this; - } - - public function getWidth() : int - { - return $this->width; - } - - public function setWidth(int $width) : self - { - Assertion::greaterOrEqualThan($width, 0); - - $this->requestedWidth = $width; - - $this->width = $this->maybeShrinkWidth($this->marginAuto ? 0 : $this->margin, $width); - - if ($this->marginAuto) { - $this->calculateMarginAuto($this->width); - } - - $this->calculateContentWidth(); - $this->generateBorderRows(); - $this->generatePaddingTopBottomRows(); - - return $this; - } - - private function maybeShrinkWidth(int $margin, int $width) : int - { - if ($width + ($margin * 2) >= $this->terminal->getWidth()) { - $width = $this->terminal->getWidth() - ($margin * 2); - - if ($width <= 0) { - throw CannotShrinkMenuException::fromMarginAndTerminalWidth($margin, $this->terminal->getWidth()); - } - } - - return $width; - } - - public function getPaddingTopBottom() : int - { - return $this->paddingTopBottom; - } - - public function getPaddingLeftRight() : int - { - return $this->paddingLeftRight; - } - - private function generatePaddingTopBottomRows() : void - { - if ($this->borderLeftWidth || $this->borderRightWidth) { - $borderColour = $this->getBorderColourCode(); - } else { - $borderColour = ''; - } - - $paddingRow = sprintf( - "%s%s%s%s%s%s%s%s%s%s\n", - $this->debugMode ? $this->getDebugString($this->margin) : str_repeat(' ', $this->margin), - $borderColour, - str_repeat(' ', $this->borderLeftWidth), - $this->getColoursSetCode(), - str_repeat(' ', $this->paddingLeftRight), - str_repeat(' ', $this->contentWidth), - str_repeat(' ', $this->paddingLeftRight), - $borderColour, - str_repeat(' ', $this->borderRightWidth), - $this->coloursResetCode - ); - - - if ($this->debugMode && s::length($paddingRow) <= $this->terminal->getWidth()) { - $paddingRow = substr_replace( - $paddingRow, - sprintf("%s\n", $this->getDebugString($this->terminal->getWidth() - (s::length($paddingRow) - 1))), - -1 - ); - } - - $this->paddingTopBottom = max($this->paddingTopBottom, 0); - $this->paddingTopBottomRows = array_fill(0, $this->paddingTopBottom, $paddingRow); - } - - /** - * @return array - */ - public function getPaddingTopBottomRows() : array - { - return $this->paddingTopBottomRows; - } - - public function setPadding(int $topBottom, int $leftRight = null) : self - { - if ($leftRight === null) { - $leftRight = $topBottom; - } - - $this->setPaddingTopBottom($topBottom); - $this->setPaddingLeftRight($leftRight); - - $this->calculateContentWidth(); - $this->generatePaddingTopBottomRows(); - - return $this; - } - - public function setPaddingTopBottom(int $topBottom) : self - { - Assertion::greaterOrEqualThan($topBottom, 0); - $this->paddingTopBottom = $topBottom; - - $this->generatePaddingTopBottomRows(); - - return $this; - } - - public function setPaddingLeftRight(int $leftRight) : self - { - Assertion::greaterOrEqualThan($leftRight, 0); - $this->paddingLeftRight = $leftRight; - - $this->calculateContentWidth(); - $this->generatePaddingTopBottomRows(); - - return $this; - } - - public function getMargin() : int - { - return $this->margin; - } - - public function setMarginAuto() : self - { - $this->marginAuto = true; - $this->margin = 0; - - $this->setWidth($this->requestedWidth); - - return $this; - } - - private function calculateMarginAuto(int $width) : void - { - $this->margin = (int) floor(($this->terminal->getWidth() - ($width)) / 2); - } - - public function setMargin(int $margin) : self - { - Assertion::greaterOrEqualThan($margin, 0); - - $this->marginAuto = false; - $this->margin = $margin; - - //margin + width may now exceed terminal size - //so set width again to trigger width check + maybe resize - $this->setWidth($this->requestedWidth); - - return $this; - } - - public function getContentWidth() : int - { - return $this->contentWidth; - } - - /** - * Get padding for right had side of content - */ - public function getRightHandPadding(int $contentLength) : int - { - $rightPadding = $this->getContentWidth() - $contentLength + $this->getPaddingLeftRight(); - - if ($rightPadding < 0) { - $rightPadding = 0; - } - - return $rightPadding; - } - - public function setItemExtra(string $itemExtra) : self - { - $this->itemExtra = $itemExtra; - - return $this; - } - - public function getItemExtra() : string - { - return $this->itemExtra; - } - - public function getDisplaysExtra() : bool - { - return $this->displaysExtra; - } - - public function setDisplaysExtra(bool $displaysExtra) : self - { - $this->displaysExtra = $displaysExtra; - - return $this; - } - - public function getTitleSeparator() : string - { - return $this->titleSeparator; - } - - public function setTitleSeparator(string $actionSeparator) : self - { - $this->titleSeparator = $actionSeparator; - - return $this; - } - - private function generateBorderRows() : void - { - $borderRow = sprintf( - "%s%s%s%s\n", - $this->debugMode ? $this->getDebugString($this->margin) : str_repeat(' ', $this->margin), - $this->getBorderColourCode(), - str_repeat(' ', $this->width), - $this->getColoursResetCode() - ); - - if ($this->debugMode && s::length($borderRow) <= $this->terminal->getWidth()) { - $borderRow = substr_replace( - $borderRow, - sprintf("%s\n", $this->getDebugString($this->terminal->getWidth() - (s::length($borderRow) - 1))), - -1 - ); - } - - $this->borderTopWidth = max($this->borderTopWidth, 0); - $this->borderBottomWidth = max($this->borderBottomWidth, 0); - - $this->borderTopRows = array_fill(0, $this->borderTopWidth, $borderRow); - $this->borderBottomRows = array_fill(0, $this->borderBottomWidth, $borderRow); - } - - /** - * @return array - */ - public function getBorderTopRows() : array - { - return $this->borderTopRows; - } - - /** - * @return array - */ - public function getBorderBottomRows() : array - { - return $this->borderBottomRows; - } - - /** - * @param int|string|null $rightWidth - * @param int|string|null $bottomWidth - * @param int|string|null $leftWidth - * - * Shorthand function to set all borders values at once - */ - public function setBorder( - int $topWidth, - $rightWidth = null, - $bottomWidth = null, - $leftWidth = null, - string $colour = null - ) : self { - if (!is_int($rightWidth)) { - $colour = $rightWidth; - $rightWidth = $bottomWidth = $leftWidth = $topWidth; - } elseif (!is_int($bottomWidth)) { - $colour = $bottomWidth; - $bottomWidth = $topWidth; - $leftWidth = $rightWidth; - } elseif (!is_int($leftWidth)) { - $colour = $leftWidth; - $leftWidth = $rightWidth; - } - - $this->borderTopWidth = $topWidth; - $this->borderRightWidth = $rightWidth; - $this->borderBottomWidth = $bottomWidth; - $this->borderLeftWidth = $leftWidth; - - if (is_string($colour)) { - $this->setBorderColour($colour); - } - - $this->calculateContentWidth(); - $this->generateBorderRows(); - $this->generatePaddingTopBottomRows(); - - return $this; - } - - public function setBorderTopWidth(int $width) : self - { - $this->borderTopWidth = $width; - - $this->generateBorderRows(); - - return $this; - } - - public function setBorderRightWidth(int $width) : self - { - $this->borderRightWidth = $width; - $this->calculateContentWidth(); - - $this->generatePaddingTopBottomRows(); - - return $this; - } - - public function setBorderBottomWidth(int $width) : self - { - $this->borderBottomWidth = $width; - - $this->generateBorderRows(); - - return $this; - } - - public function setBorderLeftWidth(int $width) : self - { - $this->borderLeftWidth = $width; - $this->calculateContentWidth(); - - $this->generatePaddingTopBottomRows(); - - return $this; - } - - public function setBorderColour(string $colour, string $fallback = null) : self - { - $this->borderColour = ColourUtil::validateColour( - $this->terminal, - $colour, - $fallback - ); - - $this->generateBorderRows(); - $this->generatePaddingTopBottomRows(); - - return $this; - } - - public function getBorderTopWidth() : int - { - return $this->borderTopWidth; - } - - public function getBorderRightWidth() : int - { - return $this->borderRightWidth; - } - - public function getBorderBottomWidth() : int - { - return $this->borderBottomWidth; - } - - public function getBorderLeftWidth() : int - { - return $this->borderLeftWidth; - } - - public function getBorderColour() : string - { - return $this->borderColour; - } - - public function getBorderColourCode() : string - { - if (!ctype_digit($this->borderColour)) { - $borderColourCode = self::$availableBackgroundColors[$this->borderColour]; - } else { - $borderColourCode = sprintf("48;5;%s", $this->borderColour); - } - - return sprintf("\033[%sm", $borderColourCode); - } - - - /** - * Get ansi escape sequence for setting or unsetting the specified option code. - * - * @param string $string Option code (bold|dim|underscore|blink|reverse|conceal) - * @param bool $set Whether to set or unset the code - * - * @return string - */ - public function getOptionCode(string $string, bool $set = true): string - { - return sprintf("\033[%sm", self::$availableOptions[$string][$set ? 'set' : 'unset']); - } - - /** - * Get a string of given length consisting of 0-9 - * eg $length = 15 : 012345678901234 - */ - private function getDebugString(int $length) : string - { - $nums = []; - for ($i = 0, $j = 0; $i < $length; $i++, $j++) { - if ($j === 10) { - $j = 0; - } - - $nums[] = $j; - } - - return implode('', $nums); - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/README.md b/src/ncc/ThirdParty/php-school/cli-menu/README.md deleted file mode 100644 index ae65957..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/README.md +++ /dev/null @@ -1,1473 +0,0 @@ -

- -

- -

- - - - - - - - - - - - - - - -

- ---- -## Contents - - * [Minimum Requirements](#minimum-requirements) - * [Installation](#installation) - * [Upgrading](#upgrading) - * [Usage](#usage) - * [Quick Setup](#quick-setup) - * [Examples](#examples) - * [API](#api) - * [Appearance](#appearance) - * [Menu Title](#menu-title) - * [Colour](#colour) - * [Width](#width) - * [Padding](#padding) - * [Margin](#margin) - * [Borders](#borders) - * [Exit Button Text](#exit-button-text) - * [Remove Exit Button](#remove-exit-button) - * [Items](#appearance) - * [Selectable Item](#selectable-item) - * [Checkbox Item](#checkbox-item) - * [Radio Item](#radio-item) - * [Line Break Item](#line-break-item) - * [Static Item](#static-item) - * [Ascii Art Item](#ascii-art-item) - * [Sub Menu Item](#sub-menu-item) - * [Split Item](#split-item) - * [Disabling Items & Sub Menus](#disabling-items--sub-menus) - * [Item Markers](#item-markers) - * [Item Extra](#item-extra) - * [Menu Methods](#menu-methods) - * [Redrawing the Menu](#redrawing-the-menu) - * [Getting, Removing and Adding items](#getting-removing-and-adding-items) - * [Custom Control Mapping](#custom-control-mapping) - * [Item Keyboard Shortcuts](#item-keyboard-shortcuts) - * [Dialogues](#dialogues) - * [Flash](#flash) - * [Confirm](#confirm) - * [Inputs](#inputs) - * [Text](#text-input) - * [Number](#number-input) - * [Password](#password-input) - * [Custom Input](#custom-input) - * [Dialogues & Input Styling](#dialogues--input-styling) - * [Docs Translations](#docs-translations) - * [Integrations](#integrations) - -## Minimum Requirements - - * PHP 7.1 - * Composer - * ext-posix - -## Installation - -```bash -composer require php-school/cli-menu -``` - -## Upgrading - -Please refer to the [Upgrade Documentation](UPGRADE.md) documentation to see what is required to upgrade your installed -`cli-menu` version. - -## Usage - -### Quick Setup -Here is a super basic example menu which will echo out the text of the selected item to get you started. -```php -getSelectedItem()->getText(); -}; - -$menu = (new CliMenuBuilder) - ->setTitle('Basic CLI Menu') - ->addItem('First Item', $itemCallable) - ->addItem('Second Item', $itemCallable) - ->addItem('Third Item', $itemCallable) - ->addLineBreak('-') - ->setBorder(1, 2, 'yellow') - ->setPadding(2, 4) - ->setMarginAuto() - ->build(); - - -$menu->open(); -``` - -### Examples - -Check out the [examples](examples) directory and run them to see what is possible! The best way to run the examples is to git clone the repository: - -```shell -git clone https://github.com/php-school/cli-menu.git -cd cli-menu -composer install --no-dev -cd examples -php basic.php -``` - -#### Basic Menu -basic - -#### Basic Menu Auto Centered -submenu - -#### Basic Menu with separation -basic-seperation - -#### Menu with crazy separation -crazy-seperation - -#### Custom Styles -custom-styles - -#### Borders and 256 colours -submenu - -#### Useful Separation -useful-seperation - -#### Displaying Item Extra -item-extra - -#### Remove Defaults -remove-defaults - -#### Submenu -submenu -submenu-options - -#### Split Item -split-item - -#### Disabled Items & Submenus -submenu - -#### Checkbox Items -checkbox -checkbox-split - -#### Radio Items - -radio -radio-split - -#### Flash Dialogue -submenu - -#### Confirm Dialogue -submenu - -#### Number Input -submenu -submenu - -#### Text Input -submenu - -#### Password Input -submenu - -#### Using cli-menu to create art - -Want to see something really cool? Well you can use cli-menu to create a drawing canvas on your terminal. Check it out!: - -submenu - -## API - -The `CliMenu` object is constructed via the Builder class - -```php -build(); -``` - -Once you have a menu object, you can open and close it like so: - -```php -$menu->open(); -$menu->close(); -``` - -### Appearance - -#### Menu Title - -You can give your menu a title and you can customise the separator, a line which displays under the title. -Whatever string you pass to `setTitleSeparator` will be repeated for the width of the Menu. - -```php -setTitle('One Menu to rule them all!') - ->setTitleSeparator('*-') - ->build(); -``` - -#### Colour - -You can change the foreground and background colour of the menu to any of the following colours: - -* black -* red -* green -* yellow -* blue -* magenta -* cyan -* white - -```php -setForegroundColour('green') - ->setBackgroundColour('black') - ->build(); -``` - -If your terminal supports 256 colours then you can also use any of those by specifying the code, like `230`. You can find a list -of the [colours and codes here](https://jonasjacek.github.io/colors/). If you specify a code and the terminal does not support 256 colours -it will automatically fallback to a sane default, using a generated map you can see in src/Util/ColourUtil.php. You can also manually specify the -fallback colour as the second argument to `setForegroundColour` and `setBackgroundColour. - -In this example if no 256 colour support is found it will automatically fall back to `green` and `blue`. - -```php -setForegroundColour('40') - ->setBackgroundColour('92') - ->build(); -``` - -In this example if no 256 colour support is found it will fall back to `yellow` and `magenta`. - -```php -setForegroundColour('40', 'yellow') - ->setBackgroundColour('92', 'magenta') - ->build(); -``` - -#### Width - -Customise the width of the menu. Setting a value larger than the size of the terminal will result in -the width being the same as the terminal size. The width will include the padding and the border. So with a width of 100 -and all around border of 5 and all around padding of 5 will leave for a content width of 80 (5 + 5 + 80 + 5 + 5). - -```php -setWidth(1000) //if terminal is only 400, width will also be 400 - ->build(); -``` - -If you want to use the full width of the terminal, you can grab the terminal object and ask/set it from there like so: - -```php -setWidth($builder->getTerminal()->getWidth()) - ->build(); -``` - -If you want to use the full width of the terminal and apply a margin, use the terminal width, and we will do the calculations -automatically (shrink the width based on the margin). - -```php -setWidth($builder->getTerminal()->getWidth()) - ->setMargin(2) - ->build(); -``` - -#### Padding - -The padding can be set for all sides with one value or can be set individually for top/bottom and left/right. - -```php -setPadding(10) //10 padding top/bottom/left/right - ->build(); -``` - -Different values can also be set for the top/bottom and the left/right padding: - -```php -setPaddingTopBottom(10) - ->setPaddingLeftRight(5) - ->build(); -``` - -Configure top/bottom and left/right padding using the shorthand method: - -```php -setPadding(10, 5) //top/bottom = 10, left/right = 5 - ->build(); -``` - -#### Margin - -The margin can be customised as one value. It can also be set automatically which will center the menu nicely in the -terminal. - -Automatically center menu: - -```php -setWidth(200) - ->setMarginAuto() - ->build(); -``` - -Arbitrary margin: - -```php -setWidth(200) - ->setMargin(5) - ->build(); -``` - -#### Borders - -Borders can be customised just like CSS borders. We can add any amount of border to either side, left, right top or -bottom and we can apply a colour to it. - -Set universal red border of 2: - -```php -setWidth(200) - ->setBorder(2, 'red') - ->build(); -``` - -Configure each border separately: - -```php -setWidth(200) - ->setBorderTopWidth(2) - ->setBorderRightWidth(4) - ->setBorderBottomWidth(2) - ->setBorderLeftWidth(4) - ->setBorderColour('42', 'red') //SpringGreen2 fallback to red - ->build(); -``` - -Configure each border separately using the shorthand method, like CSS: - -```php -setWidth(200) - ->setBorder(3, 4, 'red') //top/bottom = 3, left/right = 4 - ->setBorder(3, 4, 5, 'red') //top = 3, left/right = 4, bottom = 5 - ->setBorder(3, 4, 5, 6, 'red') //top = 3, left = 4, bottom = 5, right = 6 - ->build(); -``` - -#### Exit Button Text - -Modify the exit button text: - -```php -setExitButtonText("Don't you want me baby?") - ->build(); -``` - -#### Remove Exit Button - -You can remove the exit button altogether: - -```php -disableDefaultItems() - ->build(); -``` - -Note: This will also disable the Go Back button for sub menus. - -You can manually add exit and go back buttons using the following: - -```php -disableDefaultItems() - ->addSubMenu('Super Sub Menu', function (CliMenuBuilder $b) { - $b->disableDefaultItems() - ->setTitle('Behold the awesomeness') - ->addItem('Return to parent menu', new GoBackAction); //add a go back button - }) - ->addItem('Leave this place now !', new ExitAction) //add an exit button - ->build(); -``` - -### Items - -There a few different types of items you can add to your menu - -* Selectable Item - This is the type of item you need for something to be selectable (you can hit enter and it will invoke your callable) -* Checkbox Item - This is a checkbox type of item that keeps track of its toggled state to show a different marker. -* Radio Item - This is a radio type of item that keeps track of its toggled state to show a different marker. Disables all other radios within its `CliMenu` level. -* Line Break Item - This is used to break up areas, it can span multiple lines and will be the width of Menu. Whatever string is passed will be repeated. -* Static Item - This will print whatever text is passed, useful for headings. -* Ascii Art Item - Special item which allows usage of Ascii art. It takes care of padding and alignment. -* Sub Menu Item - Special item to allow an item to open another menu. Useful for an options menu. -* Split Item - Special item to fit multiple items on the same row. - -### Selectable Item - -```php -addItem('The Item Text', function (CliMenu $menu) { - echo 'I am alive!'; - }) - ->build(); -``` - -You can add multiple items at once like so: - -```php -addItems([ - ['Item 1', $callable], - ['Item 2', $callable], - ['Item 3', $callable], - ]) - ->build(); -``` - -Note: You can add as many items as you want and they can all have a different action. The action is the second parameter -and must be a valid PHP `callable`. Try using an `Invokable` class to keep your actions easily testable. - -### Checkbox Item - -```php -getSelectedItem()->getText(); -}; - -$menu = (new CliMenuBuilder) - ->addCheckboxItem('Item 1', $callable) - ->addCheckboxItem('Item 2', $callable) - ->addCheckboxItem('Item 3', $callable) - ->build(); -``` - -You can add multiple checkbox items at once like so: - -```php -addCheckboxItems([ - ['Item 1', $callable], - ['Item 2', $callable], - ['Item 3', $callable], - ]) - ->build(); -``` - -When selecting an item, it will be toggled. Notice at first each item is unchecked. After selecting one it will become -checked. - -### Radio Item - -```php -getSelectedItem()->getText(); -}; - -$menu = (new CliMenuBuilder) - ->addRadioItem('Item 1', $callable) - ->addRadioItem('Item 2', $callable) - ->addRadioItem('Item 3', $callable) - ->build(); -``` - -You can add multiple radio items at once like so: - -```php -addRadioItems([ - ['Item 1', $callable], - ['Item 2', $callable], - ['Item 3', $callable], - ]) - ->build(); -``` - -When selecting an item, it will be toggled. Notice at first each item is unchecked. After selecting one it will become -checked and all other `RadioItem` within the same level will be unchecked. - -### Line Break Item - -```php -addLineBreak('<3', 2) - ->build(); -``` - -The above would repeat the character sequence `<3` across the Menu for 2 lines - -### Static Item - -Static items are similar to Line Breaks, however, they don't repeat and fill. It is output as is. -If the text is longer than the width of the Menu, it will be continued on the next line. - -```php -addStaticItem('AREA 1') - //add some items here - ->addStaticItem('AREA 2') - //add some boring items here - ->addStaticItem('AREA 51') - //add some top secret items here - ->build(); -``` - -### Ascii Art Item - -The following will place the Ascii art in the centre of your menu. Use these constants to alter the -alignment: - -* AsciiArtItem::POSITION_CENTER -* AsciiArtItem::POSITION_LEFT -* AsciiArtItem::POSITION_RIGHT - -```php -addAsciiArt($art, AsciiArtItem::POSITION_CENTER) - ->build(); -``` - -The third optional parameter to `addAsciiArt` is alternate text. If the ascii art is too wide for the terminal, then -it will not be displayed at all. However, if you pass a string to the third argument, in the case that the ascii art is too -wide for the terminal the alternate text will be displayed instead. - -### Sub Menu Item - -Sub Menus are really powerful! You can add Menus to Menus, whattttt?? You can have your main menu and then an options menu. -The options item will look like a normal item except when you hit it, you will enter to another menu, which -can have different styles and colours! - -```php -addItem('Normal Item', $callable) - ->addSubMenu('Super Sub Menu', function (CliMenuBuilder $b) { - $b->setTitle('Behold the awesomeness') - ->addItem(/** **/); - }) - ->build(); -``` - -In this example a single sub menu will be created. Upon entering the sub menu, you will be able to return to the main menu -or exit completely. A Go Back button will be automatically added. You can customise this text using the `->setGoBackButtonText()` method on the `CliMenuBuilder` -instance for the sub menu. - -There are a few things to note about the syntax and builder process here - -1. The first parameter to `addSubMenu` is the text to be displayed on the menu which you select to enter the submenu. -2. The second parameter is a closure, which will be invoked with a new instance of `CliMenuBuilder` which you can use to customise the sub menu exactly the same way you would the parent -3. If you do not modify the styles of the sub menu (eg, colours) it will inherit styles from the parent! - -If you have already have a configured menu builder you can just pass that to `addSubMenuFromBuilder` and be done: - -```php -setTitle('Behold the awesomeness') - ->addItem(/** **/); - -$menu = (new CliMenuBuilder) - ->addSubMenuFromBuilder('Super Sub Menu', $subMenuBuilder) - ->build(); -``` - -Note: The submenu menu item will be an instance of `\ncc\PhpSchool\CliMenu\MenuItem\MenuMenuItem`. If you need access to the submenu, -you can get it via `$menuMenuItem->getSubMenu()`. - -### Split Item - -Split Items allows you to add multiple items on the same row. The full width of the menu will be split evenly between all items. You can move between those items using left/right arrows. - -You can set the number of spaces separating items using `->setGutter()` (defaults to 2). - -Only Selectable, Checkbox, Radio, Static and SubMenu items are currently allowed inside a Split Item. - -```php -getSelectedItem()->getText(); -}; - -$menu = (new CliMenuBuilder) - ->setWidth(150) - ->addStaticItem('Below is a SplitItem') - ->addSplitItem(function (SplitItemBuilder $b) use ($itemCallable) { - $b->setGutter(5) - ->addSubMenu('Sub Menu on a split item', function (CliMenuBuilder $b) { - $b->setTitle('Behold the awesomeness') - ->addItem('This is awesome', function() { print 'Yes!'; }); - }) - ->addItem('Item 2', $itemCallable) - ->addStaticItem('Item 3 - Static'); - }) - ->build(); - -$menu->open(); -``` - -There are a few things to note about the syntax and builder process here: - -1. The first parameter to `addSplitItem` is a closure, which will be invoked with a new instance of `SplitItemBuilder` which you can use to add items to the split item. -2. You can call `addItem`, `addCheckboxItem`, `addRadioItem`, `addSubMenu` and `addStaticItem` on the `SplitItemBuilder`. -3. `SplitItemBuilder` has a fluent interface so you can chain method calls. - -### Disabling Items & Sub Menus - -In this example we are disabling certain items and a submenu but still having them shown in the menu. - -```php -getSelectedItem()->getText(); -}; - -$menu = (new CliMenuBuilder) - ->setTitle('Basic CLI Menu Disabled Items') - ->addItem('First Item', $itemCallable) - ->addItem('Second Item', $itemCallable, false, true) - ->addItem('Third Item', $itemCallable, false, true) - ->addSubMenu('Submenu', function (CliMenuBuilder $b) use ($itemCallable) { - $b->setTitle('Basic CLI Menu Disabled Items > Submenu') - ->addItem('You can go in here!', $itemCallable); - }) - ->addSubMenu('Disabled Submenu', function (CliMenuBuilder $b) use ($itemCallable) { - $b->setTitle('Basic CLI Menu Disabled Items > Disabled Submenu') - ->addItem('Nope can\'t see this!', $itemCallable) - ->disableMenu(); - }) - ->addLineBreak('-') - ->build(); -``` - -The third param on the `->addItem` call is what disables an item while the `->disableMenu()` call disables the relevant menu. - -The outcome is a full menu with dimmed rows to denote them being disabled. When a user navigates the menu these items are jumped over to the next available selectable item. - -### Item Markers - -The marker displayed by the side of the currently active item can be modified, UTF-8 characters are supported. -The marker for un-selected items can also be modified. If you want to disable it, just set it to an empty string. Item -markers only display on *selectable* items, which are: `\ncc\PhpSchool\CliMenu\MenuItem\SelectableItem` & `\ncc\PhpSchool\CliMenu\MenuItem\MenuMenuItem`. - -```php -modifySelectableStyle(function (SelectableStyle $style) { - $style->setUnselectedMarker('❅ ') - ->setSelectedMarker('✏ ') - - // disable unselected marker - ->setUnselectedMarker('') - ; - }) - ->build(); -``` - -You may also change the marker for `\ncc\PhpSchool\CliMenu\MenuItem\CheckboxItem`: - -```php -modifyCheckboxStyle(function (CheckboxStyle $style) { - $style->setUncheckedMarker('[○] ') - ->setCheckedMarker('[●] '); - }) - ->addCheckboxItem('Orange juice', function () {}) - ->addCheckboxItem('Bread', function () {}) - ->build(); -``` - -and for `\ncc\PhpSchool\CliMenu\MenuItem\RadioItem`: - -```php -modifyRadioStyle(function (RadioStyle $style) { - $style->setUncheckedMarker('[ ] ') - ->setCheckedMarker('[✔] '); - }) - ->addRadioItem('Go shopping', function () {}) - ->addRadioItem('Go camping', function () {}) - ->build(); -``` - -### Item Extra - -You can optionally display some arbitrary text on the right hand side of an item. You can customise this text and -you indicate which items to display it on. We use it to display `[COMPLETED]` on completed exercises, where the menu lists -exercises for a workshop application. - -Item Extra is currently limited to only selectable items (menus, checkboxes & radios included) - -The third parameter to `addItem` is a boolean whether to show the item extra or not. It defaults to false. - -```php -modifySelectableStyle(function (SelectableStyle $style) { - $style->setItemExtra('✔'); - }) - ->addItem('Exercise 1', function (CliMenu $menu) { echo 'I am complete!'; }, true) - ->build(); -``` - -If no items have display extra set to true, then the item extra will not be displayed. If you toggle the item to show -it's item extra in a callback or at runtime it will render incorrectly. - -In order to fix that you need to tell the menu to display item extra explicitly. You can do this when constructing the -menu like so: - -```php -setItemExtra('✔') - ->addItem('Exercise 1', function (CliMenu $menu) { - $selectedItem = $menu->getSelectedItem(); - if ($selectedItem->showsItemExtra()) { - $selectedItem->hideItemExtra(); - } else { - $selectedItem->showItemExtra(); - } - }) - ->displayExtra() - ->build(); -``` - -## Menu Methods - -The next set of documentation applies to methods available directly on the `\ncc\PhpSchool\CliMenu\CliMenu` instance. Typically -you will invoke these methods whilst your menu is open in you action callbacks. - -### Redrawing the Menu - -You can modify the menu and its style when executing an action and then you can redraw it! In this example we will toggle the background -colour in an action. - -```php -getStyle()->setBg($menu->getStyle()->getBg() === 'red' ? 'blue' : 'red'); - $menu->redraw(); -}; - -$menu = (new CliMenuBuilder) - ->setTitle('Basic CLI Menu') - ->addItem('First Item', $itemCallable) - ->addItem('Second Item', $itemCallable) - ->addItem('Third Item', $itemCallable) - ->addLineBreak('-') - ->build(); - -$menu->open(); -``` - -If you change the menu drastically, such as making the width smaller, when it redraws you might see artifacts of the previous draw -as `redraw` only draws over the top of the terminal. If this happens you can pass `true` to `redraw` and it will first clear -the terminal before redrawing. - -```php -getStyle()->setWidth($menu->getStyle()->getWidth() === 100 ? 80 : 100); - $menu->redraw(true); -}; - -$menu = (new CliMenuBuilder) - ->setTitle('Basic CLI Menu') - ->addItem('First Item', $itemCallable) - ->addItem('Second Item', $itemCallable) - ->addItem('Third Item', $itemCallable) - ->addLineBreak('-') - ->build(); - -$menu->open(); -``` - -### Getting, Removing and Adding items - -You can also interact with the menu items in an action. You can add, remove and replace items. If you do this, you -will likely want to redraw the menu as well so the new list is rendered. - -```php -getItems() as $item) { - $menu->removeItem($item); - } - - //add single item - $menu->addItem(new LineBreakItem('-')); - - //add multiple items - $menu->addItems([new LineBreakItem('-'), new LineBreakItem('*')]); - - //replace all items - $menu->setItems([new LineBreakItem('+'), new LineBreakItem('-')]); - - $menu->redraw(); -}; - -$menu = (new CliMenuBuilder) - ->setTitle('Basic CLI Menu') - ->addItem('First Item', $itemCallable) - ->addItem('Second Item', $itemCallable) - ->addItem('Third Item', $itemCallable) - ->addLineBreak('-') - ->build(); - -$menu->open(); -``` - -## Custom Control Mapping - -This functionality allows to map custom key presses to a callable. For example we can set the key press "x" to close the menu: - -```php -close(); -}; - -$menu = (new CliMenuBuilder) - ->addItem('Item 1', function(CliMenu $menu) {}) - ->build(); - -$menu->addCustomControlMapping("x", $exit); - -$menu->open(); -``` - -Another example is mapping shortcuts to a list of items: - -```php -addItem('List of [C]lients', $myCallback) - ->build(); - -// Now, pressing Uppercase C (it's case sensitive) will call $myCallback -$menu->addCustomControlMapping('C', $myCallback); - -$menu->open(); -``` - -## Item Keyboard Shortcuts - -If you enable auto shortcuts `CliMenuBuilder` will parse the items text and check for shortcuts. Any single character inside square brackets -will be treated as a shortcut. Pressing that character when the menu is open will trigger that items callable. - -This functionality works for split items as well as sub menus. The same characters can be used inside sub menus and the -callable which is invoked will depend on which menu is currently open. - -Note: all shortcuts are lower cased. - -To enable this automatic keyboard shortcut mapping simply call `->enableAutoShortcuts()`: - -```php -enableAutoShortcuts() - ->addItem('List of [C]lients', $myCallback) - ->build(); - -$menu->open(); - -//Pressing c will execute $myCallback. -``` - -You can customise the shortcut matching by passing your own regex to `enableAutoShortcuts`. Be careful to only match -one character in the first capture group or an exception will be thrown. - -### Dialogues - -#### Flash - -Show a one line message over the top of the menu. It has a separate style object which is colored by default different -to the menu. It can be modified to suit your own style. The dialogue is dismissed with any key press. In the example -below we change the background color on the flash to green. - -```php -flash("PHP School FTW!!"); - $flash->getStyle()->setBg('green'); - $flash->display(); -}; - -$menu = (new CliMenuBuilder) - ->setTitle('Basic CLI Menu') - ->addItem('First Item', $itemCallable) - ->addItem('Second Item', $itemCallable) - ->addItem('Third Item', $itemCallable) - ->addLineBreak('-') - ->build(); - -$menu->open(); -``` - -#### Confirm - -Prompts are very similar to flashes except that a button is shown which has to be selected to dismiss them. The button -text can be customised. - -```php -confirm('PHP School FTW!') - ->display('OK!'); -}; - -$menu = (new CliMenuBuilder) - ->setTitle('Basic CLI Menu') - ->addItem('First Item', $itemCallable) - ->addItem('Second Item', $itemCallable) - ->addItem('Third Item', $itemCallable) - ->addLineBreak('-') - ->build(); - -$menu->open(); -``` -### Inputs - -Inputs - added in version 3.0 of `cli-menu` allow to prompt the user for input and validate it. The following types are supported: -text, number and password. Inputs can be executed in any item callback. They have separate style objects which are colored by default different to the menu. -They can be modified to suit your own style. - -Each input is created by calling one of the `ask*` methods which will return an -instance of the input you requested. To execute the prompt and wait for the input you must -call `ask()` on the input. When the input has been received and validated, `ask()` will return -an instance of `InputResult`. `InputResult` exposes the method `fetch` to grab the raw input. - -#### Text Input - -The text input will prompt for a string and when the enter key is hit it will validate that -the string is not empty. As well as the style you can modify the prompt text (the default is 'Enter text:'), the -placeholder text (the default is empty) and the validation failed text (the default is 'Invalid, try again'). - -```php -askText() - ->setPromptText('Enter your name') - ->setPlaceholderText('Jane Doe') - ->setValidationFailedText('Please enter your name') - ->ask(); - - var_dump($result->fetch()); -}; - -$menu = (new CliMenuBuilder) - ->setTitle('Basic CLI Menu') - ->addItem('Enter text', $itemCallable) - ->addLineBreak('-') - ->build(); - -$menu->open(); - -``` - -#### Number Input - -The number input will prompt for an integer value (signed or not) and when the enter key is hit it will validate that -the input is actually a number (`/^-?\d+$/`). As well as the style you can modify the prompt text (the default is 'Enter a number:'), the -placeholder text (the default is empty) and the validation failed text (the default is 'Not a valid number, try again'). - -When entering a number you can use the up/down keys to increment and decrement the number. - -```php -askNumber() - ->setPromptText('Enter your age') - ->setPlaceholderText(10) - ->setValidationFailedText('Invalid age, try again') - ->ask(); - - var_dump($result->fetch()); -}; - -$menu = (new CliMenuBuilder) - ->setTitle('Basic CLI Menu') - ->addItem('Enter number', $itemCallable) - ->addLineBreak('-') - ->build(); - -$menu->open(); - -``` - -#### Password Input - -The password input will prompt for a text value and when the enter key is hit it will validate that the input is 16 characters or longer. -As well as the style you can modify the prompt text (the default is 'Enter password:'), the -placeholder text (the default is empty) and the validation failed text (the default is 'Invalid password, try again'). You can also set -a custom password validator as a PHP callable. When typing passwords they are echo'd back to the user as an asterisk. - -Ask for a password with the default validation: - -```php -askPassword() - ->setPromptText('Please enter your password') - ->setValidationFailedText('Invalid password, try again') - ->setPlaceholderText('') - ->ask(); - - var_dump($result->fetch()); -}; - -$menu = (new CliMenuBuilder) - ->setTitle('Basic CLI Menu') - ->addItem('Enter password', $itemCallable) - ->addLineBreak('-') - ->build(); - -$menu->open(); - -``` - -Validators can be any PHP callable. The callable will be passed the input value and must return a boolean, false indicating -validation failure and true indicating validation success. If validation fails then the validation failure text will be shown. - -It is also possible to customise the validation failure message dynamically, but only when using a `Closure` as a validator. -The closure will be binded to the `Password` input class which will allow you to call `setValidationFailedText` inside the closure. - -Ask for a password with custom validation. Here we validate the password is not equal to `password` and that the -password is longer than 20 characters. - -```php -askPassword() - ->setPromptText('Please enter your password') - ->setValidationFailedText('Invalid password, try again') - ->setPlaceholderText('') - ->setValidator(function ($password) { - return $password !== 'password' && strlen($password) > 20; - }) - ->ask(); - - var_dump($result->fetch()); -}; - -$menu = (new CliMenuBuilder) - ->setTitle('Basic CLI Menu') - ->addItem('Enter password', $itemCallable) - ->addLineBreak('-') - ->build(); - -$menu->open(); - -``` - -Ask for a password with custom validation and set the validation failure message dynamically: - -```php -askPassword() - ->setPromptText('Please enter your password') - ->setValidationFailedText('Invalid password, try again') - ->setPlaceholderText('') - ->setValidator(function ($password) { - if ($password === 'password') { - $this->setValidationFailedText('Password is too weak'); - return false; - } else if (strlen($password) <= 20) { - $this->setValidationFailedText('Password is not long enough'); - return false; - } - - return true; - }) - ->ask(); - - var_dump($result->fetch()); -}; - -$menu = (new CliMenuBuilder) - ->setTitle('Basic CLI Menu') - ->addItem('Enter password', $itemCallable) - ->addLineBreak('-') - ->build(); - -$menu->open(); - -``` - -#### Custom Input - -If you need a new type of input which is not covered by the bundled selection then you can create your own by implementing -`\ncc\PhpSchool\CliMenu\Input\Input` - take a look at existing implementations to see how they are built. If all you need is some custom -validation - extend the `\ncc\PhpSchool\CliMenu\Input\Text` class and overwrite the `validate` method. You can then use it in -your menu item actions like so: - -```php -setBg('yellow') - ->setFg('black'); - - $input = new class (new InputIO($menu, $menu->getTerminal()), $style) extends Text { - public function validate(string $value) : bool - { - //some validation - return true; - } - }; - - $result = $input->ask(); - - var_dump($result->fetch()); -}; - -$menu = (new CliMenuBuilder) - ->setTitle('Basic CLI Menu') - ->addItem('Enter password', $itemCallable) - ->addLineBreak('-') - ->build(); - -$menu->open(); - -``` - -### Dialogues & Input Styling - -All of the dialogues and inputs expose a `getStyle()` method which you can use to customise the appearance of them. However, if -you want to create a consistent style for all your dialogues and inputs without configuring it for each one -you can build up a `MenuStyle` object and pass it to the dialogue and input methods like so: - -```php -setBg('green') - ->setFg('magenta'); - -$itemCallable = function (CliMenu $menu) use ($popupStyle) { - $menu->flash("PHP School FTW!!", $popupStyle)->display(); - $menu->confirm('PHP School FTW!', $popupStyle)->display('OK!'); - $menu->askNumber($popupStyle)->ask(); -}; - -$menu = (new CliMenuBuilder) - ->setTitle('Basic CLI Menu') - ->addItem('First Item', $itemCallable) - ->addItem('Second Item', $itemCallable) - ->addItem('Third Item', $itemCallable) - ->addLineBreak('-') - ->build(); - -$menu->open(); -``` - ---- - -Once you get going you might just end up with something that looks a little like this... - -![Learn You PHP CLI Menu](https://cloud.githubusercontent.com/assets/2174476/11409864/be082444-93ba-11e5-84ab-1b6cfa38aef8.png) - -You can see the construction code here for more clarity on how to perform advanced configuration: -[PHP School](https://github.com/php-school/php-workshop/blob/3240d3217bbf62b1063613fc13eb5adff2299bbe/src/Factory/MenuFactory.php) - -## Integrations - - * [Symfony Console](https://github.com/RedAntNL/console) - * [Laravel](https://github.com/nunomaduro/laravel-console-menu) - * [Laravel Artisan](https://github.com/VladReshet/ArtisanUI) diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Style/CheckboxStyle.php b/src/ncc/ThirdParty/php-school/cli-menu/Style/CheckboxStyle.php deleted file mode 100644 index 7eddc90..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Style/CheckboxStyle.php +++ /dev/null @@ -1,119 +0,0 @@ - '[✔] ', - 'uncheckedMarker' => '[ ] ', - 'itemExtra' => '✔', - 'displaysExtra' => false, - ]; - - /** - * @var string - */ - private $checkedMarker; - - /** - * @var string - */ - private $uncheckedMarker; - - /** - * @var string - */ - private $itemExtra; - - /** - * @var bool - */ - private $displaysExtra; - - public function __construct() - { - $this->checkedMarker = self::DEFAULT_STYLES['checkedMarker']; - $this->uncheckedMarker = self::DEFAULT_STYLES['uncheckedMarker']; - $this->itemExtra = self::DEFAULT_STYLES['itemExtra']; - $this->displaysExtra = self::DEFAULT_STYLES['displaysExtra']; - } - - public function hasChangedFromDefaults() : bool - { - $currentValues = [ - $this->checkedMarker, - $this->uncheckedMarker, - $this->itemExtra, - $this->displaysExtra, - ]; - - return $currentValues !== array_values(self::DEFAULT_STYLES); - } - - public function getMarker(MenuItemInterface $item, bool $selected) : string - { - if (!$item instanceof CheckboxItem) { - throw new \InvalidArgumentException( - sprintf('Expected an instance of: %s. Got: %s', CheckboxItem::class, get_class($item)) - ); - } - - return $item->getChecked() ? $this->checkedMarker : $this->uncheckedMarker; - } - - public function getCheckedMarker() : string - { - return $this->checkedMarker; - } - - public function setCheckedMarker(string $marker) : self - { - $this->checkedMarker = $marker; - - return $this; - } - - public function getUncheckedMarker() : string - { - return $this->uncheckedMarker; - } - - public function setUncheckedMarker(string $marker) : self - { - $this->uncheckedMarker = $marker; - - return $this; - } - - public function getItemExtra() : string - { - return $this->itemExtra; - } - - public function setItemExtra(string $itemExtra) : self - { - $this->itemExtra = $itemExtra; - - // if we customise item extra, it means we most likely want to display it - $this->setDisplaysExtra(true); - - return $this; - } - - public function getDisplaysExtra() : bool - { - return $this->displaysExtra; - } - - public function setDisplaysExtra(bool $displaysExtra) : self - { - $this->displaysExtra = $displaysExtra; - - return $this; - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Style/DefaultStyle.php b/src/ncc/ThirdParty/php-school/cli-menu/Style/DefaultStyle.php deleted file mode 100644 index 6ee2ffa..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Style/DefaultStyle.php +++ /dev/null @@ -1,30 +0,0 @@ - DefaultStyle::class, - AsciiArtItem::class => DefaultStyle::class, - LineBreakItem::class => DefaultStyle::class, - SplitItem::class => DefaultStyle::class, - SelectableItem::class => SelectableStyle::class, - MenuMenuItem::class => SelectableStyle::class, - CheckboxItem::class => CheckboxStyle::class, - RadioItem::class => RadioStyle::class, - ]; - - /** - * @var array - */ - private $styles; - - public function __construct() - { - $this->styles = [ - DefaultStyle::class => new DefaultStyle(), - SelectableStyle::class => new SelectableStyle(), - CheckboxStyle::class => new CheckboxStyle(), - RadioStyle::class => new RadioStyle() - ]; - } - - /** - * For each of our unmodified item styles, we replace ours with the versions - * from the given style locator. - * - * @param Locator $other - */ - public function importFrom(self $other) : void - { - $this->styles = mapWithKeys( - $this->styles, - function ($styleClass, ItemStyle $instance) use ($other) { - return $instance->hasChangedFromDefaults() - ? $instance - : $other->getStyle($styleClass); - } - ); - } - - public function getStyle(string $styleClass) : ItemStyle - { - if (!isset($this->styles[$styleClass])) { - throw InvalidStyle::unregisteredStyle($styleClass); - } - - return $this->styles[$styleClass]; - } - - public function setStyle(ItemStyle $itemStyle, string $styleClass) : void - { - if (!isset($this->styles[$styleClass])) { - throw InvalidStyle::unregisteredStyle($styleClass); - } - - if (!$itemStyle instanceof $styleClass) { - throw InvalidStyle::notSubClassOf($styleClass); - } - - $this->styles[$styleClass] = $itemStyle; - } - - public function hasStyleForMenuItem(MenuItemInterface $item) : bool - { - return isset($this->itemStyleMap[get_class($item)]); - } - - public function getStyleForMenuItem(MenuItemInterface $item) : ItemStyle - { - if (!isset($this->itemStyleMap[get_class($item)])) { - throw InvalidStyle::unregisteredItem(get_class($item)); - } - - $styleClass = $this->itemStyleMap[get_class($item)]; - - return $this->getStyle($styleClass); - } - - public function registerItemStyle(string $itemClass, ItemStyle $itemStyle) : void - { - if (isset($this->itemStyleMap[$itemClass])) { - throw InvalidStyle::itemAlreadyRegistered($itemClass); - } - - $this->itemStyleMap[$itemClass] = get_class($itemStyle); - $this->styles[get_class($itemStyle)] = $itemStyle; - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Style/RadioStyle.php b/src/ncc/ThirdParty/php-school/cli-menu/Style/RadioStyle.php deleted file mode 100644 index 030775c..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Style/RadioStyle.php +++ /dev/null @@ -1,119 +0,0 @@ - '[●] ', - 'uncheckedMarker' => '[○] ', - 'itemExtra' => '✔', - 'displaysExtra' => false, - ]; - - /** - * @var string - */ - private $checkedMarker; - - /** - * @var string - */ - private $uncheckedMarker; - - /** - * @var string - */ - private $itemExtra; - - /** - * @var bool - */ - private $displaysExtra; - - public function __construct() - { - $this->checkedMarker = self::DEFAULT_STYLES['checkedMarker']; - $this->uncheckedMarker = self::DEFAULT_STYLES['uncheckedMarker']; - $this->itemExtra = self::DEFAULT_STYLES['itemExtra']; - $this->displaysExtra = self::DEFAULT_STYLES['displaysExtra']; - } - - public function hasChangedFromDefaults() : bool - { - $currentValues = [ - $this->checkedMarker, - $this->uncheckedMarker, - $this->itemExtra, - $this->displaysExtra, - ]; - - return $currentValues !== array_values(self::DEFAULT_STYLES); - } - - public function getMarker(MenuItemInterface $item, bool $selected) : string - { - if (!$item instanceof RadioItem) { - throw new \InvalidArgumentException( - sprintf('Expected an instance of: %s. Got: %s', RadioItem::class, get_class($item)) - ); - } - - return $item->getChecked() ? $this->checkedMarker : $this->uncheckedMarker; - } - - public function getCheckedMarker() : string - { - return $this->checkedMarker; - } - - public function setCheckedMarker(string $marker) : self - { - $this->checkedMarker = $marker; - - return $this; - } - - public function getUncheckedMarker() : string - { - return $this->uncheckedMarker; - } - - public function setUncheckedMarker(string $marker) : self - { - $this->uncheckedMarker = $marker; - - return $this; - } - - public function getItemExtra() : string - { - return $this->itemExtra; - } - - public function setItemExtra(string $itemExtra) : self - { - $this->itemExtra = $itemExtra; - - // if we customise item extra, it means we most likely want to display it - $this->setDisplaysExtra(true); - - return $this; - } - - public function getDisplaysExtra() : bool - { - return $this->displaysExtra; - } - - public function setDisplaysExtra(bool $displaysExtra) : self - { - $this->displaysExtra = $displaysExtra; - - return $this; - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Style/SelectableStyle.php b/src/ncc/ThirdParty/php-school/cli-menu/Style/SelectableStyle.php deleted file mode 100644 index cf3fd25..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Style/SelectableStyle.php +++ /dev/null @@ -1,112 +0,0 @@ - '● ', - 'unselectedMarker' => '○ ', - 'itemExtra' => '✔', - 'displaysExtra' => false, - ]; - - /** - * @var string - */ - private $selectedMarker; - - /** - * @var string - */ - private $unselectedMarker; - - /** - * @var string - */ - private $itemExtra; - - /** - * @var bool - */ - private $displaysExtra; - - public function __construct() - { - $this->selectedMarker = self::DEFAULT_STYLES['selectedMarker']; - $this->unselectedMarker = self::DEFAULT_STYLES['unselectedMarker']; - $this->itemExtra = self::DEFAULT_STYLES['itemExtra']; - $this->displaysExtra = self::DEFAULT_STYLES['displaysExtra']; - } - - public function hasChangedFromDefaults() : bool - { - $currentValues = [ - $this->selectedMarker, - $this->unselectedMarker, - $this->itemExtra, - $this->displaysExtra, - ]; - - return $currentValues !== array_values(self::DEFAULT_STYLES); - } - - public function getMarker(MenuItemInterface $item, bool $selected) : string - { - return $selected ? $this->selectedMarker : $this->unselectedMarker; - } - - public function getSelectedMarker() : string - { - return $this->selectedMarker; - } - - public function setSelectedMarker(string $marker) : self - { - $this->selectedMarker = $marker; - - return $this; - } - - public function getUnselectedMarker() : string - { - return $this->unselectedMarker; - } - - public function setUnselectedMarker(string $marker) : self - { - $this->unselectedMarker = $marker; - - return $this; - } - - public function getItemExtra() : string - { - return $this->itemExtra; - } - - public function setItemExtra(string $itemExtra) : self - { - $this->itemExtra = $itemExtra; - - // if we customise item extra, it means we most likely want to display it - $this->setDisplaysExtra(true); - - return $this; - } - - public function getDisplaysExtra() : bool - { - return $this->displaysExtra; - } - - public function setDisplaysExtra(bool $displaysExtra) : self - { - $this->displaysExtra = $displaysExtra; - - return $this; - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Terminal/TerminalFactory.php b/src/ncc/ThirdParty/php-school/cli-menu/Terminal/TerminalFactory.php deleted file mode 100644 index 482a2c6..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Terminal/TerminalFactory.php +++ /dev/null @@ -1,20 +0,0 @@ - - */ -class TerminalFactory -{ - public static function fromSystem() : Terminal - { - return new UnixTerminal(new ResourceInputStream, new ResourceOutputStream); - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/UPGRADE.md b/src/ncc/ThirdParty/php-school/cli-menu/UPGRADE.md deleted file mode 100644 index 0eb9ab7..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/UPGRADE.md +++ /dev/null @@ -1,113 +0,0 @@ -# Upgrade Documentation - -This document serves as a reference to upgrade your current cli-menu installation if improvements, deprecations -or backwards compatibility (BC) breakages occur. - -## 4.0.0 - -### BC breaks - -* Trait `ncc\PhpSchool\CliMenu\MenuItem\SelectableTrait` was removed. Copy the old code into your menu item - if you need it. -* Methods `ncc\PhpSchool\CliMenu\Builder\CliMenuBuilder#setUnselectedMarker()` & `ncc\PhpSchool\CliMenu\Builder\CliMenuBuilder#setSelectedMarker()` were removed. - Customise markers on the individual item styles: - - ```php - modifySelectableStyle(function (SelectableStyle $style) { - $style->setUnselectedMarker('❅ ') - ->setSelectedMarker('✏ ') - - // disable unselected marker - ->setUnselectedMarker('') - ; - }) - ->build(); - ``` -* Method getStyle() was added to interface ncc\PhpSchool\CliMenu\MenuItem\MenuItemInterface. Items must now implement this - method. For selectable items use `\ncc\PhpSchool\CliMenu\Style\SelectableStyle` or a subclass of. For static items use - `\ncc\PhpSchool\CliMenu\Style\DefaultStyle` or a subclass of. -* `ncc\PhpSchool\CliMenu\MenuStyle` marker methods have been removed. If you were using these directly. Operate on the item - style object instead. - -## 3.0.0 - -### BC breaks - -* Class `ncc\PhpSchool\CliMenu\CliMenuBuilder` has been moved, use - `ncc\PhpSchool\CliMenu\Builder\CliMenuBuilder` instead. Please migrate to the new namespace. -* `ncc\PhpSchool\CliMenu\Builder\CliMenuBuilder#addSubMenu` now takes a text and a closure used to configure the submenu. The callback - invoked with a new instance of `ncc\PhpSchool\CliMenu\Builder\CliMenuBuilder` as a parameter. `addSubMenu` now returns itself instead of - the sub menu `ncc\PhpSchool\CliMenu\Builder\CliMenuBuilder`. See below for upgrade example. -* Removed `ncc\PhpSchool\CliMenu\Terminal` namespace, the code has been migrated to the `php-school/terminal` package and is - largely modified. -* Removed methods `setTerminal`, `getSubMenu`, `getMenuStyle` and `end` from `ncc\PhpSchool\CliMenu\CliMenuBuilder`. -* Removed static method `getDefaultStyleValues` on `ncc\PhpSchool\CliMenu\MenuStyle`. - - -#### Migrating to new `addSubMenu` method in `CliMenuBuilder` - -Previous code: - -```php -getSelectedItem()->getText(); -}; - -$menu = (new CliMenuBuilder) - ->setTitle('CLI Menu') - ->addItem('First Item', $itemCallable) - ->addLineBreak('-') - ->addSubMenu('Options') - ->setTitle('CLI Menu > Options') - ->addItem('First option', function (CliMenu $menu) { - echo sprintf('Executing option: %s', $menu->getSelectedItem()->getText()); - }) - ->addLineBreak('-') - ->end() - ->build(); - -$menu->open(); -``` - -Would now become: - -```php -getSelectedItem()->getText(); -}; - -$menu = (new CliMenuBuilder) - ->setTitle('CLI Menu') - ->addItem('First Item', $itemCallable) - ->addLineBreak('-') - ->addSubMenu('Options', function (CliMenuBuilder $b) { - $b->setTitle('CLI Menu > Options') - ->addItem('First option', function (CliMenu $menu) { - echo sprintf('Executing option: %s', $menu->getSelectedItem()->getText()); - }) - ->addLineBreak('-'); - }) - ->build(); - -$menu->open(); -``` diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Util/ArrayUtils.php b/src/ncc/ThirdParty/php-school/cli-menu/Util/ArrayUtils.php deleted file mode 100644 index 5c035fd..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Util/ArrayUtils.php +++ /dev/null @@ -1,41 +0,0 @@ - $v) { - $callback($k, $v); - } -} - -function max(array $items) : int -{ - return count($items) > 0 ? \max($items) : 0; -} - -function collect(array $items) : Collection -{ - return new Collection($items); -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Util/Collection.php b/src/ncc/ThirdParty/php-school/cli-menu/Util/Collection.php deleted file mode 100644 index 1901837..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Util/Collection.php +++ /dev/null @@ -1,45 +0,0 @@ -items = $items; - } - - public function map(callable $cb) : self - { - return new self(mapWithKeys($this->items, $cb)); - } - - public function filter(callable $cb) : self - { - return new self(filter($this->items, $cb)); - } - - public function values() : self - { - return new self(array_values($this->items)); - } - - public function each(callable $cb) : self - { - each($this->items, $cb); - - return $this; - } - - public function all() : array - { - return $this->items; - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Util/ColourUtil.php b/src/ncc/ThirdParty/php-school/cli-menu/Util/ColourUtil.php deleted file mode 100644 index fe11874..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Util/ColourUtil.php +++ /dev/null @@ -1,334 +0,0 @@ - 'black', - 1 => 'red', - 2 => 'green', - 3 => 'yellow', - 4 => 'blue', - 5 => 'magenta', - 6 => 'cyan', - 7 => 'white', - 8 => 'black', - 9 => 'red', - 10 => 'green', - 11 => 'yellow', - 12 => 'blue', - 13 => 'magenta', - 14 => 'cyan', - 15 => 'white', - 16 => 'black', - 17 => 'blue', - 18 => 'blue', - 19 => 'blue', - 20 => 'blue', - 21 => 'blue', - 22 => 'green', - 23 => 'cyan', - 24 => 'cyan', - 25 => 'blue', - 26 => 'blue', - 27 => 'blue', - 28 => 'green', - 29 => 'green', - 30 => 'cyan', - 31 => 'cyan', - 32 => 'blue', - 33 => 'blue', - 34 => 'green', - 35 => 'green', - 36 => 'green', - 37 => 'cyan', - 38 => 'cyan', - 39 => 'cyan', - 40 => 'green', - 41 => 'green', - 42 => 'green', - 43 => 'cyan', - 44 => 'cyan', - 45 => 'cyan', - 46 => 'green', - 47 => 'green', - 48 => 'green', - 49 => 'green', - 50 => 'cyan', - 51 => 'cyan', - 52 => 'red', - 53 => 'blue', - 54 => 'blue', - 55 => 'blue', - 56 => 'blue', - 57 => 'blue', - 58 => 'yellow', - 59 => 'black', - 60 => 'blue', - 61 => 'blue', - 62 => 'blue', - 63 => 'blue', - 64 => 'green', - 65 => 'green', - 66 => 'cyan', - 67 => 'cyan', - 68 => 'blue', - 69 => 'blue', - 70 => 'green', - 71 => 'green', - 72 => 'green', - 73 => 'cyan', - 74 => 'cyan', - 75 => 'cyan', - 76 => 'green', - 77 => 'green', - 78 => 'green', - 79 => 'green', - 80 => 'cyan', - 81 => 'cyan', - 82 => 'green', - 83 => 'green', - 84 => 'green', - 85 => 'green', - 86 => 'cyan', - 87 => 'cyan', - 88 => 'red', - 89 => 'magenta', - 90 => 'magenta', - 91 => 'magenta', - 92 => 'blue', - 93 => 'blue', - 94 => 'yellow', - 95 => 'red', - 96 => 'magenta', - 97 => 'magenta', - 98 => 'blue', - 99 => 'blue', - 100 => 'yellow', - 101 => 'yellow', - 102 => 'white', - 103 => 'blue', - 104 => 'blue', - 105 => 'blue', - 106 => 'green', - 107 => 'green', - 108 => 'green', - 109 => 'cyan', - 110 => 'cyan', - 111 => 'cyan', - 112 => 'green', - 113 => 'green', - 114 => 'green', - 115 => 'green', - 116 => 'cyan', - 117 => 'cyan', - 118 => 'green', - 119 => 'green', - 120 => 'green', - 121 => 'green', - 122 => 'green', - 123 => 'cyan', - 124 => 'red', - 125 => 'magenta', - 126 => 'magenta', - 127 => 'magenta', - 128 => 'magenta', - 129 => 'magenta', - 130 => 'red', - 131 => 'red', - 132 => 'magenta', - 133 => 'magenta', - 134 => 'magenta', - 135 => 'magenta', - 136 => 'yellow', - 137 => 'red', - 138 => 'red', - 139 => 'magenta', - 140 => 'magenta', - 141 => 'magenta', - 142 => 'yellow', - 143 => 'yellow', - 144 => 'yellow', - 145 => 'white', - 146 => 'white', - 147 => 'white', - 148 => 'yellow', - 149 => 'green', - 150 => 'green', - 151 => 'green', - 152 => 'cyan', - 153 => 'white', - 154 => 'green', - 155 => 'green', - 156 => 'green', - 157 => 'green', - 158 => 'green', - 159 => 'cyan', - 160 => 'red', - 161 => 'magenta', - 162 => 'magenta', - 163 => 'magenta', - 164 => 'magenta', - 165 => 'magenta', - 166 => 'red', - 167 => 'red', - 168 => 'magenta', - 169 => 'magenta', - 170 => 'magenta', - 171 => 'magenta', - 172 => 'red', - 173 => 'red', - 174 => 'red', - 175 => 'magenta', - 176 => 'magenta', - 177 => 'magenta', - 178 => 'yellow', - 179 => 'yellow', - 180 => 'white', - 181 => 'white', - 182 => 'magenta', - 183 => 'magenta', - 184 => 'yellow', - 185 => 'yellow', - 186 => 'yellow', - 187 => 'yellow', - 188 => 'white', - 189 => 'white', - 190 => 'yellow', - 191 => 'yellow', - 192 => 'green', - 193 => 'green', - 194 => 'green', - 195 => 'cyan', - 196 => 'red', - 197 => 'red', - 198 => 'magenta', - 199 => 'magenta', - 200 => 'magenta', - 201 => 'magenta', - 202 => 'red', - 203 => 'red', - 204 => 'magenta', - 205 => 'magenta', - 206 => 'magenta', - 207 => 'magenta', - 208 => 'red', - 209 => 'red', - 210 => 'red', - 211 => 'magenta', - 212 => 'magenta', - 213 => 'magenta', - 214 => 'red', - 215 => 'white', - 216 => 'red', - 217 => 'red', - 218 => 'magenta', - 219 => 'magenta', - 220 => 'yellow', - 221 => 'yellow', - 222 => 'yellow', - 223 => 'white', - 224 => 'white', - 225 => 'magenta', - 226 => 'yellow', - 227 => 'yellow', - 228 => 'yellow', - 229 => 'yellow', - 230 => 'yellow', - 231 => 'white', - 232 => 'black', - 233 => 'black', - 234 => 'black', - 235 => 'black', - 236 => 'black', - 237 => 'black', - 238 => 'black', - 239 => 'black', - 240 => 'black', - 241 => 'black', - 242 => 'black', - 243 => 'black', - 244 => 'white', - 245 => 'white', - 246 => 'white', - 247 => 'white', - 248 => 'white', - 249 => 'white', - 250 => 'white', - 251 => 'white', - 252 => 'white', - 253 => 'white', - 254 => 'white', - 255 => 'white', - ]; - - public static function getDefaultColourNames() : array - { - return self::$defaultColoursNames; - } - - /** - * Simple function to transform a 8-bit (256 colours) colour code - * to one of the default 8 colors available in the terminal - */ - public static function map256To8(int $colourCode) : string - { - if (!isset(self::$coloursMap[$colourCode])) { - throw new \InvalidArgumentException('Invalid colour code'); - } - - return self::$coloursMap[$colourCode]; - } - - /** - * Check if $colour exists - * If it's a 256-colours code and $terminal doesn't support it, returns a fallback value - */ - public static function validateColour(Terminal $terminal, string $colour, string $fallback = null) : string - { - if (!ctype_digit($colour)) { - return self::validateColourName($colour); - } - - Assertion::between($colour, 0, 255, 'Invalid colour code'); - - if ($terminal->getColourSupport() >= 256) { - return $colour; - } - - if ($fallback !== null) { - return self::validateColourName($fallback); - } - - return static::map256To8((int) $colour); - } - - private static function validateColourName(string $colourName) : string - { - Assertion::inArray($colourName, static::getDefaultColourNames()); - return $colourName; - } -} diff --git a/src/ncc/ThirdParty/php-school/cli-menu/Util/StringUtil.php b/src/ncc/ThirdParty/php-school/cli-menu/Util/StringUtil.php deleted file mode 100644 index 7e9942e..0000000 --- a/src/ncc/ThirdParty/php-school/cli-menu/Util/StringUtil.php +++ /dev/null @@ -1,52 +0,0 @@ - - */ -class StringUtil -{ - /** - * Minimal multi-byte wordwrap implementation - * which also takes break length into consideration - */ - public static function wordwrap(string $string, int $width, string $break = "\n") : string - { - return implode( - $break, - array_map(function (string $line) use ($width, $break) { - $line = rtrim($line); - if (mb_strlen($line) <= $width) { - return $line; - } - - $words = explode(' ', $line); - $line = ''; - $actual = ''; - foreach ($words as $word) { - if (mb_strlen($actual . $word) <= $width) { - $actual .= $word . ' '; - } else { - if ($actual !== '') { - $line .= rtrim($actual) . $break; - } - $actual = $word . ' '; - } - } - return $line . trim($actual); - }, explode("\n", $string)) - ); - } - - public static function stripAnsiEscapeSequence(string $str) : string - { - return (string) preg_replace('/\x1b[^m]*m/', '', $str); - } - - public static function length(string $str, bool $ignoreAnsiEscapeSequence = true) : int - { - return mb_strlen($ignoreAnsiEscapeSequence ? self::stripAnsiEscapeSequence($str) : $str); - } -} diff --git a/src/ncc/ThirdParty/php-school/terminal/Exception/NotInteractiveTerminal.php b/src/ncc/ThirdParty/php-school/terminal/Exception/NotInteractiveTerminal.php deleted file mode 100644 index 2ee2f9b..0000000 --- a/src/ncc/ThirdParty/php-school/terminal/Exception/NotInteractiveTerminal.php +++ /dev/null @@ -1,19 +0,0 @@ - - */ -class NotInteractiveTerminal extends \RuntimeException -{ - public static function inputNotInteractive() : self - { - return new self('Input stream is not interactive (non TTY)'); - } - - public static function outputNotInteractive() : self - { - return new self('Output stream is not interactive (non TTY)'); - } -} diff --git a/src/ncc/ThirdParty/php-school/terminal/IO/BufferedOutput.php b/src/ncc/ThirdParty/php-school/terminal/IO/BufferedOutput.php deleted file mode 100644 index f51da9c..0000000 --- a/src/ncc/ThirdParty/php-school/terminal/IO/BufferedOutput.php +++ /dev/null @@ -1,40 +0,0 @@ - - */ -class BufferedOutput implements OutputStream -{ - private $buffer = ''; - - public function write(string $buffer): void - { - $this->buffer .= $buffer; - } - - public function fetch(bool $clean = true) : string - { - $buffer = $this->buffer; - - if ($clean) { - $this->buffer = ''; - } - - return $buffer; - } - - public function __toString() : string - { - return $this->fetch(); - } - - /** - * Whether the stream is connected to an interactive terminal - */ - public function isInteractive() : bool - { - return false; - } -} diff --git a/src/ncc/ThirdParty/php-school/terminal/IO/InputStream.php b/src/ncc/ThirdParty/php-school/terminal/IO/InputStream.php deleted file mode 100644 index f2d6f00..0000000 --- a/src/ncc/ThirdParty/php-school/terminal/IO/InputStream.php +++ /dev/null @@ -1,20 +0,0 @@ - - */ -interface InputStream -{ - /** - * Callback should be called with the number of bytes requested - * when ready. - */ - public function read(int $numBytes, callable $callback) : void; - - /** - * Whether the stream is connected to an interactive terminal - */ - public function isInteractive() : bool; -} diff --git a/src/ncc/ThirdParty/php-school/terminal/IO/OutputStream.php b/src/ncc/ThirdParty/php-school/terminal/IO/OutputStream.php deleted file mode 100644 index 9447b4b..0000000 --- a/src/ncc/ThirdParty/php-school/terminal/IO/OutputStream.php +++ /dev/null @@ -1,19 +0,0 @@ - - */ -interface OutputStream -{ - /** - * Write the buffer to the stream - */ - public function write(string $buffer) : void; - - /** - * Whether the stream is connected to an interactive terminal - */ - public function isInteractive() : bool; -} diff --git a/src/ncc/ThirdParty/php-school/terminal/IO/ResourceInputStream.php b/src/ncc/ThirdParty/php-school/terminal/IO/ResourceInputStream.php deleted file mode 100644 index 4c94d75..0000000 --- a/src/ncc/ThirdParty/php-school/terminal/IO/ResourceInputStream.php +++ /dev/null @@ -1,47 +0,0 @@ - - */ -class ResourceInputStream implements InputStream -{ - /** - * @var resource - */ - private $stream; - - public function __construct($stream = STDIN) - { - if (!is_resource($stream) || get_resource_type($stream) !== 'stream') { - throw new \InvalidArgumentException('Expected a valid stream'); - } - - $meta = stream_get_meta_data($stream); - if (strpos($meta['mode'], 'r') === false && strpos($meta['mode'], '+') === false) { - throw new \InvalidArgumentException('Expected a readable stream'); - } - - $this->stream = $stream; - } - - public function read(int $numBytes, callable $callback) : void - { - $buffer = fread($this->stream, $numBytes); - $callback($buffer); - } - - /** - * Whether the stream is connected to an interactive terminal - */ - public function isInteractive() : bool - { - return posix_isatty($this->stream); - } -} diff --git a/src/ncc/ThirdParty/php-school/terminal/IO/ResourceOutputStream.php b/src/ncc/ThirdParty/php-school/terminal/IO/ResourceOutputStream.php deleted file mode 100644 index 4382f45..0000000 --- a/src/ncc/ThirdParty/php-school/terminal/IO/ResourceOutputStream.php +++ /dev/null @@ -1,46 +0,0 @@ - - */ -class ResourceOutputStream implements OutputStream -{ - /** - * @var resource - */ - private $stream; - - public function __construct($stream = STDOUT) - { - if (!is_resource($stream) || get_resource_type($stream) !== 'stream') { - throw new \InvalidArgumentException('Expected a valid stream'); - } - - $meta = stream_get_meta_data($stream); - if (strpos($meta['mode'], 'r') !== false && strpos($meta['mode'], '+') === false) { - throw new \InvalidArgumentException('Expected a writable stream'); - } - - $this->stream = $stream; - } - - public function write(string $buffer): void - { - fwrite($this->stream, $buffer); - } - - /** - * Whether the stream is connected to an interactive terminal - */ - public function isInteractive() : bool - { - return posix_isatty($this->stream); - } -} diff --git a/src/ncc/ThirdParty/php-school/terminal/InputCharacter.php b/src/ncc/ThirdParty/php-school/terminal/InputCharacter.php deleted file mode 100644 index 53d4ddb..0000000 --- a/src/ncc/ThirdParty/php-school/terminal/InputCharacter.php +++ /dev/null @@ -1,137 +0,0 @@ - - */ -class InputCharacter -{ - /** - * @var string - */ - private $data; - - public const UP = 'UP'; - public const DOWN = 'DOWN'; - public const RIGHT = 'RIGHT'; - public const LEFT = 'LEFT'; - public const CTRLA = 'CTRLA'; - public const CTRLB = 'CTRLB'; - public const CTRLE = 'CTRLE'; - public const CTRLF = 'CTRLF'; - public const BACKSPACE = 'BACKSPACE'; - public const CTRLW = 'CTRLW'; - public const ENTER = 'ENTER'; - public const TAB = 'TAB'; - public const ESC = 'ESC'; - - private static $controls = [ - "\033[A" => self::UP, - "\033[B" => self::DOWN, - "\033[C" => self::RIGHT, - "\033[D" => self::LEFT, - "\033OA" => self::UP, - "\033OB" => self::DOWN, - "\033OC" => self::RIGHT, - "\033OD" => self::LEFT, - "\001" => self::CTRLA, - "\002" => self::CTRLB, - "\005" => self::CTRLE, - "\006" => self::CTRLF, - "\010" => self::BACKSPACE, - "\177" => self::BACKSPACE, - "\027" => self::CTRLW, - "\n" => self::ENTER, - "\t" => self::TAB, - "\e" => self::ESC, - ]; - - public function __construct(string $data) - { - $this->data = $data; - } - - public function isHandledControl() : bool - { - return isset(static::$controls[$this->data]); - } - - /** - * Is this character a control sequence? - */ - public function isControl() : bool - { - return preg_match('/[\x00-\x1F\x7F]/', $this->data); - } - - /** - * Is this character a normal character? - */ - public function isNotControl() : bool - { - return ! $this->isControl(); - } - - /** - * Get the raw character or control sequence - */ - public function get() : string - { - return $this->data; - } - - /** - * Get the actual control name that this sequence represents. - * One of the class constants. Eg. self::UP. - * - * Throws an exception if the character is not actually a control sequence - */ - public function getControl() : string - { - if (!isset(static::$controls[$this->data])) { - throw new \RuntimeException(sprintf('Character "%s" is not a control', $this->data)); - } - - return static::$controls[$this->data]; - } - - /** - * Get the raw character or control sequence - */ - public function __toString() : string - { - return $this->get(); - } - - /** - * Does the given control name exist? eg self::UP. - */ - public static function controlExists(string $controlName) : bool - { - return in_array($controlName, static::$controls, true); - } - - /** - * Get all of the available control names - */ - public static function getControls() : array - { - return array_values(array_unique(static::$controls)); - } - - /** - * Create a instance from a given control name. Throws an exception if the - * control name does not exist. - */ - public static function fromControlName(string $controlName) : self - { - if (!static::controlExists($controlName)) { - throw new \InvalidArgumentException(sprintf('Control "%s" does not exist', $controlName)); - } - - return new static(array_search($controlName, static::$controls, true)); - } -} diff --git a/src/ncc/ThirdParty/php-school/terminal/NonCanonicalReader.php b/src/ncc/ThirdParty/php-school/terminal/NonCanonicalReader.php deleted file mode 100644 index 1667064..0000000 --- a/src/ncc/ThirdParty/php-school/terminal/NonCanonicalReader.php +++ /dev/null @@ -1,79 +0,0 @@ - - */ -class NonCanonicalReader -{ - /** - * @var Terminal - */ - private $terminal; - - /** - * @var bool - */ - private $wasCanonicalModeEnabled; - - /** - * Map of characters to controls. - * Eg map 'w' to the up control. - * - * @var array - */ - private $mappings = []; - - public function __construct(Terminal $terminal) - { - $this->terminal = $terminal; - $this->wasCanonicalModeEnabled = $terminal->isCanonicalMode(); - $this->terminal->disableCanonicalMode(); - } - - public function addControlMapping(string $character, string $mapToControl) : void - { - if (!InputCharacter::controlExists($mapToControl)) { - throw new \InvalidArgumentException(sprintf('Control "%s" does not exist', $mapToControl)); - } - - $this->mappings[$character] = $mapToControl; - } - - public function addControlMappings(array $mappings) : void - { - foreach ($mappings as $character => $mapToControl) { - $this->addControlMapping($character, $mapToControl); - } - } - - /** - * This should be ran with the terminal canonical mode disabled. - * - * @return InputCharacter - */ - public function readCharacter() : InputCharacter - { - $char = $this->terminal->read(4); - - if (isset($this->mappings[$char])) { - return InputCharacter::fromControlName($this->mappings[$char]); - } - - return new InputCharacter($char); - } - - public function __destruct() - { - if ($this->wasCanonicalModeEnabled) { - $this->terminal->enableCanonicalMode(); - } - } -} diff --git a/src/ncc/ThirdParty/php-school/terminal/README.md b/src/ncc/ThirdParty/php-school/terminal/README.md deleted file mode 100644 index 9e6372a..0000000 --- a/src/ncc/ThirdParty/php-school/terminal/README.md +++ /dev/null @@ -1,32 +0,0 @@ -

Terminal Utility

- -

- Small utility to help provide a simple, consise API for terminal interaction -

- -

- - - - - - - - - - - - -

- ---- - -## Install - -```bash -composer require php-school/terminal -``` - -## TODO - -- [ ] Docs diff --git a/src/ncc/ThirdParty/php-school/terminal/Terminal.php b/src/ncc/ThirdParty/php-school/terminal/Terminal.php deleted file mode 100644 index d0cfc34..0000000 --- a/src/ncc/ThirdParty/php-school/terminal/Terminal.php +++ /dev/null @@ -1,133 +0,0 @@ - - * @author Aydin Hassan - */ -interface Terminal -{ - /** - * Get the available width of the terminal - */ - public function getWidth() : int; - - /** - * Get the available height of the terminal - */ - public function getHeight() : int; - - /** - * Get the number of colours the terminal supports (1, 8, 256, true colours) - */ - public function getColourSupport() : int; - - /** - * Disables echoing every character back to the terminal. This means - * we do not have to clear the line when reading. - */ - public function disableEchoBack() : void; - - /** - * Enable echoing back every character input to the terminal. - */ - public function enableEchoBack() : void; - - /** - * Is echo back mode enabled - */ - public function isEchoBack() : bool; - - /** - * Disable canonical input (allow each key press for reading, rather than the whole line) - * - * @see https://www.gnu.org/software/libc/manual/html_node/Canonical-or-Not.html - */ - public function disableCanonicalMode() : void; - - /** - * Enable canonical input - read input by line - * - * @see https://www.gnu.org/software/libc/manual/html_node/Canonical-or-Not.html - */ - public function enableCanonicalMode() : void; - - /** - * Is canonical mode enabled or not - */ - public function isCanonicalMode() : bool; - - /** - * Check if the Input & Output streams are interactive. Eg - they are - * connected to a terminal. - * - * @return bool - */ - public function isInteractive() : bool; - - /** - * Restore the terminals original configuration - */ - public function restoreOriginalConfiguration() : void; - - /** - * Test whether terminal supports colour output - */ - public function supportsColour() : bool; - - /** - * Clear the terminal window - */ - public function clear() : void; - - /** - * Clear the current cursors line - */ - public function clearLine() : void; - - /** - * Erase screen from the current line down to the bottom of the screen - */ - public function clearDown() : void; - - /** - * Clean the whole console without jumping the window - */ - public function clean() : void; - - /** - * Enable cursor display - */ - public function enableCursor() : void; - - /** - * Disable cursor display - */ - public function disableCursor() : void; - - /** - * Move the cursor to the top left of the window - */ - public function moveCursorToTop() : void; - - /** - * Move the cursor to the start of a specific row - */ - public function moveCursorToRow(int $rowNumber) : void; - - /** - * Move the cursor to a specific column - */ - public function moveCursorToColumn(int $columnNumber) : void; - - /** - * Read from the input stream - */ - public function read(int $bytes) : string; - - /** - * Write to the output stream - */ - public function write(string $buffer) : void; -} diff --git a/src/ncc/ThirdParty/php-school/terminal/UnixTerminal.php b/src/ncc/ThirdParty/php-school/terminal/UnixTerminal.php deleted file mode 100644 index 870cd6b..0000000 --- a/src/ncc/ThirdParty/php-school/terminal/UnixTerminal.php +++ /dev/null @@ -1,287 +0,0 @@ - - * @author Aydin Hassan - */ -class UnixTerminal implements Terminal -{ - /** - * @var bool - */ - private $isCanonical; - - /** - * Whether terminal echo back is enabled or not. - * Eg. user key presses and the terminal immediately shows it. - * - * @var bool - */ - private $echoBack = true; - - /** - * @var int - */ - private $width; - - /** - * @var int - */ - private $height; - - /** - * @var int; - */ - private $colourSupport; - - /** - * @var string - */ - private $originalConfiguration; - - /** - * @var InputStream - */ - private $input; - - /** - * @var OutputStream - */ - private $output; - - public function __construct(InputStream $input, OutputStream $output) - { - $this->getOriginalConfiguration(); - $this->getOriginalCanonicalMode(); - $this->input = $input; - $this->output = $output; - } - - private function getOriginalCanonicalMode() : void - { - exec('stty -a', $output); - $this->isCanonical = (strpos(implode("\n", $output), ' icanon') !== false); - } - - public function getWidth() : int - { - return $this->width ?: $this->width = (int) exec('tput cols'); - } - - public function getHeight() : int - { - return $this->height ?: $this->height = (int) exec('tput lines'); - } - - public function getColourSupport() : int - { - return $this->colourSupport ?: $this->colourSupport = (int) exec('tput colors'); - } - - private function getOriginalConfiguration() : string - { - return $this->originalConfiguration ?: $this->originalConfiguration = exec('stty -g'); - } - - /** - * Disables echoing every character back to the terminal. This means - * we do not have to clear the line when reading. - */ - public function disableEchoBack() : void - { - exec('stty -echo'); - $this->echoBack = false; - } - - /** - * Enable echoing back every character input to the terminal. - */ - public function enableEchoBack() : void - { - exec('stty echo'); - $this->echoBack = true; - } - - /** - * Is echo back mode enabled - */ - public function isEchoBack() : bool - { - return $this->echoBack; - } - - /** - * Disable canonical input (allow each key press for reading, rather than the whole line) - * - * @see https://www.gnu.org/software/libc/manual/html_node/Canonical-or-Not.html - */ - public function disableCanonicalMode() : void - { - if ($this->isCanonical) { - exec('stty -icanon'); - $this->isCanonical = false; - } - } - - /** - * Enable canonical input - read input by line - * - * @see https://www.gnu.org/software/libc/manual/html_node/Canonical-or-Not.html - */ - public function enableCanonicalMode() : void - { - if (!$this->isCanonical) { - exec('stty icanon'); - $this->isCanonical = true; - } - } - - /** - * Is canonical mode enabled or not - */ - public function isCanonicalMode() : bool - { - return $this->isCanonical; - } - - /** - * Restore the original terminal configuration - */ - public function restoreOriginalConfiguration() : void - { - exec('stty ' . $this->getOriginalConfiguration()); - } - - /** - * Check if the Input & Output streams are interactive. Eg - they are - * connected to a terminal. - * - * @return bool - */ - public function isInteractive() : bool - { - return $this->input->isInteractive() && $this->output->isInteractive(); - } - - /** - * Assert that both the Input & Output streams are interactive. Throw - * `NotInteractiveTerminal` if not. - */ - public function mustBeInteractive() : void - { - if (!$this->input->isInteractive()) { - throw NotInteractiveTerminal::inputNotInteractive(); - } - - if (!$this->output->isInteractive()) { - throw NotInteractiveTerminal::outputNotInteractive(); - } - } - - /** - * @see https://github.com/symfony/Console/blob/master/Output/StreamOutput.php#L95-L102 - */ - public function supportsColour() : bool - { - if (DIRECTORY_SEPARATOR === '\\') { - return false !== getenv('ANSICON') || 'ON' === getenv('ConEmuANSI') || 'xterm' === getenv('TERM'); - } - - return $this->isInteractive(); - } - - public function clear() : void - { - $this->output->write("\033[2J"); - } - - public function clearLine() : void - { - $this->output->write("\033[2K"); - } - - /** - * Erase screen from the current line down to the bottom of the screen - */ - public function clearDown() : void - { - $this->output->write("\033[J"); - } - - public function clean() : void - { - foreach (range(0, $this->getHeight()) as $rowNum) { - $this->moveCursorToRow($rowNum); - $this->clearLine(); - } - } - - public function enableCursor() : void - { - $this->output->write("\033[?25h"); - } - - public function disableCursor() : void - { - $this->output->write("\033[?25l"); - } - - public function moveCursorToTop() : void - { - $this->output->write("\033[H"); - } - - public function moveCursorToRow(int $rowNumber) : void - { - $this->output->write(sprintf("\033[%d;0H", $rowNumber)); - } - - public function moveCursorToColumn(int $column) : void - { - $this->output->write(sprintf("\033[%dC", $column)); - } - - public function showSecondaryScreen() : void - { - $this->output->write("\033[?47h"); - } - - public function showPrimaryScreen() : void - { - $this->output->write("\033[?47l"); - } - - /** - * Read bytes from the input stream - */ - public function read(int $bytes): string - { - $buffer = ''; - $this->input->read($bytes, function ($data) use (&$buffer) { - $buffer .= $data; - }); - return $buffer; - } - - /** - * Write to the output stream - */ - public function write(string $buffer): void - { - $this->output->write($buffer); - } - - /** - * Restore the original terminal configuration on shutdown. - */ - public function __destruct() - { - $this->restoreOriginalConfiguration(); - } -} diff --git a/src/ncc/autoload.php b/src/ncc/autoload.php index 7ac6bd5..1ecdbcd 100644 --- a/src/ncc/autoload.php +++ b/src/ncc/autoload.php @@ -13,13 +13,6 @@ spl_autoload_register( 'ncc\\abstracts\\regexpatterns' => '/Abstracts/RegexPatterns.php', 'ncc\\abstracts\\scopes' => '/Abstracts/Scopes.php', 'ncc\\abstracts\\stringpaddingmethod' => '/Abstracts/StringPaddingMethod.php', - 'ncc\\assert\\assert' => '/ThirdParty/beberlei/assert/Assert.php', - 'ncc\\assert\\assertion' => '/ThirdParty/beberlei/assert/Assertion.php', - 'ncc\\assert\\assertionchain' => '/ThirdParty/beberlei/assert/AssertionChain.php', - 'ncc\\assert\\assertionfailedexception' => '/ThirdParty/beberlei/assert/AssertionFailedException.php', - 'ncc\\assert\\invalidargumentexception' => '/ThirdParty/beberlei/assert/InvalidArgumentException.php', - 'ncc\\assert\\lazyassertion' => '/ThirdParty/beberlei/assert/LazyAssertion.php', - 'ncc\\assert\\lazyassertionexception' => '/ThirdParty/beberlei/assert/LazyAssertionException.php', 'ncc\\cli\\functions' => '/CLI/Functions.php', 'ncc\\cli\\helpmenu' => '/CLI/HelpMenu.php', 'ncc\\cli\\main' => '/CLI/Main.php', @@ -44,59 +37,6 @@ spl_autoload_register( 'ncc\\objects\\projectconfiguration\\compiler' => '/Objects/ProjectConfiguration/Compiler.php', 'ncc\\objects\\projectconfiguration\\dependency' => '/Objects/ProjectConfiguration/Dependency.php', 'ncc\\objects\\projectconfiguration\\project' => '/Objects/ProjectConfiguration/Project.php', - 'ncc\\phpschool\\climenu\\action\\exitaction' => '/ThirdParty/php-school/cli-menu/Action/ExitAction.php', - 'ncc\\phpschool\\climenu\\action\\gobackaction' => '/ThirdParty/php-school/cli-menu/Action/GoBackAction.php', - 'ncc\\phpschool\\climenu\\builder\\climenubuilder' => '/ThirdParty/php-school/cli-menu/Builder/CliMenuBuilder.php', - 'ncc\\phpschool\\climenu\\builder\\splititembuilder' => '/ThirdParty/php-school/cli-menu/Builder/SplitItemBuilder.php', - 'ncc\\phpschool\\climenu\\climenu' => '/ThirdParty/php-school/cli-menu/CliMenu.php', - 'ncc\\phpschool\\climenu\\dialogue\\cancellableconfirm' => '/ThirdParty/php-school/cli-menu/Dialogue/CancellableConfirm.php', - 'ncc\\phpschool\\climenu\\dialogue\\confirm' => '/ThirdParty/php-school/cli-menu/Dialogue/Confirm.php', - 'ncc\\phpschool\\climenu\\dialogue\\dialogue' => '/ThirdParty/php-school/cli-menu/Dialogue/Dialogue.php', - 'ncc\\phpschool\\climenu\\dialogue\\flash' => '/ThirdParty/php-school/cli-menu/Dialogue/Flash.php', - 'ncc\\phpschool\\climenu\\exception\\cannotshrinkmenuexception' => '/ThirdParty/php-school/cli-menu/Exception/CannotShrinkMenuException.php', - 'ncc\\phpschool\\climenu\\exception\\invalidshortcutexception' => '/ThirdParty/php-school/cli-menu/Exception/InvalidShortcutException.php', - 'ncc\\phpschool\\climenu\\exception\\invalidterminalexception' => '/ThirdParty/php-school/cli-menu/Exception/InvalidTerminalException.php', - 'ncc\\phpschool\\climenu\\exception\\menunotopenexception' => '/ThirdParty/php-school/cli-menu/Exception/MenuNotOpenException.php', - 'ncc\\phpschool\\climenu\\frame' => '/ThirdParty/php-school/cli-menu/Frame.php', - 'ncc\\phpschool\\climenu\\input\\input' => '/ThirdParty/php-school/cli-menu/Input/Input.php', - 'ncc\\phpschool\\climenu\\input\\inputio' => '/ThirdParty/php-school/cli-menu/Input/InputIO.php', - 'ncc\\phpschool\\climenu\\input\\inputresult' => '/ThirdParty/php-school/cli-menu/Input/InputResult.php', - 'ncc\\phpschool\\climenu\\input\\number' => '/ThirdParty/php-school/cli-menu/Input/Number.php', - 'ncc\\phpschool\\climenu\\input\\password' => '/ThirdParty/php-school/cli-menu/Input/Password.php', - 'ncc\\phpschool\\climenu\\input\\text' => '/ThirdParty/php-school/cli-menu/Input/Text.php', - 'ncc\\phpschool\\climenu\\menuitem\\asciiartitem' => '/ThirdParty/php-school/cli-menu/MenuItem/AsciiArtItem.php', - 'ncc\\phpschool\\climenu\\menuitem\\checkboxitem' => '/ThirdParty/php-school/cli-menu/MenuItem/CheckboxItem.php', - 'ncc\\phpschool\\climenu\\menuitem\\linebreakitem' => '/ThirdParty/php-school/cli-menu/MenuItem/LineBreakItem.php', - 'ncc\\phpschool\\climenu\\menuitem\\menuiteminterface' => '/ThirdParty/php-school/cli-menu/MenuItem/MenuItemInterface.php', - 'ncc\\phpschool\\climenu\\menuitem\\menumenuitem' => '/ThirdParty/php-school/cli-menu/MenuItem/MenuMenuItem.php', - 'ncc\\phpschool\\climenu\\menuitem\\propagatesstyles' => '/ThirdParty/php-school/cli-menu/MenuItem/PropagatesStyles.php', - 'ncc\\phpschool\\climenu\\menuitem\\radioitem' => '/ThirdParty/php-school/cli-menu/MenuItem/RadioItem.php', - 'ncc\\phpschool\\climenu\\menuitem\\selectableitem' => '/ThirdParty/php-school/cli-menu/MenuItem/SelectableItem.php', - 'ncc\\phpschool\\climenu\\menuitem\\selectableitemrenderer' => '/ThirdParty/php-school/cli-menu/MenuItem/SelectableItemRenderer.php', - 'ncc\\phpschool\\climenu\\menuitem\\splititem' => '/ThirdParty/php-school/cli-menu/MenuItem/SplitItem.php', - 'ncc\\phpschool\\climenu\\menuitem\\staticitem' => '/ThirdParty/php-school/cli-menu/MenuItem/StaticItem.php', - 'ncc\\phpschool\\climenu\\menustyle' => '/ThirdParty/php-school/cli-menu/MenuStyle.php', - 'ncc\\phpschool\\climenu\\style\\checkboxstyle' => '/ThirdParty/php-school/cli-menu/Style/CheckboxStyle.php', - 'ncc\\phpschool\\climenu\\style\\defaultstyle' => '/ThirdParty/php-school/cli-menu/Style/DefaultStyle.php', - 'ncc\\phpschool\\climenu\\style\\exception\\invalidstyle' => '/ThirdParty/php-school/cli-menu/Style/Exception/InvalidStyle.php', - 'ncc\\phpschool\\climenu\\style\\itemstyle' => '/ThirdParty/php-school/cli-menu/Style/ItemStyle.php', - 'ncc\\phpschool\\climenu\\style\\locator' => '/ThirdParty/php-school/cli-menu/Style/Locator.php', - 'ncc\\phpschool\\climenu\\style\\radiostyle' => '/ThirdParty/php-school/cli-menu/Style/RadioStyle.php', - 'ncc\\phpschool\\climenu\\style\\selectablestyle' => '/ThirdParty/php-school/cli-menu/Style/SelectableStyle.php', - 'ncc\\phpschool\\climenu\\terminal\\terminalfactory' => '/ThirdParty/php-school/cli-menu/Terminal/TerminalFactory.php', - 'ncc\\phpschool\\climenu\\util\\collection' => '/ThirdParty/php-school/cli-menu/Util/Collection.php', - 'ncc\\phpschool\\climenu\\util\\colourutil' => '/ThirdParty/php-school/cli-menu/Util/ColourUtil.php', - 'ncc\\phpschool\\climenu\\util\\stringutil' => '/ThirdParty/php-school/cli-menu/Util/StringUtil.php', - 'ncc\\phpschool\\terminal\\exception\\notinteractiveterminal' => '/ThirdParty/php-school/terminal/Exception/NotInteractiveTerminal.php', - 'ncc\\phpschool\\terminal\\inputcharacter' => '/ThirdParty/php-school/terminal/InputCharacter.php', - 'ncc\\phpschool\\terminal\\io\\bufferedoutput' => '/ThirdParty/php-school/terminal/IO/BufferedOutput.php', - 'ncc\\phpschool\\terminal\\io\\inputstream' => '/ThirdParty/php-school/terminal/IO/InputStream.php', - 'ncc\\phpschool\\terminal\\io\\outputstream' => '/ThirdParty/php-school/terminal/IO/OutputStream.php', - 'ncc\\phpschool\\terminal\\io\\resourceinputstream' => '/ThirdParty/php-school/terminal/IO/ResourceInputStream.php', - 'ncc\\phpschool\\terminal\\io\\resourceoutputstream' => '/ThirdParty/php-school/terminal/IO/ResourceOutputStream.php', - 'ncc\\phpschool\\terminal\\noncanonicalreader' => '/ThirdParty/php-school/terminal/NonCanonicalReader.php', - 'ncc\\phpschool\\terminal\\terminal' => '/ThirdParty/php-school/terminal/Terminal.php', - 'ncc\\phpschool\\terminal\\unixterminal' => '/ThirdParty/php-school/terminal/UnixTerminal.php', 'ncc\\symfony\\component\\process\\exception\\exceptioninterface' => '/ThirdParty/Symfony/Process/Exception/ExceptionInterface.php', 'ncc\\symfony\\component\\process\\exception\\invalidargumentexception' => '/ThirdParty/Symfony/Process/Exception/InvalidArgumentException.php', 'ncc\\symfony\\component\\process\\exception\\logicexception' => '/ThirdParty/Symfony/Process/Exception/LogicException.php',