/** * @param UniquenessCheckerInterface $uniquenessChecker * @param int $tokenLength * * @throws \InvalidArgumentException */ public function __construct(UniquenessCheckerInterface $uniquenessChecker, $tokenLength) { Assert::integer($tokenLength, 'The value of token length has to be an integer.'); Assert::range($tokenLength, 1, 40, 'The value of token length has to be in range between 1 to 40.'); $this->tokenLength = $tokenLength; $this->uniquenessChecker = $uniquenessChecker; }
/** * Adds a participation to the data collector. * * @param string $testIdentifier It will look like "Qp0gahJ3RAO3DJ18b0XoUQ" * @param int $variationIndex * @throws InvalidArgumentException */ public function addParticipation($testIdentifier, $variationIndex) { Assert::string($testIdentifier, 'Test identifier must be a string'); Assert::integer($variationIndex, 'Variation index must be integer'); Assert::greaterThan($variationIndex, -1, 'Variation index must be integer >= 0'); $this->participations[$testIdentifier] = $variationIndex; }
/** * @param UniquenessCheckerInterface $uniquenessChecker * @param int $pinLength * * @throws \InvalidArgumentException */ public function __construct(UniquenessCheckerInterface $uniquenessChecker, $pinLength) { Assert::integer($pinLength, 'The value of pin length has to be an integer.'); Assert::range($pinLength, 1, 9, 'The value of pin length has to be in range between 1 to 9.'); $this->pinLength = $pinLength; $this->uniquenessChecker = $uniquenessChecker; }
/** * {@inheritdoc} */ public function getMessages(ConversationInterface $conversation, $offset = 0, $limit = 20, $sortDirection = 'ASC') { Assert::integer($offset, '$offset expected an integer in Repository::getMessages(). Got: %s'); Assert::integer($limit, '$limit expected an integer in Repository::getMessages(). Got: %s'); Assert::oneOf(strtoupper($sortDirection), ['ASC', 'DESC'], '$sortDirection expected either ASC or DESC in Repository::getMessages(). Got: %s'); return $this->driver->findMessages($conversation, $offset, $limit, $sortDirection); }
/** * Initializes a new instance of this class. * * @param string $cookieName The name the cookie. * @param int $ttl How long should the cookie last in browser. Default 5 years * Setting a negative number will make cookie expire after current session * @throws InvalidArgumentException */ public function __construct($cookieName, $ttl = 157766400) { // We cannot typehint for primitive types yet so therefore we check if the cookie name is a (valid) string. Assert::string($cookieName, 'The cookie name is invalid.'); Assert::notEmpty($cookieName, 'The cookie name is invalid.'); Assert::integer($ttl, 'The cookie ttl parameter should be a integer.'); $this->cookieName = $cookieName; $this->ttl = $ttl; }
/** * Create a Serializer instance. * * @param int $indent The number of times the indent string is repeated. * @param string $indentString The string to indent the comment with. * @param bool $indentFirstLine Whether to indent the first line. * @param int|null $lineLength The max length of a line or NULL to disable line wrapping. */ public function __construct($indent = 0, $indentString = ' ', $indentFirstLine = true, $lineLength = null) { Assert::integer($indent); Assert::string($indentString); Assert::boolean($indentFirstLine); Assert::nullOrInteger($lineLength); $this->indent = $indent; $this->indentString = $indentString; $this->isFirstLineIndented = $indentFirstLine; $this->lineLength = $lineLength; }
/** * @param Key $source * @param string $key * @param int $bits * @param int $type * @param array $details */ public function __construct(Key $source, $key, $bits, $type, array $details = []) { Assert::stringNotEmpty($key, __CLASS__ . '::$key expected a non empty string. Got: %s'); Assert::integer($bits, __CLASS__ . '::$bits expected an integer. Got: %s'); Assert::oneOf($type, [OPENSSL_KEYTYPE_RSA, OPENSSL_KEYTYPE_DSA, OPENSSL_KEYTYPE_DH, OPENSSL_KEYTYPE_EC], __CLASS__ . '::$type expected one of: %2$s. Got: %s'); $this->source = $source; $this->key = $key; $this->bits = $bits; $this->type = $type; $this->details = $details; }
/** * {@inheritdoc} */ public function distribute(array $integers, $amount) { Assert::allInteger($integers); Assert::integer($amount); $total = array_sum($integers); $distributedAmounts = []; foreach ($integers as $element) { $distributedAmounts[] = (int) round($element * $amount / $total, 0, PHP_ROUND_HALF_DOWN); } $missingAmount = $amount - array_sum($distributedAmounts); for ($i = 0; $i < abs($missingAmount); $i++) { $distributedAmounts[$i] += $missingAmount >= 0 ? 1 : -1; } return $distributedAmounts; }
/** * Generate KeyPair. * * @param int $keySize Size of the key. * * @throws KeyPairGenerationException When OpenSSL failed to generate keys. * * @return KeyPair */ public function generateKeyPair($keySize = 4096) { Assert::integer($keySize, __METHOD__ . '::$keySize should be an integer. Got: %s'); $key = openssl_pkey_new(['private_key_type' => OPENSSL_KEYTYPE_RSA, 'private_key_bits' => $keySize]); if (!$key) { throw new KeyPairGenerationException(sprintf('OpenSSL key creation failed during generation with error: %s', openssl_error_string())); } if (!openssl_pkey_export($key, $privateKey)) { throw new KeyPairGenerationException(sprintf('OpenSSL key export failed during generation with error: %s', openssl_error_string())); } $details = openssl_pkey_get_details($key); if (!is_array($details)) { throw new KeyPairGenerationException(sprintf('OpenSSL key parsing failed during generation with error: %s', openssl_error_string())); } return new KeyPair(new PublicKey($details['key']), new PrivateKey($privateKey)); }
/** * Suggests a command based on similarity in a list of available commands. * * @param string $badCommand invalid command * @param array $commands list of available commands * @param int $suggestThreshold similarity threshold * @return string suggestion or empty string if no command is similar enough */ function suggestCommand($badCommand, array $commands, $suggestThreshold = 70) { Assert::string($badCommand, "Bad command must be a string. Got: %s"); Assert::integer($suggestThreshold, "Suggest threshold must be an integer. Got: %s"); $badCommand = strtolower($badCommand); $bestMatch = ""; $bestMatchPercentage = 0; $byRefPercentage = 0; foreach ($commands as $command) { \similar_text($badCommand, strtolower($command), $byRefPercentage); if ($byRefPercentage > $bestMatchPercentage) { $bestMatchPercentage = $byRefPercentage; $bestMatch = $command; } } return $bestMatchPercentage >= $suggestThreshold ? $bestMatch : ""; }
/** * {@inheritdoc} * * @throws \InvalidArgumentException */ public function setUnitPrice($unitPrice) { Assert::integer($unitPrice, 'Unit price must be an integer.'); $this->unitPrice = $unitPrice; $this->recalculateUnitsTotal(); }
private function assertFlagsValid($flags) { Assert::integer($flags, 'The option flags must be an integer. Got: %s'); if ($flags & self::PREFER_SHORT_NAME && $flags & self::PREFER_LONG_NAME) { throw new InvalidArgumentException('The option flags PREFER_SHORT_NAME and PREFER_LONG_NAME cannot be combined.'); } }
private function assertFlagsValid($flags) { Assert::integer($flags, 'The argument flags must be an integer. Got: %s'); if ($flags & self::REQUIRED && $flags & self::OPTIONAL) { throw new InvalidArgumentException('The argument flags REQUIRED and OPTIONAL cannot be combined.'); } if ($flags & self::STRING) { if ($flags & self::BOOLEAN) { throw new InvalidArgumentException('The argument flags STRING and BOOLEAN cannot be combined.'); } if ($flags & self::INTEGER) { throw new InvalidArgumentException('The argument flags STRING and INTEGER cannot be combined.'); } if ($flags & self::FLOAT) { throw new InvalidArgumentException('The argument flags STRING and FLOAT cannot be combined.'); } } elseif ($flags & self::BOOLEAN) { if ($flags & self::INTEGER) { throw new InvalidArgumentException('The argument flags BOOLEAN and INTEGER cannot be combined.'); } if ($flags & self::FLOAT) { throw new InvalidArgumentException('The argument flags BOOLEAN and FLOAT cannot be combined.'); } } elseif ($flags & self::INTEGER) { if ($flags & self::FLOAT) { throw new InvalidArgumentException('The argument flags INTEGER and FLOAT cannot be combined.'); } } }
/** * Set number * * @param integer $number * @return Course */ public function setNumber($number) { Assert::integer($number); $this->number = $number; $this->refreshKey(); return $this; }
/** * {@inheritdoc} */ public function requestCertificate($domain, CertificateRequest $csr, $timeout = 180) { Assert::stringNotEmpty($domain, 'requestCertificate::$domain expected a non-empty string. Got: %s'); Assert::integer($timeout, 'requestCertificate::$timeout expected an integer. Got: %s'); $humanText = ['-----BEGIN CERTIFICATE REQUEST-----', '-----END CERTIFICATE REQUEST-----']; $csrContent = $this->csrSigner->signCertificateRequest($csr); $csrContent = trim(str_replace($humanText, '', $csrContent)); $csrContent = trim($this->httpClient->getBase64Encoder()->encode(base64_decode($csrContent))); $response = $this->requestResource('POST', ResourcesDirectory::NEW_CERTIFICATE, ['resource' => ResourcesDirectory::NEW_CERTIFICATE, 'csr' => $csrContent], false); // If the CA has not yet issued the certificate, the body of this response will be empty if (strlen(trim($response)) < 10) { // 10 to avoid false results $location = $this->httpClient->getLastLocation(); // Waiting loop $endTime = time() + $timeout; while (time() <= $endTime) { $response = $this->httpClient->unsignedRequest('GET', $location, null, false); if (200 === $this->httpClient->getLastCode()) { break; } if (202 !== $this->httpClient->getLastCode()) { throw new CertificateRequestFailedException($response); } sleep(1); } if (202 === $this->httpClient->getLastCode()) { throw new CertificateRequestTimedOutException($response); } } // Find issuers certificate $links = $this->httpClient->getLastLinks(); $certificatesChain = null; foreach ($links as $link) { if (!isset($link['rel']) || 'up' !== $link['rel']) { continue; } $location = trim($link[0], '<>'); $certificate = $this->httpClient->unsignedRequest('GET', $location, null, false); if (strlen(trim($certificate)) > 10) { $pem = chunk_split(base64_encode($certificate), 64, "\n"); $pem = "-----BEGIN CERTIFICATE-----\n" . $pem . "-----END CERTIFICATE-----\n"; $certificatesChain = new Certificate($pem, $certificatesChain); } } // Domain certificate $pem = chunk_split(base64_encode($response), 64, "\n"); $pem = "-----BEGIN CERTIFICATE-----\n" . $pem . "-----END CERTIFICATE-----\n"; return new CertificateResponse($csr, new Certificate($pem, $certificatesChain)); }
/** * {@inheritdoc} */ public function setAmount($amount) { Assert::integer($amount, 'Amount must be an integer.'); $this->amount = $amount; if (!$this->isNeutral()) { $this->recalculateAdjustable(); } }
private function assertFlagsValid($flags) { Assert::integer($flags, 'The option flags must be an integer. Got: %s'); if ($flags & self::NO_VALUE) { if ($flags & self::REQUIRED_VALUE) { throw new InvalidArgumentException('The option flags VALUE_NONE and VALUE_REQUIRED cannot be combined.'); } if ($flags & self::OPTIONAL_VALUE) { throw new InvalidArgumentException('The option flags VALUE_NONE and VALUE_OPTIONAL cannot be combined.'); } if ($flags & self::MULTI_VALUED) { throw new InvalidArgumentException('The option flags VALUE_NONE and MULTI_VALUED cannot be combined.'); } } if ($flags & self::OPTIONAL_VALUE && $flags & self::MULTI_VALUED) { throw new InvalidArgumentException('The option flags VALUE_OPTIONAL and MULTI_VALUED cannot be combined.'); } if ($flags & self::STRING) { if ($flags & self::BOOLEAN) { throw new InvalidArgumentException('The option flags STRING and BOOLEAN cannot be combined.'); } if ($flags & self::INTEGER) { throw new InvalidArgumentException('The option flags STRING and INTEGER cannot be combined.'); } if ($flags & self::FLOAT) { throw new InvalidArgumentException('The option flags STRING and FLOAT cannot be combined.'); } } elseif ($flags & self::BOOLEAN) { if ($flags & self::INTEGER) { throw new InvalidArgumentException('The option flags BOOLEAN and INTEGER cannot be combined.'); } if ($flags & self::FLOAT) { throw new InvalidArgumentException('The option flags BOOLEAN and FLOAT cannot be combined.'); } } elseif ($flags & self::INTEGER) { if ($flags & self::FLOAT) { throw new InvalidArgumentException('The option flags INTEGER and FLOAT cannot be combined.'); } } }
/** * {@inheritdoc} */ protected function isConfigurationValid(array $configuration) { Assert::keyExists($configuration, 'amount'); Assert::integer($configuration['amount']); }
public function __construct($path, $flags = 0) { Assert::string($path, 'The path must be a string. Got: %s'); Assert::notEmpty($path, 'The path must not be empty.'); Assert::integer($flags, 'The flags must be an integer. Got: %s'); $this->path = $path; $this->flags = $flags; $this->encoder = new JsonEncoder(); $this->encoder->setEscapeGtLt($this->flags & self::ESCAPE_GT_LT); $this->encoder->setEscapeAmpersand($this->flags & self::ESCAPE_AMPERSAND); $this->encoder->setEscapeSingleQuote($this->flags & self::ESCAPE_SINGLE_QUOTE); $this->encoder->setEscapeDoubleQuote($this->flags & self::ESCAPE_DOUBLE_QUOTE); $this->encoder->setEscapeSlash(!($this->flags & self::NO_ESCAPE_SLASH)); $this->encoder->setEscapeUnicode(!($this->flags & self::NO_ESCAPE_UNICODE)); $this->encoder->setPrettyPrinting($this->flags & self::PRETTY_PRINT); $this->encoder->setTerminateWithLineFeed($this->flags & self::TERMINATE_WITH_LINE_FEED); $this->decoder = new JsonDecoder(); $this->decoder->setObjectDecoding(JsonDecoder::ASSOC_ARRAY); }