_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q257300 | AbstractInstallCommand.executeCommand | test | protected function executeCommand($command, OutputInterface $output = null, array $options = [])
{
if (is_null($output)) {
$output = new NullOutput();
}
$options = array_merge($options, [
'command' => $command,
]);
$this
->getApplication()
->run(new ArrayInput($options), $output);
return $this;
} | php | {
"resource": ""
} |
q257301 | Str.between | test | public function between($start, $end)
{
if ($start == '' && $end == '') {
return $this;
}
if ($start != '' && strpos($this->string, $start) === false) {
return new static();
}
if ($end != '' && strpos($this->string, $end) === false) {
return new static();
}
if ($start == '') {
return new static(substr($this->string, 0, strpos($this->string, $end)));
}
if ($end == '') {
return new static(substr($this->string, strpos($this->string, $start) + strlen($start)));
}
$stringWithoutStart = explode($start, $this->string)[1];
$middle = explode($end, $stringWithoutStart)[0];
return new static($middle);
} | php | {
"resource": ""
} |
q257302 | Str.sanitizeForTease | test | private function sanitizeForTease($string)
{
$string = trim($string);
//remove html
$string = strip_tags($string);
//replace multiple spaces
$string = preg_replace("/\s+/", ' ', $string);
return $string;
} | php | {
"resource": ""
} |
q257303 | Str.replaceFirst | test | public function replaceFirst($search, $replace)
{
if ($search == '') {
return $this;
}
$position = strpos($this->string, $search);
if ($position === false) {
return $this;
}
$resultString = substr_replace($this->string, $replace, $position, strlen($search));
return new static($resultString);
} | php | {
"resource": ""
} |
q257304 | Str.replaceLast | test | public function replaceLast($search, $replace)
{
if ($search == '') {
return $this;
}
$position = strrpos($this->string, $search);
if ($position === false) {
return $this;
}
$resultString = substr_replace($this->string, $replace, $position, strlen($search));
return new static($resultString);
} | php | {
"resource": ""
} |
q257305 | Str.possessive | test | public function possessive()
{
if ($this->string == '') {
return new static();
}
$noApostropheEdgeCases = ['it'];
if (in_array($this->string, $noApostropheEdgeCases)) {
return new static($this->string.'s');
}
return new static($this->string.'\''.($this->string[strlen($this->string) - 1] != 's' ? 's' : ''));
} | php | {
"resource": ""
} |
q257306 | Str.segment | test | public function segment($delimiter, $index)
{
$segments = explode($delimiter, $this->string);
if ($index < 0) {
$segments = array_reverse($segments);
$index = abs($index) - 1;
}
$segment = isset($segments[$index]) ? $segments[$index] : '';
return new static($segment);
} | php | {
"resource": ""
} |
q257307 | Str.contains | test | public function contains($needle, $caseSensitive = false, $absolute = false)
{
return $this->find($needle, $caseSensitive, $absolute);
} | php | {
"resource": ""
} |
q257308 | PayUMoneyGateway.encrypt | test | protected function encrypt()
{
$this->hash = '';
$hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";
$hashVarsSeq = explode('|', $hashSequence);
$hash_string = '';
foreach($hashVarsSeq as $hash_var) {
$hash_string .= isset($this->parameters[$hash_var]) ? $this->parameters[$hash_var] : '';
$hash_string .= '|';
}
$hash_string .= $this->salt;
$this->hash = strtolower(hash('sha512', $hash_string));
} | php | {
"resource": ""
} |
q257309 | PayUMoneyGateway.decrypt | test | protected function decrypt($response)
{
$hashSequence = "status||||||udf5|udf4|udf3|udf2|udf1|email|firstname|productinfo|amount|txnid|key";
$hashVarsSeq = explode('|', $hashSequence);
$hash_string = $this->salt."|";
foreach($hashVarsSeq as $hash_var) {
$hash_string .= isset($response[$hash_var]) ? $response[$hash_var] : '';
$hash_string .= '|';
}
$hash_string = trim($hash_string,'|');
return strtolower(hash('sha512', $hash_string));
} | php | {
"resource": ""
} |
q257310 | CCAvenueGateway.encrypt | test | protected function encrypt($plainText,$key)
{
$secretKey = $this->hextobin(md5($key));
$initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
$openMode = @mcrypt_module_open(MCRYPT_RIJNDAEL_128, '','cbc', '');
$blockSize = @mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, 'cbc');
$plainPad = $this->pkcs5_pad($plainText, $blockSize);
if (@mcrypt_generic_init($openMode, $secretKey, $initVector) != -1)
{
$encryptedText = @mcrypt_generic($openMode, $plainPad);
@mcrypt_generic_deinit($openMode);
}
return bin2hex($encryptedText);
} | php | {
"resource": ""
} |
q257311 | CCAvenueGateway.decrypt | test | protected function decrypt($encryptedText,$key)
{
$secretKey = $this->hextobin(md5($key));
$initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
$encryptedText=$this->hextobin($encryptedText);
$openMode = @mcrypt_module_open(MCRYPT_RIJNDAEL_128, '','cbc', '');
@mcrypt_generic_init($openMode, $secretKey, $initVector);
$decryptedText = @mdecrypt_generic($openMode, $encryptedText);
$decryptedText = rtrim($decryptedText, "\0");
@mcrypt_generic_deinit($openMode);
return $decryptedText;
} | php | {
"resource": ""
} |
q257312 | CitrusGateway.encrypt | test | protected function encrypt()
{
$hash_string = $this->vanityUrl.$this->parameters['orderAmount'].$this->parameters['merchantTxnId'].$this->parameters['currency'];
$this->hash = hash_hmac('sha1', $hash_string, $this->secretKey);
} | php | {
"resource": ""
} |
q257313 | CitrusGateway.decrypt | test | protected function decrypt($response)
{
$hash_string = '';
$hash_string .= $response['TxId'];
$hash_string .= $response['TxStatus'];
$hash_string .= $response['amount'];
$hash_string .= $response['pgTxnNo'];
$hash_string .= $response['issuerRefNo'];
$hash_string .= $response['authIdCode'];
$hash_string .= $response['firstName'];
$hash_string .= $response['lastName'];
$hash_string .= $response['pgRespCode'];
$hash_string .= $response['addressZip'];
return hash_hmac('sha1', $hash_string, $this->secretKey);
} | php | {
"resource": ""
} |
q257314 | EBSGateway.encrypt | test | protected function encrypt()
{
$this->hash = '';
$hash_string = $this->secretKey."|".urlencode($this->parameters['account_id'])."|".urlencode($this->parameters['amount'])."|".urlencode($this->parameters['reference_no'])."|".$this->parameters['return_url']."|".urlencode($this->parameters['mode']);
$this->hash = md5($hash_string);
} | php | {
"resource": ""
} |
q257315 | VerbalExpressions.range | test | public function range()
{
$args = func_get_args();
$arg_num = count($args);
if ($arg_num%2 != 0) {
throw new \InvalidArgumentException('Number of args must be even', 1);
}
$value = '[';
for ($i = 0; $i < $arg_num;) {
$value .= self::sanitize($args[$i++]) . '-' . self::sanitize($args[$i++]);
}
$value .= ']';
return $this->add($value);
} | php | {
"resource": ""
} |
q257316 | VerbalExpressions.addModifier | test | public function addModifier($modifier)
{
if (strpos($this->modifiers, $modifier) === false) {
$this->modifiers .= $modifier;
}
return $this;
} | php | {
"resource": ""
} |
q257317 | Pages.addRange | test | public function addRange(int $start, int $end): void
{
$this->pages = array_merge($this->pages, range($start, $end));
} | php | {
"resource": ""
} |
q257318 | Merger.addRaw | test | public function addRaw(string $content, PagesInterface $pages = null): void
{
$this->sources[] = new RawSource($content, $pages);
} | php | {
"resource": ""
} |
q257319 | Merger.addFile | test | public function addFile(string $filename, PagesInterface $pages = null): void
{
$this->sources[] = new FileSource($filename, $pages);
} | php | {
"resource": ""
} |
q257320 | Merger.addIterator | test | public function addIterator(iterable $iterator, PagesInterface $pages = null): void
{
foreach ($iterator as $filename) {
$this->addFile($filename, $pages);
}
} | php | {
"resource": ""
} |
q257321 | Linked.jsonUnserializeFromProperties | test | protected static function jsonUnserializeFromProperties($properties)
{
if ( ! is_array($properties) && ! is_object($properties)) {
throw UnserializationException::invalidProperty('Linked CRS', 'properties', $properties, 'array or object');
}
$properties = new \ArrayObject($properties);
if ( ! $properties->offsetExists('href')) {
throw UnserializationException::missingProperty('Linked CRS', 'properties.href', 'string');
}
$href = (string) $properties['href'];
$type = isset($properties['type']) ? (string) $properties['type'] : null;
return new self($href, $type);
} | php | {
"resource": ""
} |
q257322 | GeoJson.setOptionalConstructorArgs | test | protected function setOptionalConstructorArgs(array $args)
{
foreach ($args as $arg) {
if ($arg instanceof CoordinateReferenceSystem) {
$this->crs = $arg;
}
if ($arg instanceof BoundingBox) {
$this->boundingBox = $arg;
}
}
} | php | {
"resource": ""
} |
q257323 | UnserializationException.invalidValue | test | public static function invalidValue($context, $value, $expectedType)
{
return new self(sprintf(
'%s expected value of type %s, %s given',
$context,
$expectedType,
is_object($value) ? get_class($value) : gettype($value)
));
} | php | {
"resource": ""
} |
q257324 | UnserializationException.invalidProperty | test | public static function invalidProperty($context, $property, $value, $expectedType)
{
return new self(sprintf(
'%s expected "%s" property of type %s, %s given',
$context,
$property,
$expectedType,
is_object($value) ? get_class($value) : gettype($value)
));
} | php | {
"resource": ""
} |
q257325 | Named.jsonUnserializeFromProperties | test | protected static function jsonUnserializeFromProperties($properties)
{
if ( ! is_array($properties) && ! is_object($properties)) {
throw UnserializationException::invalidProperty('Named CRS', 'properties', $properties, 'array or object');
}
$properties = new \ArrayObject($properties);
if ( ! $properties->offsetExists('name')) {
throw UnserializationException::missingProperty('Named CRS', 'properties.name', 'string');
}
$name = (string) $properties['name'];
return new self($name);
} | php | {
"resource": ""
} |
q257326 | Application.configPath | test | public function configPath($path = '')
{
return $this->basePath.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'matthewbdaly'.DIRECTORY_SEPARATOR.'artisan-standalone'.DIRECTORY_SEPARATOR.'config'.($path ? DIRECTORY_SEPARATOR.$path : $path);
} | php | {
"resource": ""
} |
q257327 | Application.getNamespace | test | public function getNamespace()
{
if (! is_null($this->namespace)) {
return $this->namespace;
}
$path = $this->basePath;
$composer = json_decode(file_get_contents($path.DIRECTORY_SEPARATOR.'composer.json'), true);
foreach ((array) data_get($composer, 'autoload.psr-4') as $namespace => $path) {
return $this->namespace = $namespace;
}
throw new RuntimeException('Unable to detect application namespace.');
} | php | {
"resource": ""
} |
q257328 | CacheAdapterExtension.load | test | public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
// Configure client services
$first = isset($config['providers']['default']) ? 'default' : null;
foreach ($config['providers'] as $name => $arguments) {
if (null === $first) {
$first = $name;
}
$factoryClass = $container->getDefinition($arguments['factory'])->getClass();
$factoryClass::validate($arguments['options'], $name);
// See if any option has a service reference
$arguments['options'] = $this->findReferences($arguments['options']);
$def = $container->register('cache.provider.'.$name, DummyAdapter::class);
$def->setFactory([new Reference($arguments['factory']), 'createAdapter'])
->addArgument($arguments['options'])
->setPublic(true);
$def->addTag('cache.provider');
foreach ($arguments['aliases'] as $alias) {
$container->setAlias($alias, new Alias('cache.provider.'.$name, true));
}
}
if (null !== $first) {
$container->setAlias('cache', 'cache.provider.'.$first);
$container->setAlias('php_cache', 'cache.provider.'.$first);
}
} | php | {
"resource": ""
} |
q257329 | HdNode.newMasterNode | test | public static function newMasterNode($entropy)
{
$hmac = hash_hmac('sha512', $entropy, 'ed25519 seed', true);
return new HdNode(
substr($hmac, 0, 32),
substr($hmac, 32, 32)
);
} | php | {
"resource": ""
} |
q257330 | Account.getNativeBalance | test | public function getNativeBalance()
{
MathSafety::require64Bit();
foreach ($this->getBalances() as $balance) {
if ($balance->isNativeAsset()) return $balance->getBalance();
}
return 0;
} | php | {
"resource": ""
} |
q257331 | Account.getNativeBalanceStroops | test | public function getNativeBalanceStroops()
{
MathSafety::require64Bit();
foreach ($this->getBalances() as $balance) {
if ($balance->isNativeAsset()) return $balance->getUnscaledBalance();
}
return "0";
} | php | {
"resource": ""
} |
q257332 | Account.getCustomAssetBalanceValue | test | public function getCustomAssetBalanceValue(Asset $asset)
{
foreach ($this->getBalances() as $balance) {
if ($balance->getAssetCode() !== $asset->getAssetCode()) continue;
if ($balance->getAssetIssuerAccountId() != $asset->getIssuer()->getAccountIdString()) continue;
return $balance->getBalance();
}
return null;
} | php | {
"resource": ""
} |
q257333 | Account.getCustomAssetBalance | test | public function getCustomAssetBalance(Asset $asset)
{
foreach ($this->getBalances() as $balance) {
if ($balance->getAssetCode() !== $asset->getAssetCode()) continue;
if ($balance->getAssetIssuerAccountId() != $asset->getIssuer()->getAccountIdString()) continue;
return $balance;
}
return null;
} | php | {
"resource": ""
} |
q257334 | Account.getCustomAssetBalanceStroops | test | public function getCustomAssetBalanceStroops(Asset $asset)
{
MathSafety::require64Bit();
foreach ($this->getBalances() as $balance) {
if ($balance->getAssetCode() !== $asset->getAssetCode()) continue;
if ($balance->getAssetIssuerAccountId() != $asset->getIssuer()->getAccountIdString()) continue;
return $balance->getUnscaledBalance();
}
return null;
} | php | {
"resource": ""
} |
q257335 | Bip39.getEntropyChecksumHex | test | public static function getEntropyChecksumHex($entropyBytes)
{
$checksumLengthBits = (strlen($entropyBytes)*8) / 32;
$hashBytes = hash('sha256', $entropyBytes, true);
// base_convert can only handle up to 64 bits, so we have to reduce the
// length of data that gets sent to it
$checksumLengthBytes = ceil($checksumLengthBits / 8);
$reducedBytesToChecksum = substr($hashBytes, 0, $checksumLengthBytes);
$reducedChecksumHex = bin2hex($reducedBytesToChecksum);
$reducedChecksumBits = str_pad(base_convert($reducedChecksumHex, 16, 2), $checksumLengthBytes * 8, '0', STR_PAD_LEFT);
$checksumBitstring = substr($reducedChecksumBits, 0, $checksumLengthBits);
$checksumHex = static::bitstringToHex($checksumBitstring);
return $checksumHex;
} | php | {
"resource": ""
} |
q257336 | Bip39.bitstringToHex | test | public static function bitstringToHex($bitstring)
{
$chunkSizeBits = 8;
// If the string is shorter than the chunk size it can be 0-padded
if (strlen($bitstring) < $chunkSizeBits) {
$bitstring = str_pad($bitstring, $chunkSizeBits, '0', STR_PAD_LEFT);
}
if (strlen($bitstring) % $chunkSizeBits !== 0) throw new \InvalidArgumentException(sprintf('Got bitstring of length %s, but it must be divisible by %s', strlen($bitstring), $chunkSizeBits));
$finalHex = '';
for ($i=0; $i < strlen($bitstring); $i += $chunkSizeBits) {
$bitstringPart = substr($bitstring, $i, $chunkSizeBits);
$hex = base_convert($bitstringPart, 2, 16);
// Ensure hex is always two characters
$hex = str_pad($hex, 2, '0', STR_PAD_LEFT);
$finalHex .= $hex;
}
return $finalHex;
} | php | {
"resource": ""
} |
q257337 | Bip39.mnemonicToEntropy | test | public function mnemonicToEntropy($mnenomic)
{
$bitstring = $this->parseMnemonic($mnenomic);
// Calculate expected lengths
$numChecksumBits = strlen($bitstring) / 33;
$numEntropyBits = strlen($bitstring) - $numChecksumBits;
// Get checksum bits from the end of the string
$checksumBits = substr($bitstring, -1 * $numChecksumBits);
$checksumHex = static::bitstringToHex($checksumBits);
// Remaining bits are the entropy
$entropyBits = substr($bitstring, 0, $numEntropyBits);
$entropyHex = static::bitstringToHex($entropyBits);
$entropyBytes = hex2bin($entropyHex);
if ($checksumHex !== static::getEntropyChecksumHex($entropyBytes)) {
throw new \InvalidArgumentException('Invalid checksum');
}
return $entropyBytes;
} | php | {
"resource": ""
} |
q257338 | TransactionBuilder.authorizeTrustline | test | public function authorizeTrustline(Asset $asset, $trustorId, $sourceAccountId = null)
{
if ($trustorId instanceof Keypair) {
$trustorId = $trustorId->getPublicKey();
}
$op = new AllowTrustOp($asset, new AccountId($trustorId), $sourceAccountId);
$op->setIsAuthorized(true);
return $this->addOperation($op);
} | php | {
"resource": ""
} |
q257339 | TransactionBuilder.revokeTrustline | test | public function revokeTrustline(Asset $asset, $trustorId, $sourceAccountId = null)
{
if ($trustorId instanceof Keypair) {
$trustorId = $trustorId->getPublicKey();
}
$op = new AllowTrustOp($asset, new AccountId($trustorId), $sourceAccountId);
$op->setIsAuthorized(false);
return $this->addOperation($op);
} | php | {
"resource": ""
} |
q257340 | Operation.toXdr | test | public function toXdr()
{
$bytes = '';
// Source Account
$bytes .= XdrEncoder::optional($this->sourceAccount);
// Type
$bytes .= XdrEncoder::unsignedInteger($this->type);
return $bytes;
} | php | {
"resource": ""
} |
q257341 | XdrEncoder.opaqueVariable | test | public static function opaqueVariable($value)
{
$maxLength = pow(2, 32) - 1;
if (strlen($value) > $maxLength) throw new \InvalidArgumentException(sprintf('Value of length %s is greater than the maximum allowed length of %s', strlen($value), $maxLength));
$bytes = '';
$bytes .= self::unsignedInteger(strlen($value));
$bytes .= self::applyPadding($value);
return $bytes;
} | php | {
"resource": ""
} |
q257342 | XdrEncoder.optional | test | public static function optional(XdrEncodableInterface $value = null)
{
$bytes = '';
if ($value !== null) {
$bytes .= self::boolean(true);
$bytes .= $value->toXdr();
}
else {
$bytes .= self::boolean(false);
}
return $bytes;
} | php | {
"resource": ""
} |
q257343 | BucketLevel.getUniqueBucketHashes | test | public function getUniqueBucketHashes()
{
$hashes = [];
if ($this->curr != self::HASH_EMPTY) $hashes[] = $this->curr;
if ($this->snap != self::HASH_EMPTY) $hashes[] = $this->snap;
return array_values(array_unique($hashes));
} | php | {
"resource": ""
} |
q257344 | Server.accountExists | test | public function accountExists($accountId)
{
// Handle basic errors such as malformed account IDs
try {
$account = $this->getAccount($accountId);
} catch (\InvalidArgumentException $e) {
return false;
}
// Account ID may be valid but hasn't been funded yet
if (!$account) return false;
return $account->getNativeBalanceStroops() != '0';
} | php | {
"resource": ""
} |
q257345 | SetOptionsOp.setAuthRequired | test | public function setAuthRequired($isRequired)
{
if ($isRequired) {
$this->setFlags = $this->setFlags | static::FLAG_AUTH_REQUIRED;
$this->clearFlags = $this->clearFlags & ~(static::FLAG_AUTH_REQUIRED);
}
else {
$this->setFlags = $this->setFlags & ~(static::FLAG_AUTH_REQUIRED);
$this->clearFlags = $this->clearFlags | static::FLAG_AUTH_REQUIRED;
}
return $this;
} | php | {
"resource": ""
} |
q257346 | SetOptionsOp.setAuthRevocable | test | public function setAuthRevocable($isRevocable)
{
if ($isRevocable) {
$this->setFlags = $this->setFlags | static::FLAG_AUTH_REVOCABLE;
$this->clearFlags = $this->clearFlags & ~(static::FLAG_AUTH_REVOCABLE);
}
else {
$this->setFlags = $this->setFlags & ~(static::FLAG_AUTH_REVOCABLE);
$this->clearFlags = $this->clearFlags | static::FLAG_AUTH_REVOCABLE;
}
return $this;
} | php | {
"resource": ""
} |
q257347 | Keypair.getPublicKeyChecksum | test | public function getPublicKeyChecksum()
{
$checksumBytes = substr($this->getPublicKeyBytes(), -2);
$unpacked = unpack('v', $checksumBytes);
return array_shift($unpacked);
} | php | {
"resource": ""
} |
q257348 | XdrDecoder.opaqueFixedString | test | public static function opaqueFixedString($xdr, $length)
{
$bytes = static::opaqueFixed($xdr, $length);
// remove trailing nulls
return strval(rtrim($bytes, "\0x00"));
} | php | {
"resource": ""
} |
q257349 | PostTransactionResponse.parseRawData | test | protected function parseRawData($rawData)
{
if (!$rawData) return;
if (!empty($rawData['result_xdr'])) {
$xdr = new XdrBuffer(base64_decode($rawData['result_xdr']));
$this->result = TransactionResult::fromXdr($xdr);
}
} | php | {
"resource": ""
} |
q257350 | TransactionEnvelope.sign | test | public function sign($keypairsOrsecretKeyStrings, Server $server = null)
{
if (!is_array($keypairsOrsecretKeyStrings)) $keypairsOrsecretKeyStrings = [$keypairsOrsecretKeyStrings];
$transactionHash = null;
if ($server) {
$transactionHash = $server->getApiClient()->hash($this->transactionBuilder);
}
else {
$transactionHash = $this->transactionBuilder->hash();
}
foreach ($keypairsOrsecretKeyStrings as $keypairOrSecretKeyString) {
if (is_string($keypairOrSecretKeyString)) {
$keypairOrSecretKeyString = Keypair::newFromSeed($keypairOrSecretKeyString);
}
$decorated = $keypairOrSecretKeyString->signDecorated($transactionHash);
$this->signatures->append($decorated);
}
return $this;
} | php | {
"resource": ""
} |
q257351 | ApiClient.submitTransaction | test | public function submitTransaction(TransactionBuilder $transactionBuilder, $signingAccountSeedString)
{
$transactionEnvelope = $transactionBuilder->sign($signingAccountSeedString);
return $this->submitB64Transaction(base64_encode($transactionEnvelope->toXdr()));
} | php | {
"resource": ""
} |
q257352 | Patch.fromText | test | public function fromText($patchText){
$patches = array();
if (!$patchText) {
return $patches;
}
$lines = explode("\n", $patchText);
while (count($lines)) {
$line = $lines[0];
if (!preg_match("/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/", $line, $m)) {
throw new \InvalidArgumentException("Invalid patch string: " . $line);
}
$patch = new PatchObject();
$patch->setStart1($m[1]);
if ($m[2] == '') {
$patch->setStart1($patch->getStart1() - 1);
$patch->setLength1(1);
} elseif ($m[2] == '0') {
$patch->setLength1(0);
} else {
$patch->setStart1($patch->getStart1() - 1);
$patch->setLength1($m[2]);
}
$patch->setStart2($m[3]);
if ($m[4] == '') {
$patch->setStart2($patch->getStart2() - 1);
$patch->setLength2(1);
} elseif ($m[4] == '0') {
$patch->setLength2(0);
} else {
$patch->setStart2($patch->getStart2() - 1);
$patch->setLength2($m[4]);
}
$patches[] = $patch;
array_shift($lines);
while (count($lines)) {
$line = $lines[0];
if ($line) {
$sign = mb_substr($line, 0, 1);
} else {
$sign = '';
}
$text = Utils::unescapeString(mb_substr($line, 1));
switch ($sign) {
case '+':
// Insertion.
$patch->appendChanges(array(Diff::INSERT, $text));
break;
case '-':
// Deletion.
$patch->appendChanges(array(Diff::DELETE, $text));
break;
case ' ':
// Minor equality.
$patch->appendChanges(array(Diff::EQUAL, $text));
break;
case '@':
// Start of next patch.
break 2;
case '':
// Blank line? Whatever.
break;
default:
// WTF?
throw new \UnexpectedValueException("Invalid patch mode: " . $sign . PHP_EOL . $text);
}
array_shift($lines);
}
}
return $patches;
} | php | {
"resource": ""
} |
q257353 | Patch.toText | test | public function toText($patches)
{
$text = '';
foreach ($patches as $patch) {
$text .= (string)$patch;
}
return $text;
} | php | {
"resource": ""
} |
q257354 | Patch.addContext | test | public function addContext(PatchObject $patch, $text)
{
if (!mb_strlen($text)) {
return;
}
$padding = 0;
$pattern = mb_substr($text, $patch->getStart1(), $patch->getLength1());
// Look for the first and last matches of pattern in text.
// If two different matches are found, increase the pattern length.
$match = $this->getMatch();
while (
(!$pattern || mb_strpos($text, $pattern) !== mb_strrpos($text, $pattern)) &&
($match->getMaxBits() == 0 || mb_strlen($pattern) < $match->getMaxBits() - 2 * $this->getMargin())
) {
$padding += $this->getMargin();
$pattern = mb_substr(
$text,
max(0, $patch->getStart2() - $padding),
$patch->getStart2() + $patch->getLength1() + $padding - max(0, $patch->getStart2() - $padding)
);
}
// Add one chunk for good luck.
$padding += $this->getMargin();
// Add the prefix.
$prefix = mb_substr($text, max(0, $patch->getStart2() - $padding), min($patch->getStart2(), $padding));
if ($prefix != '') {
$patch->prependChanges(array(Diff::EQUAL, $prefix));
}
// Add the suffix.
$suffix = mb_substr($text, $patch->getStart2() + $patch->getLength1(), $padding);
if ($suffix != '') {
$patch->appendChanges(array(Diff::EQUAL, $suffix));
}
// Roll back the start points.
$prefixLen = mb_strlen($prefix);
$patch->setStart1($patch->getStart1() - $prefixLen);
$patch->setStart2($patch->getStart2() - $prefixLen);
// Extend lengths.
$suffixLen = mb_strlen($suffix);
$patch->setLength1($patch->getLength1() + $prefixLen + $suffixLen);
$patch->setLength2($patch->getLength2() + $prefixLen + $suffixLen);
} | php | {
"resource": ""
} |
q257355 | Patch.deepCopy | test | protected function deepCopy($patches)
{
$patchesCopy = array();
foreach ($patches as $patch) {
$patchCopy = clone $patch;
$patchesCopy[] = $patchCopy;
}
return $patchesCopy;
} | php | {
"resource": ""
} |
q257356 | Match.bitapScore | test | protected function bitapScore($errors, $matchLoc, $patternLen, $searchLoc)
{
$accuracy = $errors / $patternLen;
$proximity = abs($searchLoc - $matchLoc);
if (!$this->getDistance()) {
// Dodge divide by zero error.
return $proximity ? 1.0 : $accuracy;
}
return $accuracy + ($proximity/$this->getDistance());
} | php | {
"resource": ""
} |
q257357 | Match.alphabet | test | public function alphabet($pattern)
{
$s = array();
foreach (preg_split("//u", $pattern, -1, PREG_SPLIT_NO_EMPTY) as $char) {
$s[$char] = 0;
}
for ($i = 0; $i < mb_strlen($pattern); $i++) {
$s[mb_substr($pattern, $i, 1)] |= 1 << (mb_strlen($pattern) - $i - 1);
}
return $s;
} | php | {
"resource": ""
} |
q257358 | Diff.prettyHtml | test | public function prettyHtml()
{
$diffs = $this->getChanges();
$html = '';
foreach ($diffs as $change) {
$op = $change[0];
$data = $change[1];
$text = str_replace(array(
'&', '<', '>', "\n",
), array(
'&', '<', '>', '¶<br>',
), $data);
if ($op == self::INSERT) {
$html .= '<ins style="background:#e6ffe6;">' . $text . '</ins>';
} elseif ($op == self::DELETE) {
$html .= '<del style="background:#ffe6e6;">' . $text . '</del>';
} else {
$html .= '<span>' . $text . '</span>';
}
}
return $html;
} | php | {
"resource": ""
} |
q257359 | Diff.toDelta | test | public function toDelta() {
$diffs = $this->getChanges();
$text = array();
foreach ($diffs as $change) {
$op = $change[0];
$data = $change[1];
if ($op == self::INSERT) {
$text[] = '+'. Utils::escapeString($data);
} elseif ($op == self::DELETE) {
$text[] = '-' . mb_strlen($data);
} else {
$text[] = '=' . mb_strlen($data);
}
}
return implode("\t", $text);
} | php | {
"resource": ""
} |
q257360 | Diff.fromDelta | test | public function fromDelta($text1, $delta)
{
$diffs = array();
// Cursor in text1
$pointer = 0;
$tokens = explode("\t", $delta);
foreach ($tokens as $token) {
if ($token == '') {
// Blank tokens are ok (from a trailing \t).
continue;
}
// Each token begins with a one character parameter which specifies the
// operation of this token (delete, insert, equality).
$op = mb_substr($token, 0, 1);
$param = mb_substr($token, 1);
switch ($op) {
case '+':
$diffs[] = array(
self::INSERT,
Utils::unescapeString($param),
);
break;
case '-':
case '=':
if (!is_numeric($param)) {
throw new \InvalidArgumentException('Invalid number in delta: ' . $param);
} elseif ($param < 0) {
throw new \InvalidArgumentException('Negative number in delta: ' . $param);
} else {
$n = (int) $param;
}
$text = mb_substr($text1, $pointer, $n);
$pointer += $n;
$diffs[] = array(
$op == '=' ? self::EQUAL : self::DELETE,
$text,
);
break;
default:
// Anything else is an error.
throw new \InvalidArgumentException('Invalid diff operation in delta: ' . $op);
}
}
if ($pointer != mb_strlen($text1)) {
throw new \InvalidArgumentException('Delta length (' . $pointer . ') does not equal source text length (' . mb_strlen($text1) . ').');
}
$this->setChanges($diffs);
return $this;
} | php | {
"resource": ""
} |
q257361 | Diff.levenshtein | test | public function levenshtein()
{
$diffs = $this->getChanges();
$levenshtein = 0;
$insertions = 0;
$deletions = 0;
foreach ($diffs as $change) {
$op = $change[0];
$text = $change[1];
switch ($op) {
case self::INSERT:
$insertions += mb_strlen($text);
break;
case self::DELETE:
$deletions += mb_strlen($text);
break;
case self::EQUAL:
// A deletion and an insertion is one substitution.
$levenshtein += max($insertions, $deletions);
$insertions = 0;
$deletions = 0;
break;
}
}
$levenshtein += max($insertions, $deletions);
return $levenshtein;
} | php | {
"resource": ""
} |
q257362 | Diff.compute | test | protected function compute($text1, $text2, $checklines, $deadline)
{
if ($text1 == '') {
// Just add some text (speedup).
return array(
array(self::INSERT, $text2),
);
}
if ($text2 == '') {
// Just delete some text (speedup).
return array(
array(self::DELETE, $text1),
);
}
if (mb_strlen($text1) < mb_strlen($text2)) {
$shortText = $text1;
$longText = $text2;
} else {
$shortText = $text2;
$longText = $text1;
}
$i = mb_strpos($longText, $shortText);
if ($i !== false) {
// Shorter text is inside the longer text (speedup).
$diffs = array(
array(self::INSERT, mb_substr($longText, 0, $i)),
array(self::EQUAL, $shortText),
array(self::INSERT, mb_substr($longText, $i + mb_strlen($shortText))),
);
// Swap insertions for deletions if diff is reversed.
if (mb_strlen($text2) < mb_strlen($text1)) {
$diffs[0][0] = self::DELETE;
$diffs[2][0] = self::DELETE;
}
return $diffs;
}
if (mb_strlen($shortText) == 1) {
// Single character string.
// After the previous speedup, the character can't be an equality.
$diffs = array(
array(self::DELETE, $text1),
array(self::INSERT, $text2),
);
return $diffs;
}
// Don't risk returning a non-optimal diff if we have unlimited time.
if ($this->getTimeout() > 0) {
// Check to see if the problem can be split in two.
$hm = $this->getToolkit()->halfMatch($text1, $text2);
if ($hm) {
// A half-match was found, sort out the return data.
list($text1_a, $text1_b, $text2_a, $text2_b, $mid_common) = $hm;
// Send both pairs off for separate processing.
$diffA = new Diff();
$diffA->main($text1_a, $text2_a, $checklines, $deadline);
$diffB = new Diff();
$diffB->main($text1_b, $text2_b, $checklines, $deadline);
// Merge the results.
$diffs = array_merge(
$diffA->getChanges(),
array(
array(self::EQUAL, $mid_common),
),
$diffB->getChanges()
);
return $diffs;
}
}
if ($checklines
&& mb_strlen($text1) > Diff::LINEMODE_THRESOLD
&& mb_strlen($text2) > Diff::LINEMODE_THRESOLD) {
return $this->lineMode($text1, $text2, $deadline);
}
return $this->bisect($text1, $text2, $deadline);
} | php | {
"resource": ""
} |
q257363 | Diff.lineMode | test | protected function lineMode($text1, $text2, $deadline)
{
// Scan the text on a line-by-line basis first.
list($text1, $text2, $lineArray) = $this->getToolkit()->linesToChars($text1, $text2);
$diff = new Diff();
$diff->main($text1, $text2, false, $deadline);
$diffs = $diff->getChanges();
// Convert the diff back to original text.
$this->getToolkit()->charsToLines($diffs, $lineArray);
$diff->setChanges($diffs);
// Eliminate freak matches (e.g. blank lines)
$diff->cleanupSemantic();
$diffs = $diff->getChanges();
// Rediff any replacement blocks, this time character-by-character.
// Add a dummy entry at the end.
array_push($diffs, array(self::EQUAL, ''));
$pointer = 0;
$countDelete = 0;
$countInsert = 0;
$textDelete = '';
$textInsert = '';
while ($pointer < count($diffs)) {
switch ($diffs[$pointer][0]) {
case self::DELETE:
$countDelete++;
$textDelete .= $diffs[$pointer][1];
break;
case self::INSERT:
$countInsert++;
$textInsert .= $diffs[$pointer][1];
break;
case self::EQUAL:
// Upon reaching an equality, check for prior redundancies.
if ($countDelete > 0 && $countInsert > 0) {
// Delete the offending records and add the merged ones.
$subDiff = new Diff();
$subDiff->main($textDelete, $textInsert, false, $deadline);
array_splice($diffs, $pointer - $countDelete - $countInsert, $countDelete + $countInsert, $subDiff->getChanges());
$pointer = $pointer - $countDelete - $countInsert + count($subDiff->getChanges());
}
$countDelete = 0;
$countInsert = 0;
$textDelete = '';
$textInsert = '';
break;
}
$pointer++;
}
// Remove the dummy entry at the end.
array_pop($diffs);
return $diffs;
} | php | {
"resource": ""
} |
q257364 | Diff.bisectSplit | test | protected function bisectSplit($text1, $text2, $x, $y, $deadline)
{
$text1A = mb_substr($text1, 0, $x);
$text2A = mb_substr($text2, 0, $y);
$text1B = mb_substr($text1, $x);
$text2B = mb_substr($text2, $y);
// Compute both diffs serially.
$diffA = new Diff();
$diffA->main($text1A, $text2A, false, $deadline);
$diffB = new Diff();
$diffB->main($text1B, $text2B, false, $deadline);
return array_merge($diffA->getChanges(), $diffB->getChanges());
} | php | {
"resource": ""
} |
q257365 | DiffToolkit.commonPrefix | test | public function commonPrefix($text1, $text2)
{
// Quick check for common null cases.
if ($text1 == '' || $text2 == '' || mb_substr($text1, 0, 1) != mb_substr($text2, 0, 1)) {
return 0;
}
// Binary search.
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
$pointermin = 0;
$pointermax = min(mb_strlen($text1), mb_strlen($text2));
$pointermid = $pointermax;
$pointerstart = 0;
while ($pointermin < $pointermid) {
if (mb_substr($text1, $pointerstart, $pointermid - $pointerstart) == mb_substr($text2, $pointerstart,
$pointermid - $pointerstart)
) {
$pointermin = $pointermid;
$pointerstart = $pointermin;
} else {
$pointermax = $pointermid;
}
$pointermid = (int)(($pointermax - $pointermin) / 2) + $pointermin;
}
return $pointermid;
} | php | {
"resource": ""
} |
q257366 | DiffToolkit.commonSuffix | test | public function commonSuffix($text1, $text2)
{
// Quick check for common null cases.
if ($text1 == '' || $text2 == '' || mb_substr($text1, -1, 1) != mb_substr($text2, -1, 1)) {
return 0;
}
// Binary search.
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
$pointermin = 0;
$pointermax = min(mb_strlen($text1), mb_strlen($text2));
$pointermid = $pointermax;
$pointerend = 0;
while ($pointermin < $pointermid) {
if (mb_substr($text1, -$pointermid, $pointermid - $pointerend) == mb_substr($text2, -$pointermid,
$pointermid - $pointerend)
) {
$pointermin = $pointermid;
$pointerend = $pointermin;
} else {
$pointermax = $pointermid;
}
$pointermid = (int)(($pointermax - $pointermin) / 2) + $pointermin;
}
return $pointermid;
} | php | {
"resource": ""
} |
q257367 | DiffToolkit.commontOverlap | test | public function commontOverlap($text1, $text2)
{
// Cache the text lengths to prevent multiple calls.
$text1_length = mb_strlen($text1);
$text2_length = mb_strlen($text2);
// Eliminate the null case.
if (!$text1_length || !$text2_length) {
return 0;
}
// Truncate the longer string.
if ($text1_length > $text2_length) {
$text1 = mb_substr($text1, -$text2_length);
} elseif ($text1_length < $text2_length) {
$text2 = mb_substr($text2, 0, $text1_length);
}
$text_length = min($text1_length, $text2_length);
// Quick check for the worst case.
if ($text1 == $text2) {
return $text_length;
}
// Start by looking for a single character match
// and increase length until no match is found.
// Performance analysis: http://neil.fraser.name/news/2010/11/04/
$best = 0;
$length = 1;
while (true) {
$pattern = mb_substr($text1, -$length);
$found = mb_strpos($text2, $pattern);
if ($found === false) {
break;
}
$length += $found;
if ($found == 0 || mb_substr($text1, -$length) == mb_substr($text2, 0, $length)) {
$best = $length;
$length += 1;
}
}
return $best;
} | php | {
"resource": ""
} |
q257368 | DiffToolkit.halfMatch | test | public function halfMatch($text1, $text2)
{
if (mb_strlen($text1) > mb_strlen($text2)) {
$longtext = $text1;
$shorttext = $text2;
} else {
$shorttext = $text1;
$longtext = $text2;
}
if (mb_strlen($longtext) < 4 || mb_strlen($shorttext) * 2 < mb_strlen(mb_strlen($longtext))) {
// Pointless
return null;
}
// First check if the second quarter is the seed for a half-match.
$hm1 = $this->halfMatchI($longtext, $shorttext, (int)((mb_strlen($longtext) + 3) / 4));
// Check again based on the third quarter.
$hm2 = $this->halfMatchI($longtext, $shorttext, (int)((mb_strlen($longtext) + 1) / 2));
if (empty($hm1) && empty($hm2)) {
return null;
} elseif (empty($hm2)) {
$hm = $hm1;
} elseif (empty($hm1)) {
$hm = $hm2;
} else {
// Both matched. Select the longest.
if (mb_strlen($hm1[4] > $hm2[4])) {
$hm = $hm1;
} else {
$hm = $hm2;
}
}
// A half-match was found, sort out the return data.
if (mb_strlen($text1) > mb_strlen($text2)) {
return array($hm[0], $hm[1], $hm[2], $hm[3], $hm[4]);
} else {
return array($hm[2], $hm[3], $hm[0], $hm[1], $hm[4]);
}
} | php | {
"resource": ""
} |
q257369 | DiffToolkit.halfMatchI | test | protected function halfMatchI($longtext, $shorttext, $i)
{
$seed = mb_substr($longtext, $i, (int)(mb_strlen($longtext) / 4));
$best_common = $best_longtext_a = $best_longtext_b = $best_shorttext_a = $best_shorttext_b = '';
$j = mb_strpos($shorttext, $seed);
while ($j !== false) {
$prefixLegth = $this->commonPrefix(mb_substr($longtext, $i), mb_substr($shorttext, $j));
$suffixLegth = $this->commonSuffix(mb_substr($longtext, 0, $i), mb_substr($shorttext, 0, $j));
if (mb_strlen($best_common) < $suffixLegth + $prefixLegth) {
$best_common = mb_substr($shorttext, $j - $suffixLegth, $suffixLegth) . mb_substr($shorttext, $j,
$prefixLegth);
$best_longtext_a = mb_substr($longtext, 0, $i - $suffixLegth);
$best_longtext_b = mb_substr($longtext, $i + $prefixLegth);
$best_shorttext_a = mb_substr($shorttext, 0, $j - $suffixLegth);
$best_shorttext_b = mb_substr($shorttext, $j + $prefixLegth);
}
$j = mb_strpos($shorttext, $seed, $j + 1);
}
if (mb_strlen($best_common) * 2 >= mb_strlen($longtext)) {
return array($best_longtext_a, $best_longtext_b, $best_shorttext_a, $best_shorttext_b, $best_common);
} else {
return null;
}
} | php | {
"resource": ""
} |
q257370 | DiffToolkit.linesToChars | test | public function linesToChars($text1, $text2)
{
// e.g. $lineArray[4] == "Hello\n"
$lineArray = array();
// e.g. $lineHash["Hello\n"] == 4
$lineHash = array();
// "\x00" is a valid character, but various debuggers don't like it.
// So we'll insert a junk entry to avoid generating a null character.
$lineArray[] = '';
$chars1 = $this->linesToCharsMunge($text1, $lineArray, $lineHash);
$chars2 = $this->linesToCharsMunge($text2, $lineArray, $lineHash);
return array($chars1, $chars2, $lineArray);
} | php | {
"resource": ""
} |
q257371 | SmscRuChannel.getRecipients | test | protected function getRecipients($notifiable, Notification $notification)
{
$to = $notifiable->routeNotificationFor('smscru', $notification);
if ($to === null || $to === false || $to === '') {
return [];
}
return \is_array($to) ? $to : [$to];
} | php | {
"resource": ""
} |
q257372 | ServiceProvider.version | test | public function version()
{
$app = $this->app;
$tab = explode('Laravel Components ', $app->version());
return intval(empty($tab[1]) ? $app::VERSION : $tab[1]);
} | php | {
"resource": ""
} |
q257373 | ServiceProvider.registerPugCompiler | test | public function registerPugCompiler($subExtension = '')
{
// Add resolver
$this->getEngineResolver()->register('pug' . $subExtension, function () use ($subExtension) {
return new CompilerEngine($this->app['Bkwld\LaravelPug\Pug' . ucfirst(ltrim($subExtension, '.')) . 'Compiler']);
});
// Add extensions
$this->app['view']->addExtension('pug' . $subExtension, 'pug' . $subExtension);
$this->app['view']->addExtension('pug' . $subExtension . '.php', 'pug' . $subExtension);
$this->app['view']->addExtension('jade' . $subExtension, 'pug' . $subExtension);
$this->app['view']->addExtension('jade' . $subExtension . '.php', 'pug' . $subExtension);
} | php | {
"resource": ""
} |
q257374 | ServiceProvider.getConfig | test | public function getConfig()
{
$key = $this->version() >= 5 ? 'laravel-pug' : 'laravel-pug::config';
return array_merge(array(
'allow_composite_extensions' => true,
), $this->app->make('config')->get($key));
} | php | {
"resource": ""
} |
q257375 | PugHandlerTrait.construct | test | public function construct(array $pugTarget, Filesystem $files, array $config, $defaultCachePath = null)
{
$this->pugTarget = $pugTarget;
$cachePath = null;
foreach (array('cache_dir', 'cache', 'defaultCache') as $name) {
if (isset($config[$name])) {
$cachePath = $config[$name];
break;
}
}
if (!$cachePath) {
$cachePath = $defaultCachePath ?: $this->getCachePath();
}
parent::__construct($files, $cachePath);
} | php | {
"resource": ""
} |
q257376 | PugHandlerTrait.getPug | test | public function getPug()
{
if (!$this->pug) {
$this->pug = $this->pugTarget[0][$this->pugTarget[1]];
}
return $this->pug;
} | php | {
"resource": ""
} |
q257377 | PugHandlerTrait.getCachePath | test | public function getCachePath()
{
if ($this->cachePath) {
return $this->cachePath;
}
$cachePath = $this->getOption('cache');
return is_string($cachePath) ? $cachePath : $this->getOption('defaultCache');
} | php | {
"resource": ""
} |
q257378 | PugHandlerTrait.getOption | test | public function getOption($name, $default = null)
{
$pug = $this->getPug();
try {
if (method_exists($pug, 'hasOption') && !$pug->hasOption($name)) {
throw new \InvalidArgumentException('invalid option');
}
return $pug->getOption($name);
} catch (\InvalidArgumentException $exception) {
return $default;
}
} | php | {
"resource": ""
} |
q257379 | PugHandlerTrait.isExpired | test | public function isExpired($path)
{
if (!$this->cachePath || parent::isExpired($path)) {
return true;
}
return is_subclass_of('\Pug\Pug', '\Phug\Renderer') && $this->hasExpiredImport($path);
} | php | {
"resource": ""
} |
q257380 | PugHandlerTrait.extractPath | test | public function extractPath($path)
{
if ($path && method_exists($this, 'setPath')) {
$this->setPath($path);
}
if (!$path && method_exists($this, 'getPath')) {
$path = $this->getPath();
}
if (!$path) {
throw new InvalidArgumentException('Missing path argument.');
}
return $path;
} | php | {
"resource": ""
} |
q257381 | AmoCrmManager.getClient | test | public function getClient()
{
if (!$this->client instanceof Client) {
$this->client = new Client(
$this->config->get('amocrm.domain'),
$this->config->get('amocrm.login'),
$this->config->get('amocrm.hash')
);
}
return $this->client;
} | php | {
"resource": ""
} |
q257382 | AmoCrmManager.getB2BFamily | test | public function getB2BFamily()
{
$client = $this->getClient();
return new B2BFamily($client,
$this->config->get('amocrm.b2bfamily.appkey'),
$this->config->get('amocrm.b2bfamily.secret'),
$this->config->get('amocrm.b2bfamily.email'),
$this->config->get('amocrm.b2bfamily.password')
);
} | php | {
"resource": ""
} |
q257383 | Optimizer.hashPrint | test | private function hashPrint($input)
{
// Get the stronger hashing algorithm available to minimize collision risks
$algorithms = hash_algos();
$algorithm = $algorithms[0];
$number = 0;
foreach ($algorithms as $hashAlgorithm) {
$lettersLength = substr($hashAlgorithm, 0, 2) === 'md'
? 2
: (substr($hashAlgorithm, 0, 3) === 'sha'
? 3
: 0
);
if ($lettersLength) {
$hashNumber = substr($hashAlgorithm, $lettersLength);
if ($hashNumber > $number) {
$number = $hashNumber;
$algorithm = $hashAlgorithm;
}
continue;
}
}
return rtrim(strtr(base64_encode(hash($algorithm, $input, true)), '+/', '-_'), '=');
} | php | {
"resource": ""
} |
q257384 | Optimizer.resolve | test | public function resolve($file)
{
return $this->locator->locate(
$file,
$this->paths,
isset($this->options['extensions'])
? $this->options['extensions']
: ['', '.pug', '.jade']
);
} | php | {
"resource": ""
} |
q257385 | Optimizer.displayFile | test | public function displayFile($__pug_file, array $__pug_parameters = [])
{
if ($this->isExpired($__pug_file, $__pug_cache_file)) {
if (isset($this->options['render'])) {
call_user_func($this->options['render'], $__pug_file, $__pug_parameters, $this->options);
return;
}
if (isset($this->options['renderer'])) {
$this->options['renderer']->displayFile($__pug_file, $__pug_parameters);
return;
}
if (isset($this->options['renderer_class_name'])) {
$className = $this->options['renderer_class_name'];
$renderer = new $className($this->options);
$renderer->displayFile($__pug_file, $__pug_parameters);
return;
}
$facade = isset($this->options['facade'])
? $this->options['facade']
: static::FACADE;
if (is_callable([$facade, 'displayFile'])) {
$facade::displayFile($__pug_file, $__pug_parameters, $this->options);
return;
}
throw new \RuntimeException(
'No valid render method, renderer engine, renderer class or facade provided.'
);
}
if (isset($this->options['shared_variables'])) {
$__pug_parameters = array_merge($this->options['shared_variables'], $__pug_parameters);
}
if (isset($this->options['globals'])) {
$__pug_parameters = array_merge($this->options['globals'], $__pug_parameters);
}
if (isset($this->options['self']) && $this->options['self']) {
$self = $this->options['self'] === true ? 'self' : strval($this->options['self']);
$__pug_parameters = [$self => $__pug_parameters];
}
extract($__pug_parameters);
include $__pug_cache_file;
} | php | {
"resource": ""
} |
q257386 | ExtensionsTrait.getExtensionsOptions | test | public static function getExtensionsOptions(array $extensions, array $options = [])
{
$methods = static::getExtensionsGetters();
foreach ($extensions as $extensionClassName) {
if (is_a($extensionClassName, ModuleInterface::class, true)) {
if (!isset($options['modules'])) {
$options['modules'] = [];
}
$options['modules'][] = $extensionClassName;
continue;
}
static::extractExtensionOptions($options, $extensionClassName, $methods);
}
return $options;
} | php | {
"resource": ""
} |
q257387 | Phug.removeOptions | test | public static function removeOptions($path, $options)
{
if (self::$renderer && (empty($path) || self::$renderer->hasOption($path))) {
if (is_array($options)) {
foreach ($options as $key => $value) {
if (is_int($key)) {
$callbacks = self::$renderer->getOption($path);
if (!is_array($callbacks) || is_callable($callbacks)) {
$callbacks = [$callbacks];
}
self::$renderer->setOption($path, array_filter(
$callbacks,
function ($item) use ($value) {
return $item !== $value;
}
));
continue;
}
static::removeOptions(array_merge($path, [$key]), $value);
}
return;
}
self::$renderer->unsetOption($path);
}
} | php | {
"resource": ""
} |
q257388 | Phug.reset | test | public static function reset()
{
static::resetFacadeOptions();
self::$renderer = null;
self::$extensions = [];
self::$filters = [];
self::$keywords = [];
} | php | {
"resource": ""
} |
q257389 | Phug.getRenderer | test | public static function getRenderer(array $options = [])
{
$options = static::getOptions($options);
if (!self::$renderer) {
$rendererClassName = self::getRendererClassName();
self::$renderer = new $rendererClassName($options);
} elseif (!empty($options)) {
self::$renderer->reInitOptions($options);
self::$renderer->getCompiler()->getFormatter()->initFormats();
}
return self::$renderer;
} | php | {
"resource": ""
} |
q257390 | Phug.addFilter | test | public static function addFilter($name, $filter)
{
$key = self::normalizeFilterName($name);
if (isset(self::$filters[$key])) {
throw new PhugException(
'Filter '.$name.' is already set.'
);
}
self::setFilter($name, $filter);
} | php | {
"resource": ""
} |
q257391 | Phug.addKeyword | test | public static function addKeyword($name, $keyword)
{
$key = self::normalizeKeywordName($name);
if (isset(self::$keywords[$key])) {
throw new PhugException(
'Keyword '.$name.' is already set.'
);
}
self::setKeyword($name, $keyword);
} | php | {
"resource": ""
} |
q257392 | Phug.textualCacheDirectory | test | public static function textualCacheDirectory($source, $destination = null, $options = null)
{
list($success, $errors, $errorDetails) = static::cacheDirectory($source, $destination, $options);
return
"$success templates cached.\n".
"$errors templates failed to be cached.\n".
implode('', array_map(function ($detail) {
return $detail['inputFile']."\n".
$detail['error']->getMessage()."\n".
$detail['error']->getTraceAsString();
}, $errorDetails));
} | php | {
"resource": ""
} |
q257393 | Cli.run | test | public function run($arguments)
{
$outputFile = $this->getNamedArgument($arguments, ['--output-file', '-o']);
$bootstrapFile = $this->getNamedArgument($arguments, ['--bootstrap', '-b']);
if ($bootstrapFile) {
include $bootstrapFile;
} elseif (file_exists('phugBootstrap.php')) {
include 'phugBootstrap.php';
}
list(, $action) = array_pad($arguments, 2, null);
$arguments = array_slice($arguments, 2);
$facade = $this->facade;
$method = $this->convertToCamelCase($action);
$customMethods = $this->getCustomMethods();
if (!$action) {
echo "You must provide a method.\n";
$this->listAvailableMethods($customMethods);
return false;
}
if (!in_array($method, iterator_to_array($this->getAvailableMethods($customMethods)))) {
echo "The method $action is not available as CLI command in the $facade facade.\n";
$this->listAvailableMethods($customMethods);
return false;
}
return $this->execute($facade, $method, $arguments, $outputFile);
} | php | {
"resource": ""
} |
q257394 | Cli.getAvailableMethods | test | public function getAvailableMethods($customMethods = null)
{
foreach ([$this->methods, $customMethods ?: $this->getCustomMethods()] as $methods) {
foreach ($methods as $method => $action) {
$method = is_int($method) ? $action : $method;
if (substr($method, 0, 2) !== '__') {
yield $method;
}
}
}
} | php | {
"resource": ""
} |
q257395 | Cli.listAvailableMethods | test | public function listAvailableMethods($customMethods = null)
{
echo "Available methods are:\n";
foreach ($this->getAvailableMethods($customMethods ?: $this->getCustomMethods()) as $method) {
$action = $this->convertToKebabCase($method);
$target = isset($this->methods[$method]) ? $this->methods[$method] : $method;
$key = array_search($target, $this->methods);
if (is_int($key)) {
$key = $this->methods[$key];
}
echo ' - '.$action.($key && $key !== $method
? ' ('.$this->convertToKebabCase($key).' alias)'
: ''
)."\n";
}
} | php | {
"resource": ""
} |
q257396 | SEOEditorMetaDescriptionColumn.getErrors | test | public function getErrors(DataObject $record)
{
$errors = [];
if (strlen($record->MetaDescription) < 10) {
$errors[] = 'seo-editor-error-too-short';
}
if (strlen($record->MetaDescription) > 160) {
$errors[] = 'seo-editor-error-too-long';
}
if (strlen(SiteTree::get()->filter('MetaDescription', $record->MetaDescription)->count() > 1)) {
$errors[] = 'seo-editor-error-duplicate';
}
return $errors;
} | php | {
"resource": ""
} |
q257397 | SEOEditorAdmin.getList | test | public function getList()
{
$list = parent::getList();
$params = $this->request->requestVar('q');
if (isset($params['RemoveEmptyMetaTitles']) && $params['RemoveEmptyMetaTitles']) {
$list = $this->removeEmptyAttributes($list, 'MetaTitle');
}
if (isset($params['RemoveEmptyMetaDescriptions']) && $params['RemoveEmptyMetaDescriptions']) {
$list = $this->removeEmptyAttributes($list, 'MetaDescription');
}
$list = $this->markDuplicates($list);
if (isset($params['DuplicatesOnly']) && $params['DuplicatesOnly']) {
$list = $list->filter('IsDuplicate', true);
}
$list = $list->sort('ID');
return $list;
} | php | {
"resource": ""
} |
q257398 | SEOEditorAdmin.markDuplicates | test | private function markDuplicates($list)
{
$duplicates = $this->findDuplicates($list, 'MetaTitle')->map('ID', 'ID')->toArray();
$duplicateList = new ArrayList();
foreach ($list as $item) {
if (in_array($item->ID, $duplicates)) {
$item->IsDuplicate = true;
$duplicateList->push($item);
}
}
$duplicates = $this->findDuplicates($list, 'MetaDescription')->map('ID', 'ID')->toArray();
foreach ($list as $item) {
if (in_array($item->ID, $duplicates)) {
$item->IsDuplicate = true;
if (!$list->byID($item->ID)) {
$duplicateList->push($item);
}
}
}
$duplicateList->merge($list);
$duplicateList->removeDuplicates();
return $duplicateList;
} | php | {
"resource": ""
} |
q257399 | SEOEditorAdmin.findDuplicates | test | private function findDuplicates(SS_List $list, $type)
{
$pageAttributes = $list->map('ID', $type)->toArray();
$potentialDuplicateAttributes = array_unique(
array_diff_assoc(
$pageAttributes,
array_unique($pageAttributes)
)
);
$duplicateAttributes = array_filter($pageAttributes, function ($value) use ($potentialDuplicateAttributes) {
return in_array($value, $potentialDuplicateAttributes);
});
if (!count($duplicateAttributes)) {
return $list;
}
return $list->filter([
'ID' => array_keys($duplicateAttributes),
]);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.