sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function validate($attribute, $value, $parameters)
{
if ($parameters) {
$this->dictionary->setDictionary($parameters);
$this->badwords = $this->dictionary->getDictionary();
}
return !$this->isProfane($value);
} | Method to extends to Validator.
@param string $attribute
@param midex $value
@param array $parameters
@param \Illuminate\Contracts\Validation\Validator $validator [description]
@return bool | entailment |
public function addConnection($uriString)
{
if (!isset(self::$connectionList[$uriString])) {
self::$connectionList[$uriString] = Factory::getDbRelationalInstance($uriString);
if (self::$transaction) {
self::$connectionList[$uriString]->beginTransaction();
}
}
return self::$connectionList[$uriString];
} | Add or reuse a connection
@param $uriString
@return \ByJG\AnyDataset\Db\DbDriverInterface | entailment |
public function beginTransaction()
{
if (self::$transaction) {
throw new TransactionException("Transaction Already Started");
}
self::$transaction = true;
foreach (self::$connectionList as $dbDriver) {
$dbDriver->beginTransaction();
}
} | Start a database transaction with the opened connections
@throws \ByJG\MicroOrm\Exception\TransactionException | entailment |
public function commitTransaction()
{
if (!self::$transaction) {
throw new TransactionException("There is no Active Transaction");
}
self::$transaction = false;
foreach (self::$connectionList as $dbDriver) {
$dbDriver->commitTransaction();
}
} | Commit all open transactions
@throws \ByJG\MicroOrm\Exception\TransactionException | entailment |
public function rollbackTransaction()
{
if (!self::$transaction) {
throw new TransactionException("There is no Active Transaction");
}
self::$transaction = false;
foreach (self::$connectionList as $dbDriver) {
$dbDriver->rollbackTransaction();
}
} | Rollback all open transactions
@throws \ByJG\MicroOrm\Exception\TransactionException | entailment |
public function destroy()
{
foreach (self::$connectionList as $dbDriver) {
if (self::$transaction) {
$dbDriver->commitTransaction();
}
}
self::$transaction = false;
self::$connectionList = [];
} | Destroy all connections | entailment |
public function boot()
{
Storage::extend('gcs', function ($app, $config) {
$adapterConfiguration = ['bucket' => $config['bucket']];
$serviceBuilderConfig = [];
$optionalServiceBuilder = null;
if (array_key_exists('project_id', $config) && false === empty($config['project_id'])) {
$adapterConfiguration += ['projectId' => $config['project_id']];
$serviceBuilderConfig += ['projectId' => $config['project_id']];
}
if (array_key_exists('credentials', $config) && false === empty($config['credentials'])) {
$serviceBuilderConfig += ['keyFilePath' => $config['credentials']];
$optionalServiceBuilder = new StorageClient($serviceBuilderConfig);
}
$adapter = new GoogleCloudStorageAdapter($optionalServiceBuilder, $adapterConfiguration);
return new Filesystem($adapter);
});
} | {@inheritdoc} | entailment |
public function register()
{
if ($this->isLumen() && !$this->app->has('filesystem')) {
$this->app->singleton('filesystem', function ($app) {
/** @var \Laravel\Lumen\Application $app */
return $app->loadComponent(
'filesystems',
\Illuminate\Filesystem\FilesystemServiceProvider::class,
'filesystem'
);
});
$this->app->singleton(
\Illuminate\Contracts\Filesystem\Factory::class,
function ($app) {
return new \Illuminate\Filesystem\FilesystemManager($app);
}
);
}
$this->registerFacades();
} | Register bindings in the container.
@return void | entailment |
public function activate(Composer $composer, IOInterface $io)
{
// preload classes to prevent errors when removing the plugin
class_exists(NpmBridge::class);
class_exists(NpmBridgeFactory::class);
class_exists(NpmClient::class);
class_exists(NpmBridge::class);
class_exists(NpmVendorFinder::class);
} | Activate the plugin.
@param Composer $composer The main Composer object.
@param IOInterface $io The i/o interface to use. | entailment |
public function onPostInstallCmd(Event $event)
{
$this->bridgeFactory->createBridge($event->getIO())
->install($event->getComposer(), $event->isDevMode());
} | Handle post install command events.
@param Event $event The event to handle.
@throws NpmNotFoundException If the npm executable cannot be located.
@throws NpmCommandFailedException If the operation fails. | entailment |
public function onPostUpdateCmd(Event $event)
{
$this->bridgeFactory->createBridge($event->getIO())
->update($event->getComposer());
} | Handle post update command events.
@param Event $event The event to handle.
@throws NpmNotFoundException If the npm executable cannot be located.
@throws NpmCommandFailedException If the operation fails. | entailment |
public function evaluate($expression)
{
$lexer = $this->getLexer();
$tokens = $lexer->tokenize($expression);
$translationStrategy = new \Math\TranslationStrategy\ShuntingYard();
return $this->evaluateRPN($translationStrategy->translate($tokens));
} | Evaluate string representing mathematical expression.
@param string $expression
@return float | entailment |
private function evaluateRPN(array $expressionTokens)
{
$stack = new \SplStack();
foreach ($expressionTokens as $token) {
$tokenValue = $token->getValue();
if (is_numeric($tokenValue)) {
$stack->push((float) $tokenValue);
continue;
}
switch ($tokenValue) {
case '+':
$stack->push($stack->pop() + $stack->pop());
break;
case '-':
$n = $stack->pop();
$stack->push($stack->pop() - $n);
break;
case '*':
$stack->push($stack->pop() * $stack->pop());
break;
case '/':
$n = $stack->pop();
$stack->push($stack->pop() / $n);
break;
case '%':
$n = $stack->pop();
$stack->push($stack->pop() % $n);
break;
default:
throw new \InvalidArgumentException(sprintf('Invalid operator detected: %s', $tokenValue));
break;
}
}
return $stack->top();
} | Evaluate array sequence of tokens in Reverse Polish notation (RPN)
representing mathematical expression.
@param array $expressionTokens
@return float
@throws \InvalidArgumentException | entailment |
public static function checkCreditorIdentifier($ci)
{
$ci = preg_replace('/\s+/u', '', $ci); // remove whitespaces
$ci = strtoupper($ci); // todo does this break the ci?
if(!self::checkRestrictedPersonIdentifierSEPA($ci))
return false;
$ciCopy = $ci;
// remove creditor business code
$nationalIdentifier = substr($ci, 7);
$check = substr($ci, 0,4);
$concat = $nationalIdentifier . $check;
$concat = preg_replace('#[^a-zA-Z0-9]#u','',$concat); // remove all non-alpha-numeric characters
$concat = $check = str_replace(self::$alphabet, self::$alphabetValues, $concat);
if(self::iso7064Mod97m10ChecksumCheck($concat))
return $ciCopy;
else
return false;
} | /*
Checks if an creditor identifier (ci) is valid. Note that also if the ci is valid it does
not have to exist
@param string $ci
@return string|false The valid iban or false if it is not valid | entailment |
public static function checkIBAN($iban, $options = null)
{
$iban = preg_replace('/\s+/u', '' , $iban ); // remove whitespaces
$iban = strtoupper($iban);
if(!preg_match('/^' . self::PATTERN_IBAN . '$/',$iban))
return false;
$ibanCopy = $iban;
if(!isset($options['checkByFormat']) || $options['checkByFormat'])
{
$countryCode = substr($iban,0,2);
if(isset(self::$ibanPatterns[$countryCode])
&& !preg_match('/^' . self::$ibanPatterns[$countryCode] . '$/',$iban))
return false;
}
if(!isset($options['checkByCheckSum']) || $options['checkByCheckSum'])
{
$iban = $check = str_replace(self::$alphabet, self::$alphabetValues, $iban);
$bban = substr($iban, 6);
$check = substr($iban, 0, 6);
$concat = $bban . $check;
if( !self::iso7064Mod97m10ChecksumCheck($concat) )
return false;
}
return $ibanCopy;
} | Checks if an iban is valid. Note that also if the iban is valid it does not have to exist
@param string $iban
@param array $options valid keys:
- checkByCheckSum (boolean): If true, the IBAN checksum is
calculated (default:true)
- checkByFormat (boolean): If true, the format is checked by
regular expression (default: true)
@return string|false The valid iban or false if it is not valid | entailment |
public static function checkBIC($bic, array $options = null)
{
$bic = preg_replace('/\s+/u', '' , $bic ); // remove whitespaces
if(!empty($options['forceLongBic']) && strlen($bic) === 8)
$bic .= empty($options['forceLongBicStr']) ? 'XXX' : $options['forceLongBicStr'];
if(empty($bic) && !empty($options['allowEmptyBic']))
return '';
$bic = strtoupper($bic); // use only capital letters
if(preg_match('/^' . self::PATTERN_BIC . '$/', $bic))
return $bic;
else
return false;
} | Checks if a bic is valid. Note that also if the bic is valid it does not have to exist
@param string $bic
@param array $options Takes the following keys:
- `allowEmptyBic`: (bool) The BIC can be empty.
- `forceLongBic`: (bool) If the BIC has exact 8 characters, `forceLongBicStr`
is added. (default false)
- `forceLongBicStr`: string (default 'XXX')
@return string|false the valid bic or false if it is not valid | entailment |
public static function isNationalTransaction($iban1, $iban2)
{
// remove whitespaces
$iban1 = preg_replace('#\s+#','',$iban1);
$iban2 = preg_replace('#\s+#','',$iban2);
// check the country code
if(stripos($iban1,substr($iban2,0,2)) === 0)
return true;
else
return false;
} | Checks if both IBANs do belong to the same country.
This function does not check if the IBANs are valid.
@param string $iban1
@param string $iban2
@return bool | entailment |
public static function isEEATransaction($iban1, $iban2)
{
// remove whitespaces
$iban1 = preg_replace('#\s+#','',$iban1);
$iban2 = preg_replace('#\s+#','',$iban2);
// check if both county codes belong to the EEA
$EEA = ['IS' => 1, 'LI' => 1, 'NO' => 1, 'BE' => 1, 'BG' => 1, 'DK' => 1, 'DE' => 1,
'EE' => 1, 'FI' => 1, 'FR' => 1, 'GR' => 1, 'IE' => 1, 'IT' => 1, 'HR' => 1,
'LV' => 1, 'LT' => 1, 'LU' => 1, 'MT' => 1, 'NL' => 1, 'AT' => 1, 'PL' => 1,
'PT' => 1, 'RO' => 1, 'SE' => 1, 'SK' => 1, 'SI' => 1, 'ES' => 1, 'CZ' => 1,
'HU' => 1, 'GB' => 1, 'CY' => 1];
if(isset($EEA[strtoupper(substr($iban1,0,2))],$EEA[strtoupper(substr($iban2,0,2))]))
return true;
return false;
} | Checks if both IBANs belong to the EEA (European Economic Area)
This function does not check if the IBANs are valid.
@param string $iban1
@param string $iban2
@return bool | entailment |
public static function crossCheckIbanBic($iban, $bic)
{
// check for special cases
if(in_array(strtoupper($bic), self::$exceptionalBics))
return true;
// remove whitespaces
$iban = preg_replace('#\s+#','',$iban);
$bic = preg_replace('#\s+#','',$bic);
// check the country code
$ibanCountryCode = strtoupper(substr($iban,0,2));
$bicCountryCode = strtoupper(substr($bic,4,2));
if($ibanCountryCode === $bicCountryCode
|| (isset(self::$bicIbanCountryCodeExceptions[$ibanCountryCode])
&& in_array($bicCountryCode,self::$bicIbanCountryCodeExceptions[$ibanCountryCode])))
return true;
else
return false;
} | Checks if IBAN and BIC belong to the same country. If not, they also can not belong to
each other.
@param string $iban
@param string $bic
@return bool | entailment |
public static function sanitizeDateFormat($input, array $preferredFormats = [])
{
$dateFormats = ['d.m.Y', 'd.m.y', 'j.n.Y', 'j.n.y', 'm.d.Y', 'm.d.y', 'n.j.Y', 'n.j.y',
'Y/m/d', 'y/m/d', 'Y/n/j', 'y/n/j', 'Y.m.d', 'y.m.d', 'Y.n.j', 'y.n.j'];
// input is already in the correct format?
$dateObj = \DateTime::createFromFormat('Y-m-d',$input);
if($dateObj !== false)
return $input;
foreach($preferredFormats as $format)
{
$dateObj = \DateTime::createFromFormat($format,$input);
if($dateObj !== false)
return $dateObj->format('Y-m-d');
}
foreach($dateFormats as $format)
{
$dateObj = \DateTime::createFromFormat($format,$input);
if($dateObj !== false)
return $dateObj->format('Y-m-d');
}
return false;
} | Tries to convert the given date into the format YYYY-MM-DD (Y-m-d). Therefor it tries the
following input formats in the order of appearance: d.m.Y, d.m.y, j.n.Y, j.n.y, m.d.Y,
m.d.y, n.j.Y, n.j.y, Y/m/d, y/m/d, Y/n/j, y/n/j, Y.m.d, y.m.d, Y.n.j, y.n.j.
Notice that this method tries to interpret the first number as day-of-month. This can
lead to wrong dates if you have something like the 1st of April 2016 written as 04.01.2016.
This will be interpreted as the 4th of January 2016. This is why you have to call this
method on your owen risk and it is not included in the sanitize() method.
@param string $input The date that should be reformatted
@param array $preferredFormats An array of formats that will be checked first.
@return string|false The sanitized date or false, if it is not sanitizable. | entailment |
public static function checkCreateDateTime($input)
{
$dateObj = \DateTime::createFromFormat('Y-m-d\TH:i:s', $input);
if($dateObj !== false && $input === $dateObj->format('Y-m-d\TH:i:s'))
return $input;
else
return false;
} | Checks if the input has the format 'Y-m-d\TH:i:s'
@param string $input
@return string|false Returns $input if it is valid and false else. | entailment |
public static function getDate($date = null, $inputFormat = 'd.m.Y')
{
if(empty($date))
$dateTimeObj = new \DateTime();
else
$dateTimeObj = \DateTime::createFromFormat($inputFormat, $date);
if($dateTimeObj === false)
return false;
return $dateTimeObj->format('Y-m-d');
} | Reformat a date string from a given format to the ISODate format. Notice: 20.13.2014 is
valid and becomes 2015-01-20.
@param string $date A date string of the given input format
@param string $inputFormat default is the german format DD.MM.YYYY
@return string|false date as YYYY-MM-DD or false, if the input is not a date. | entailment |
public static function getDateWithOffset($workdayOffset, $today = null, $inputFormat = 'd.m.Y')
{
if(empty($today))
$dateTimeObj = new \DateTime();
else
$dateTimeObj = \DateTime::createFromFormat($inputFormat, $today);
if($dateTimeObj === false)
return false;
$isTargetDay = self::dateIsTargetDay($dateTimeObj);
while( !$isTargetDay || $workdayOffset > 0 )
{
$dateTimeObj->modify('+1 day');
if($isTargetDay)
$workdayOffset--;
$isTargetDay = self::dateIsTargetDay($dateTimeObj);
}
return $dateTimeObj->format('Y-m-d');
} | Computes the next TARGET2 day (including today) with respect to a TARGET2 offset.
@param int $workdayOffset a positive number of workdays to skip.
@param string $today if set, this date is used as today
@param string $inputFormat
@return string|false YYYY-MM-DD | entailment |
public static function getDateWithMinOffsetFromToday($target, $workdayMinOffset, $inputFormat = 'd.m.Y', $today = null)
{
$targetDateObj = \DateTime::createFromFormat($inputFormat,$target);
$earliestDate = self::getDateWithOffset($workdayMinOffset, $today, $inputFormat);
if($targetDateObj === false || $earliestDate === false)
return false;
$earliestDateObj = new \DateTime($earliestDate);
$isTargetDay = self::dateIsTargetDay($targetDateObj);
while( !$isTargetDay )
{
$targetDateObj->modify('+1 day');
$isTargetDay = self::dateIsTargetDay($targetDateObj);
}
if(strcmp($targetDateObj->format('Y-m-d'),$earliestDateObj->format('Y-m-d')) > 0) // target > earliest?
return $targetDateObj->format('Y-m-d');
else
return $earliestDateObj->format('Y-m-d');
} | Returns the target date, if it has at least the given offset of TARGET2 days form today. Else
the earliest date that respects the offset is returned.
@param string $target
@param int $workdayMinOffset
@param string $inputFormat
@param string $today
@return string | entailment |
private static function dateIsTargetDay(\DateTime $date)
{
// $date is a saturday or sunday?
if($date->format('N') === '6' || $date->format('N') === '7')
return false;
$day = $date->format('m-d');
if($day === '01-01' // new year's day
|| $day === '05-01' // labour day
|| $day === '12-25' // first christmas day
|| $day === '12-26') // second christmas day
return false;
$year = $date->format('Y');
$easter = easterDate((int) $year); // contains easter sunday
$goodFriday = $easter->modify('-2 days')->format('m-d'); // $easter contains now good friday
$easterMonday = $easter->modify('+3 days')->format('m-d'); // $easter contains now easter monday
if($day === $goodFriday || $day === $easterMonday)
return false;
return true;
} | Checks if $date is a SEPA TARGET day. Every day is a TARGET day except for saturdays, sundays
new year's day, good friday, easter monday, the may holiday, first and second christmas holiday.
@param \DateTime $date
@return bool | entailment |
public static function check($field, $input, array $options = null, $version = null)
{
$field = strtolower($field);
switch($field) // fall-through's are on purpose
{
case 'orgnlcdtrschmeid_id':
case 'ci': return self::checkCreditorIdentifier($input);
case 'msgid':
case 'pmtid': // next line
case 'pmtinfid': return self::checkRestrictedIdentificationSEPA1($input);
case 'orgnlmndtid':
case 'mndtid': return $version === self::SEPA_PAIN_008_001_02
|| $version === self::SEPA_PAIN_008_001_02_GBIC
? self::checkRestrictedIdentificationSEPA1($input)
: self::checkRestrictedIdentificationSEPA2($input);
case 'initgpty': // cannot be empty (and the following things also)
case 'cdtr': // cannot be empty (and the following things also)
case 'dbtr':
if(empty($input))
return false; // cannot be empty
case 'orgid_id':
return ( self::checkLength($input, self::TEXT_LENGTH_VERY_SHORT)
&& self::checkCharset($input) )
? $input : false;
case 'orgnlcdtrschmeid_nm':
case 'ultmtcdtr':
case 'ultmtdbtr':
return ( self::checkLength($input, self::TEXT_LENGTH_SHORT)
&& self::checkCharset($input) )
? $input : false;
case 'rmtinf':
return ( self::checkLength($input, self::TEXT_LENGTH_LONG)
&& self::checkCharset($input) )
? $input : false;
case 'orgnldbtracct_iban':
case 'iban': return self::checkIBAN($input,$options);
case 'orgnldbtragt_bic':
case 'orgid_bob':
case 'bic': return self::checkBIC($input,$options);
case 'ccy': return self::checkActiveOrHistoricCurrencyCode($input);
case 'amdmntind':
case 'btchbookg': return self::checkBoolean($input);
case 'instdamt': return self::checkAmountFormat($input);
case 'seqtp': return self::checkSeqType($input);
case 'lclinstrm': return self::checkLocalInstrument($input, $options);
case 'elctrncsgntr': return (self::checkLength($input, 1025) && self::checkCharset($input)) ? $input : false;
case 'dtofsgntr':
case 'reqdcolltndt':
case 'reqdexctndt': return self::checkDateFormat($input);
case 'purp': return self::checkPurpose($input);
case 'ctgypurp': return self::checkCategoryPurpose($input);
case 'orgnldbtragt': return $input; // nothing to check here
default: return false;
}
} | Checks if the input holds for the field.
@param string $field Valid fields are: 'orgnlcdtrschmeid_id','ci','msgid','pmtid','pmtinfid',
'orgnlmndtid','mndtid','initgpty','cdtr','dbtr','orgnlcdtrschmeid_nm',
'ultmtcdrt','ultmtdebtr','rmtinf','orgnldbtracct_iban','iban','bic',
'ccy','amendment', 'btchbookg','instdamt','seqtp','lclinstrm',
'elctrncsgntr','reqdexctndt','purp','ctgypurp','orgnldbtragt'
@param mixed $input
@param array $options See `checkBIC()`, `checkIBAN()` and `checkLocalInstrument()` for details.
@param int $version Can be used to specify one of the `SEPA_PAIN_*` constants.
@return false|mixed The checked input or false, if it is not valid | entailment |
public static function checkInput($field, array &$inputArray, $inputKeys, array $options = null)
{
$value = self::getValFromMultiDimInput($inputArray,$inputKeys);
if($value === false)
return false;
else
return self::check($field,$value,$options);
} | This function checks if the index of the inputArray exists and if the input is valid. The
function can be called as `checkInput($fieldName,$_POST,['input',$fieldName],$options)`
and equals `check($fieldName,$_POST['input'][$fieldName],$options)`, but checks first, if
the index exists.
@param string $field see `check()` for valid values.
@param array $inputArray
@param string|int|mixed[] $inputKeys
@param array $options see `check()` for valid values.
@return mixed|false | entailment |
public static function sanitizeInput($field, array &$inputArray, $inputKeys, $flags = 0)
{
$value = self::getValFromMultiDimInput($inputArray,$inputKeys);
if($value === false)
return false;
else
return self::sanitize($field,$value,$flags);
} | This function checks if the index of the inputArray exists and if the input is valid. The
function can be called as `sanitizeInput($fieldName,$_POST,['input',$fieldName],$flags)`
and equals `sanitize($fieldName,$_POST['input'][$fieldName],$flags)`, but checks first, if
the index exists.
@param string $field see `sanitize()` for valid values.
@param array $inputArray
@param string|int|mixed[] $inputKeys
@param int $flags see `sanitize()` for valid values.
@return mixed|false | entailment |
public static function checkAndSanitize($field, $input, $flags = 0, array $options = null)
{
$checkedInput = self::check($field, $input, $options);
if($checkedInput !== false)
return $checkedInput;
return self::sanitize($field,$input,$flags);
} | Checks the input and if it is not valid it tries to sanitize it.
@param string $field all fields check and/or sanitize supports
@param mixed $input
@param int $flags see `sanitize()` for details
@param array $options see `check()` for details
@return mixed|false | entailment |
public static function checkAndSanitizeInput($field, array &$inputArray, $inputKeys, $flags = 0, array $options = null)
{
$value = self::getValFromMultiDimInput($inputArray,$inputKeys);
if($value === false)
return false;
else
return self::checkAndSanitize($field,$value,$flags,$options);
} | This function checks if the index of the inputArray exists and if the input is valid. The
function can be called as `checkAndSanitizeInput($fieldName,$_POST,['input',$fieldName],$flags,$options)`
and equals `checkAndSanitize($fieldName,$_POST['input'][$fieldName],$flags,$options)`, but checks first, if
the index exists.
@param string $field see `checkAndSanitize()` for valid values.
@param array $inputArray
@param string|int|mixed[] $inputKeys
@param int $flags see `checkAndSanitize()` for valid values.
@param array $options see `checkAndSanitize()` for valid values.
@return false|mixed | entailment |
public static function sanitize($field, $input, $flags = 0)
{
$field = strtolower($field);
switch($field) // fall-through's are on purpose
{
case 'orgid_id':
return self::sanitizeText(self::TEXT_LENGTH_VERY_SHORT, $input, true, $flags);
case 'ultmtcdrt':
case 'ultmtdebtr':
return self::sanitizeText(self::TEXT_LENGTH_SHORT, $input, true, $flags);
case 'orgnlcdtrschmeid_nm':
case 'initgpty':
case 'cdtr':
case 'dbtr':
return self::sanitizeText(self::TEXT_LENGTH_SHORT, $input, false, $flags);
case 'rmtinf':
return self::sanitizeText(self::TEXT_LENGTH_LONG, $input, true, $flags);
default:
return false;
}
} | Tries to sanitize the the input so it fits in the field.
@param string $field Valid fields are: 'ultmtcdrt', 'ultmtdebtr',
'orgnlcdtrschmeid_nm', 'initgpty', 'cdtr', 'dbtr', 'rmtinf'
@param mixed $input
@param int $flags Flags used in replaceSpecialChars()
@return mixed|false The sanitized input or false if the input is not sanitizeable or
invalid also after sanitizing. | entailment |
public static function containsAllKeys(array $arr, array $keys)
{
foreach($keys as $key)
{
if( !isset( $arr[$key] ) )
return false;
}
return true;
} | Checks if $arr misses one of the given $keys
@param array $arr
@param array $keys
@return bool false, if at least one key is missing, else true | entailment |
public static function containsNotAnyKey(array $arr, array $keys)
{
foreach ($keys as $key) {
if (isset($arr[$key]))
return false;
}
return true;
} | Checks if $arr not contains any key of $keys
@param array $arr
@param array $keys
@return bool true, if $arr contains not even on the the keys, else false | entailment |
private static function checkBoolean($input )
{
$bbi = filter_var($input,FILTER_VALIDATE_BOOLEAN,FILTER_NULL_ON_FAILURE);
if($bbi === true)
return 'true';
if($bbi === false)
return 'false';
return false;
} | Checks if $bbi is a valid batch booking indicator. Returns 'true' for "1", "true", "on"
and "yes", returns 'false' for "0", "false", "off", "no", and ""
@param mixed $input
@return string|false The batch booking indicator (in lower case only) or false if not
valid | entailment |
public static function sanitizeLength($input, $maxLen)
{
if(isset($input[$maxLen])) // take string as array of chars
return substr($input,0,$maxLen);
else
return $input;
} | Shortens the input string to the max length if it is to long.
@param string $input
@param int $maxLen
@return string sanitized string | entailment |
public static function replaceSpecialChars($str, $flags = 0)
{
if($flags === 0)
{
$specialCharsReplacement =& self::$specialCharsReplacement; // reference
$charExceptions = '';
}
else
{
$specialCharsReplacement = self::$specialCharsReplacement; // copy
$charExceptions = '';
if( $flags & self::FLAG_ALT_REPLACEMENT_GERMAN)
self::changeArrayValuesByAssocArray($specialCharsReplacement, ['Ä' => 'Ae', 'ä' => 'ae', 'Ö' => 'Oe', 'ö' => 'oe', 'Ü' => 'Ue', 'ü' => 'ue', 'ß' => 'ss']);
if($flags & self::FLAG_NO_REPLACEMENT_GERMAN)
{
self::changeArrayValuesToKeys($specialCharsReplacement, ['Ä', 'ä', 'Ö', 'ö', 'Ü', 'ü', 'ß']);
$charExceptions .= 'ÄäÖöÜüß';
}
}
// remove characters
$str = str_replace(['"', '&', '<', '>'], '', $str);
// replace all kinds of whitespaces by a space
$str = preg_replace('#\s+#u',' ',$str);
// special replacement for some characters (incl. greek and cyrillic)
$str = strtr($str,$specialCharsReplacement);
// replace everything not allowed in sepa files by . (a dot)
$str = preg_replace('#[^a-zA-Z0-9/\-?:().,\'+ ' . $charExceptions . ']#u','.',$str);
// remove leading and closing whitespaces
return trim($str);
} | Replaces all special chars like á, ä, â, à, å, ã, æ, Ç, Ø, Š, ", ’ and & by a latin character.
All special characters that cannot be replaced by a latin char (such like quotes) will
be removed as long as they cannot be converted. See http://www.europeanpaymentscouncil.eu/index.cfm/knowledge-bank/epc-documents/sepa-requirements-for-an-extended-character-set-unicode-subset-best-practices/
for more information about converting characters.
@param string $str
@param int $flags Use the SepaUtilities::FLAG_ALT_REPLACEMENT_* and SepaUtilities::FLAG_NO_REPLACEMENT_*
constants. FLAG_ALT_REPLACEMENT_* will ignore the best practice replacement
and use a more common one. You can use more than one flag by using
the | (bitwise or) operator. FLAG_NO_REPLACEMENT_* tells the function
not to replace the character group.
@return string | entailment |
private static function checkAmountFormat( $amount )
{
// $amount is a string -> check for '1,234.56'
$result = filter_var($amount, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
if($result === false)
$result = filter_var(strtr($amount, [',' => '.', '.' => ',']), FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
if($result === false || $result < 0.01 || $result > 999999999.99 || round($result,2) != $result)
return false;
return $result;
} | Checks if the amount fits the format: A float with only two decimals, not lower than 0.01,
not greater than 999,999,999.99.
@param mixed $amount float or string with or without thousand separator (use , or .). You
can use '.' or ',' as decimal point, but not one sign as thousand separator
and decimal point. So 1234.56; 1,234.56; 1.234,56; 1234,56 ar valid
inputs.
@return float|false | entailment |
private static function checkSeqType($seqTp)
{
$seqTp = strtoupper($seqTp);
if( in_array($seqTp, [self::SEQUENCE_TYPE_FIRST, self::SEQUENCE_TYPE_RECURRING,
self::SEQUENCE_TYPE_ONCE, self::SEQUENCE_TYPE_FINAL]) )
return $seqTp;
return false;
} | Checks if the sequence type is valid.
@param string $seqTp
@return string|false | entailment |
public static function version2string($version)
{
switch($version)
{ // fall-through's are on purpose
case self::SEPA_PAIN_001_001_03_GBIC:
case self::SEPA_PAIN_001_001_03: return 'pain.001.001.03';
case self::SEPA_PAIN_001_002_03: return 'pain.001.002.03';
case self::SEPA_PAIN_001_003_03: return 'pain.001.003.03';
case self::SEPA_PAIN_008_001_02_GBIC:
case self::SEPA_PAIN_008_001_02_AUSTRIAN_003:
case self::SEPA_PAIN_008_001_02: return 'pain.008.001.02';
case self::SEPA_PAIN_008_002_02: return 'pain.008.002.02';
case self::SEPA_PAIN_008_003_02: return 'pain.008.003.02';
default: return false;
}
} | Returns the SEPA file version as a string.
@param int $version Use the SEPA_PAIN_* constants.
@return string|false SEPA file version as a string or false if the version is invalid. | entailment |
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new FlowConfiguration();
$processor = new Processor();
$this->flowsConfig = $processor->processConfiguration($configuration, $configs);
} | Loads a specific configuration.
@param array $configs
@param ContainerBuilder $container | entailment |
public function process(ContainerBuilder $container)
{
$definition = $container->findDefinition(FlowManager::class);
foreach ($this->flowsConfig as $flowTube => $flowConfigData) {
$flowConfig = new FlowConfig($flowTube, $flowConfigData);
$flowDefinition = new Definition(Flow::class);
$flowDefinition->setAutowired(true);
$flowDefinition->setArgument('$flowConfig', $flowConfig);
try {
$producerDefinition = $container->findDefinition($flowConfig->getProducerServiceId());
$producerDefinition->setShared(false);
$producerInstanceDefinition = new Definition();
$producerInstanceDefinition
->setAutowired(true)
->setClass(ProducerInstance::class)
->setArgument('$flowConfig', $flowConfig)
->setArgument('$producer', new Reference($flowConfig->getProducerServiceId()))
;
$flowDefinition->setArgument('$producerInstance', $producerInstanceDefinition);
} catch (ServiceNotFoundException $e) {
throw new InvalidConfigurationException(
sprintf(
'Invalid producer for flow "%s", there is no service defined with ID "%s".',
$flowConfig->getDescription(),
$flowConfig->getProducerServiceId()
)
);
}
try {
$workerDefinition = $container->findDefinition($flowConfig->getWorkerServiceId());
$workerDefinition->setShared(false);
$workerInstancesDefinitions = [];
for ($instanceId = 1; $instanceId <= $flowConfig->getWorkerInstancesCount(); $instanceId++) {
$workerInstanceDefinition = new Definition();
$workerInstanceDefinition
->setAutowired(true)
->setClass(WorkerInstance::class)
->setArgument('$flowConfig', $flowConfig)
->setArgument('$instanceId', $instanceId)
->setArgument('$worker', new Reference($flowConfig->getWorkerServiceId()))
;
$workerInstancesDefinitions[] = $workerInstanceDefinition;
}
$flowDefinition->setArgument('$workerInstances', $workerInstancesDefinitions);
} catch (ServiceNotFoundException $e) {
throw new InvalidConfigurationException(
sprintf(
'Invalid workder for flow "%s", there is no service defined with ID "%s".',
$flowConfig->getDescription(),
$flowConfig->getWorkerServiceId()
)
);
}
$container->setDefinition($flowTube, $flowDefinition);
$definition->addMethodCall('addFlow', [new Reference($flowTube)]);
}
} | You can modify the container here before it is dumped to PHP code. | entailment |
public function getClassName()
{
$adapter = $this->getAdapter();
if ($adapter) {
return $adapter;
}
return ucfirst($this->dsn->scheme);
} | getClassName
Return the adapter if there is one, else return the scheme
@return string | entailment |
public function createBridge(IOInterface $io): NpmBridge
{
return new NpmBridge($io, $this->vendorFinder, $this->client);
} | Construct a new Composer NPM bridge plugin.
@param IOInterface $io The i/o interface to use. | entailment |
public function getEscapedString()
{
if ($this->escapedString === null) {
$this->escapedString = str_replace('-', ' ', $this->escape($this->getRawString()));
$this->escapedString = preg_replace(['/\s+([0-9])/','/\s+/'], ['$1', ' '], $this->escapedString);
}
return $this->escapedString;
} | Remove spaces before numbers in order to avoid search errors
Remove all dashes
@return string | entailment |
public static function escape ($string)
{
if (!is_numeric($string)) {
if (preg_match('/\W/', $string) == 1) {
// multiple words
$stringLength = strlen($string);
if ($string{0} == '"' && $string{$stringLength - 1} == '"') {
// phrase
$string = trim($string, '"');
$string = self::escapePhrase($string);
} else {
$string = self::escapeSpecialCharacters($string);
}
} else {
$string = self::escapeSpecialCharacters($string);
}
}
return $string;
} | Quote and escape search strings
@param string $string String to escape
@return string The escaped/quoted string | entailment |
public static function parse($url)
{
$scheme = substr($url, 0, strpos($url, ':'));
if (strpos($scheme, '+')) {
$scheme = substr($scheme, 0, strpos($scheme, '+'));
}
if (!$scheme) {
throw new \Exception(sprintf('The url \'%s\' could not be parsed', $url));
}
if (isset(static::$schemeMap[$scheme])) {
$className = static::$schemeMap[$scheme];
} else {
$className = static::currentNamespace() . '\\' . ucfirst($scheme) . 'Dsn';
if (!class_exists($className)) {
$className = static::currentClass();
}
}
return new $className($url);
} | parse a dsn string into a dsn instance
If a more specific dsn class is available an instance of that class is returned
@param string $url
@return mixed Dsn instance or false | entailment |
public static function map($scheme = null, $class = null)
{
if (is_array($scheme)) {
foreach ($scheme as $s => $class) {
static::map($s, $class);
}
return static::$schemeMap;
}
if ($scheme === null) {
return static::$schemeMap;
}
if ($class === null) {
return isset(static::$schemeMap[$scheme]) ? static::$schemeMap[$scheme] : null;
}
if ($class === false) {
unset($schemeMap[$scheme]);
return;
}
return static::$schemeMap[$scheme] = $class;
} | Read or change the scheme map
For example:
$true = Dsn::map('foo', '\My\Dsn\Class');
$classname = Dsn::map('foo');
$true = Dsn::map('foo', false); // Remove foo from the map
$fullMap = Dsn::map();
$false = Dsn::map('unknown');
$array = ['this' => 'That\Class', 'other' => 'Other\Class', ...];
$fullMap = Dsn::map($array);
@param mixed $scheme
@param string $class
@return mixed | entailment |
public function defaultPort($port = null)
{
if (!is_null($port)) {
$this->defaultPort = (int)$port;
if ($this->url['port'] === null) {
$this->url['port'] = $this->defaultPort;
}
}
return $this->defaultPort;
} | Get or set the default port
@param int $port
@return int | entailment |
public function parseUrl($string)
{
$this->url = [];
$url = parse_url($string);
if (!$url || !isset($url['scheme'])) {
throw new \Exception(sprintf('The url \'%s\' could not be parsed', $string));
}
$this->parseUrlArray($url);
} | parseUrl
Parse a url and merge with any extra get arguments defined
@param string $string
@return void | entailment |
protected function parseUrlArray($url)
{
if (strpos($url['scheme'], '+')) {
list($url['scheme'], $url['adapter']) = explode('+', $url['scheme']);
}
$defaultPort = $this->defaultPort();
if ($defaultPort && empty($url['port'])) {
$url['port'] = $defaultPort;
}
if (isset($url['query'])) {
$extra = [];
parse_str($url['query'], $extra);
unset($url['query']);
$url += $extra;
}
$url = array_merge($this->uriKeys, $url);
foreach (['host', 'user', 'pass'] as $key) {
if (!isset($url[$key])) {
continue;
}
$url[$key] = urldecode($url[$key]);
}
foreach ($url as $key => $val) {
$setter = 'set' . ucfirst($key);
$this->$setter($val);
}
} | Worker function for parseUrl
Take the passed array, and using getters update the instance
@param array $url
@return void | entailment |
public function toArray()
{
$url = $this->url;
$return = [];
foreach (array_keys($url) as $key) {
$getter = 'get' . ucfirst($key);
$val = $this->$getter();
if ($val !== null) {
$return[$key] = $val;
}
}
return $return;
} | toArray
Return this instance as an associative array using getter methods if they exist
@return array | entailment |
protected function toUrlArray($data)
{
$url = array_intersect_key($data, $this->uriKeys);
foreach (['host', 'user', 'pass'] as $key) {
if (!isset($url[$key])) {
continue;
}
$url[$key] = urlencode($url[$key]);
}
if ($url['adapter']) {
$return = $url['scheme'] . '+' . $url['adapter'] . '://';
} else {
$return = $url['scheme'] . '://';
}
if (!empty($url['user'])) {
$return .= $url['user'];
if (!empty($url['pass'])) {
$return .= ':' . $url['pass'];
}
$return .= '@';
}
$return .= $url['host'];
$defaultPort = $this->defaultPort();
if (!empty($url['port']) && $url['port'] != $defaultPort) {
$return .= ':' . $url['port'];
}
$return .= $url['path'];
$query = array_diff_key($data, $this->uriKeys);
if ($query) {
foreach ($query as $key => &$value) {
if (is_array($value)) {
$intermediate = [];
foreach ($value as $k => $v) {
$v = urlencode($v);
$intermediate[] = "{$key}[$k]=$v";
}
$value = implode($intermediate, '&');
continue;
}
$value = "$key=$value";
}
$return .= '?' . implode($query, '&');
}
return $return;
} | Worker function for toUrl - does not rely on instance state
@param array $data
@return string | entailment |
protected function readDictionary($dictionary)
{
$words = [];
$baseDictPath = $this->getBaseDictPath();
if (is_array($dictionary)) {
foreach ($dictionary as $file) {
if (file_exists($baseDictPath.$file.'.php')) {
$dict = include $baseDictPath.$file.'.php';
$words = array_merge($words, $dict);
} else {
// if the file isn't in the dict directory,
// it's probably a custom user library
$dict = include $file;
$words = array_merge($words, $dict);
}
}
// just a single string, not an array
} elseif (is_string($dictionary)) {
if (file_exists($baseDictPath.$dictionary.'.php')) {
$dict = include $baseDictPath.$dictionary.'.php';
$words = array_merge($words, $dict);
} else {
if (file_exists($dictionary)) {
$dict = include $dictionary;
$words = array_merge($words, $dict);
} // else nothing is merged
}
}
return $words;
} | [readDictionary description].
@param [type] $dictionary [description]
@return [type] [description] | entailment |
protected function _addFilter($facetName, $value)
{
if (isset($this->filters[$facetName])) {
$currentValue = $this->filters[$facetName];
if (!is_array($currentValue)) {
$currentValue = array($currentValue);
}
$currentValue[] = $value;
$value = $currentValue;
}
$this->filters[$facetName] = $value;
} | Add new filter without overwriting existing filters
@param string $facetName
@param string|int $value | entailment |
private function isValidAttributeFilterValue($value)
{
if (is_array($value)) {
foreach ($value as $subValue) {
if (!$this->isValidAttributeFilterValue($subValue)) {
return false;
}
}
return true;
}
return ctype_digit($value);
} | Value must be an option ID or an array of option IDs
@param mixed $value
@return bool | entailment |
public static function studlyCase($string) {
$string = Strings::capitalize(Strings::replace($string, ['/-/', '/_/'], ' '));
return Strings::replace($string, '/ /');
} | Converts the given string to `StudlyCase`
@param string $string
@return string | entailment |
public static function spinalCase($string) {
/** RegExp source http://stackoverflow.com/a/1993772 */
preg_match_all('/([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)/', $string, $matches);
$matches = $matches[0];
foreach ($matches as &$match) {
$match = ($match == Strings::upper($match)) ? Strings::lower($match) : Strings::firstLower($match);
}
return implode('-', $matches);
} | Converts the given string to `spinal-case`
@param string $string
@return string | entailment |
public function getTransport()
{
$adapter = $this->getAdapter();
if ($adapter) {
return $adapter;
}
return ucfirst($this->dsn->scheme);
} | getTransport
Return the adapter if there is one, else return the scheme
@return string | entailment |
public function appendService(ServiceBase $successor)
{
if ($this->successor !== null) {
$this->successor->appendService($successor);
} else {
$this->successor = $successor;
}
} | Append service to chain of responsibility
@param ServiceBase $successor | entailment |
protected function _constructBaseUrl($servlet, $params = array())
{
if (count($params))
{
//escape all parameters appropriately for inclusion in the query string
$escapedParams = array();
foreach ($params as $key => $value)
{
$escapedParams[] = urlencode($key) . '=' . urlencode($value);
}
$queryString = $this->_queryDelimiter . implode($this->_queryStringDelimiter, $escapedParams);
}
else
{
$queryString = '';
}
if (!$this->_basePath) {
throw new Exception('Please provide a base path');
}
$protocol = 'http://';
if ($this->_useHttps) {
$protocol = 'https://';
}
return $protocol . $this->_host . ':' . $this->_port . $this->_basePath . $servlet . $queryString;
} | Return a valid http URL given this server's host, port and path and a provided servlet name
Exclude core name from
@param string $servlet
@param array $params
@return string
@throws Exception | entailment |
public function swapCores($core, $otherCore, $method = self::METHOD_GET)
{
if (!$this->_coresUrl) {
throw new Exception('Please call "setBasePath" before.');
}
$params = array();
// construct our full parameters
$params['action'] = 'SWAP';
$params['core'] = $core;
$params['other'] = $otherCore;
$queryString = $this->_generateQueryString($params);
if ($method == self::METHOD_GET)
{
return $this->_sendRawGet($this->_coresUrl . $this->_queryDelimiter . $queryString);
}
else if ($method == self::METHOD_POST)
{
return $this->_sendRawPost($this->_coresUrl, $queryString, FALSE, 'application/x-www-form-urlencoded; charset=UTF-8');
}
else
{
throw new Apache_Solr_InvalidArgumentException("Unsupported method '$method', please use the Service::METHOD_* constants");
}
} | core swap interface
@param string $core
@param string $otherCore
@param string $method The HTTP method (Service::METHOD_GET or Service::METHOD::POST)
@return Apache_Solr_Response
@throws Apache_Solr_HttpTransportException If an error occurs during the service call
@throws Apache_Solr_InvalidArgumentException If an invalid HTTP method is used
@throws Exception | entailment |
public function info($method = self::METHOD_GET)
{
if (!$this->_infoUrl) {
throw new Exception('Please call "setBasePath" before.');
}
$params = array();
// construct our full parameters
$params['wt'] = 'json';
$queryString = $this->_generateQueryString($params);
if ($method == self::METHOD_GET)
{
return $this->_sendRawGet($this->_infoUrl . $this->_queryDelimiter . $queryString);
}
else if ($method == self::METHOD_POST)
{
return $this->_sendRawPost($this->_infoUrl, $queryString, FALSE, 'application/x-www-form-urlencoded; charset=UTF-8');
}
else
{
throw new Apache_Solr_InvalidArgumentException("Unsupported method '$method', please use the Service::METHOD_* constants");
}
} | admin info interface
@param string $method The HTTP method (Service::METHOD_GET or Service::METHOD::POST)
@return Apache_Solr_Response
@throws Apache_Solr_HttpTransportException If an error occurs during the service call
@throws Apache_Solr_InvalidArgumentException If an invalid HTTP method is used
@throws Exception | entailment |
public function exclude(array $names)
{
$filtered = clone $this;
foreach ($names as $name) {
unset($filtered[$name]);
}
return $filtered;
} | Returns new collection without the given field names
@param string[] $names
@return ApacheSolrFacetCollection | entailment |
public function match(IRequest $httpRequest) {
$url = $httpRequest->getUrl();
$basePath = Strings::replace($url->getBasePath(), '/\//', '\/');
$cleanPath = Strings::replace($url->getPath(), "/^{$basePath}/");
$path = Strings::replace($this->getPath(), '/\//', '\/');
$pathRexExp = empty($path) ? "/^.+$/" : "/^{$path}\/.*$/";
if (!Strings::match($cleanPath, $pathRexExp)) {
return NULL;
}
$cleanPath = Strings::replace($cleanPath, '/^' . $path . '\//');
$params = [];
$path = $cleanPath;
$params['action'] = $this->detectAction($httpRequest);
$frags = explode('/', $path);
if ($this->useURLModuleVersioning) {
$version = array_shift($frags);
if (!Strings::match($version, $this->versionRegex)) {
array_unshift($frags, $version);
$version = NULL;
}
}
// Resource ID.
if (count($frags) % 2 === 0) {
$params['id'] = array_pop($frags);
} elseif ($params['action'] == 'read') {
$params['action'] = 'readAll';
}
$presenterName = Inflector::studlyCase(array_pop($frags));
// Allow to use URLs like domain.tld/presenter.format.
$formats = join('|', array_keys($this->formats));
if (Strings::match($presenterName, "/.+\.({$formats})$/")) {
list($presenterName) = explode('.', $presenterName);
}
// Associations.
$assoc = [];
if (count($frags) > 0 && count($frags) % 2 === 0) {
foreach ($frags as $k => $f) {
if ($k % 2 !== 0) continue;
$assoc[$f] = $frags[$k + 1];
}
}
$params['format'] = $this->detectFormat($httpRequest);
$params['associations'] = $assoc;
$params['data'] = $this->readInput();
$params['query'] = $httpRequest->getQuery();
if ($this->useURLModuleVersioning) {
$suffix = $presenterName;
$presenterName = empty($this->module) ? "" : $this->module . ':';
$presenterName .= array_key_exists($version, $this->versionToModuleMapping)
? $this->versionToModuleMapping[$version] . ":" . $suffix
: $this->versionToModuleMapping[NULL] . ":" . $suffix;
} else {
$presenterName = empty($this->module) ? $presenterName : $this->module . ':' . $presenterName;
}
return new Request(
$presenterName,
$httpRequest->getMethod(),
$params,
[],
$httpRequest->getFiles()
);
} | Maps HTTP request to a Request object.
@param \Nette\Http\IRequest $httpRequest
@return \Nette\Application\Request|NULL | entailment |
public function constructUrl(Request $appRequest, Url $refUrl) {
// Module prefix not match.
if($this->module && !Strings::startsWith($appRequest->getPresenterName(), $this->module)) {
return NULL;
}
$parameters = $appRequest->getParameters();
$url = $refUrl->getBaseUrl();
$urlStack = [];
// Module prefix.
$moduleFrags = explode(":", $appRequest->getPresenterName());
$moduleFrags = array_map('\AdamStipak\Support\Inflector::spinalCase', $moduleFrags);
$resourceName = array_pop($moduleFrags);
$urlStack += $moduleFrags;
// Associations.
if (isset($parameters['associations']) && Validators::is($parameters['associations'], 'array')) {
$associations = $parameters['associations'];
unset($parameters['associations']);
foreach ($associations as $key => $value) {
$urlStack[] = $key;
$urlStack[] = $value;
}
}
// Resource.
$urlStack[] = $resourceName;
// Id.
if (isset($parameters['id']) && Validators::is($parameters['id'], 'scalar')) {
$urlStack[] = $parameters['id'];
unset($parameters['id']);
}
$url = $url . implode('/', $urlStack);
$sep = ini_get('arg_separator.input');
if(isset($parameters['query'])) {
$query = http_build_query($parameters['query'], '', $sep ? $sep[0] : '&');
if ($query != '') {
$url .= '?' . $query;
}
}
return $url;
} | Constructs absolute URL from Request object.
@param \Nette\Application\Request $appRequest
@param \Nette\Http\Url $refUrl
@throws \Nette\InvalidStateException
@return string|NULL | entailment |
public function hasLowerPriority(Operator $o)
{
$hasLowerPriority = ((Operator::O_LEFT_ASSOCIATIVE == $o->getAssociativity()
&& $this->getPriority() == $o->getPriority())
|| $this->getPriority() < $o->getPriority());
return $hasLowerPriority;
} | Return true if this operator has lower priority of operator $o.
@param \Math\Operator $o
@return boolean | entailment |
public function install(Composer $composer, bool $isDevMode = true)
{
$this->io->write(
'<info>Installing NPM dependencies for root project</info>'
);
$package = $composer->getPackage();
if ($this->isDependantPackage($package, $isDevMode)) {
$isNpmAvailable = $this->client->isAvailable();
$extra = $package->getExtra();
if (!$isNpmAvailable && $this->isPackageOptional($extra)) {
$this->io->write('Skipping as NPM is unavailable');
} else {
$this->client
->install(null, $isDevMode, $this->packageTimeout($extra));
}
} else {
$this->io->write('Nothing to install');
}
$this->installForVendors($composer);
} | Install NPM dependencies for a Composer project and its dependencies.
@param Composer $composer The main Composer object.
@param bool $isDevMode True if dev mode is enabled.
@throws NpmNotFoundException If the npm executable cannot be located.
@throws NpmCommandFailedException If the operation fails. | entailment |
public function update(Composer $composer)
{
$this->io->write(
'<info>Updating NPM dependencies for root project</info>'
);
$package = $composer->getPackage();
if ($this->isDependantPackage($package, true)) {
$timeout = $this->packageTimeout($package->getExtra());
$this->client->update(null, $timeout);
$this->client->install(null, true, $timeout);
} else {
$this->io->write('Nothing to update');
}
$this->installForVendors($composer);
} | Update NPM dependencies for a Composer project and its dependencies.
@param Composer $composer The main Composer object.
@throws NpmNotFoundException If the npm executable cannot be located.
@throws NpmCommandFailedException If the operation fails. | entailment |
public function isDependantPackage(
PackageInterface $package,
bool $includeDevDependencies = false
): bool {
foreach ($package->getRequires() as $link) {
if ('eloquent/composer-npm-bridge' === $link->getTarget()) {
return true;
}
}
if ($includeDevDependencies) {
foreach ($package->getDevRequires() as $link) {
if ('eloquent/composer-npm-bridge' === $link->getTarget()) {
return true;
}
}
}
return false;
} | Returns true if the supplied package requires the Composer NPM bridge.
@param PackageInterface $package The package to inspect.
@param bool $includeDevDependencies True if the dev dependencies should also be inspected.
@return bool True if the package requires the bridge. | entailment |
public function setPath($path)
{
if (!$this->databaseIsPath) {
$path = ltrim($path, '/');
}
$this->setDatabase($path);
} | setPath
@param string $path
@return void | entailment |
public function parseUrl($string)
{
$engine = null;
if ($this->databaseIsPath) {
$engine = substr($string, 0, strpos($string, ':'));
$string = 'file' . substr($string, strlen($engine));
}
parent::parseUrl($string);
if ($engine !== null) {
$this->setEngine($engine);
}
} | parseUrl
Handle the parent method only dealing with paths for the file scheme
@param string $string
@return array | entailment |
public function toUrl()
{
$url = $this->url;
unset($url['engine'], $url['database']);
$url['scheme'] = $this->getScheme();
$url['path'] = $this->getPath();
return $this->toUrlArray($url);
} | return this instance as a dsn url string
@return string | entailment |
public static function containsCaseless($haystack, $needles)
{
foreach ((array) $needles as $needle) {
$needle = preg_quote($needle);
if ($needle != '' && preg_match("/$needle/iu", $haystack)) {
return true;
}
}
return false;
} | Taken from Illuminate\Support\Str
Determine if a given string contains a given word with case insensitive match.
@param string $haystack
@param string|array $needles
@return bool | entailment |
public static function removeAccent($string)
{
$replace = [
'ъ'=> '-', 'Ь'=>'-', 'Ъ'=>'-', 'ь'=>'-',
'Ă'=> 'A', 'Ą'=>'A', 'À'=>'A', 'Ã'=>'A', 'Á'=>'A', 'Æ'=>'A', 'Â'=>'A', 'Å'=>'A', 'Ä'=>'Ae',
'Þ'=> 'B',
'Ć'=> 'C', 'ץ'=>'C', 'Ç'=>'C',
'È'=> 'E', 'Ę'=>'E', 'É'=>'E', 'Ë'=>'E', 'Ê'=>'E',
'Ğ'=> 'G',
'İ'=> 'I', 'Ï'=>'I', 'Î'=>'I', 'Í'=>'I', 'Ì'=>'I',
'Ł'=> 'L',
'Ñ'=> 'N', 'Ń'=>'N',
'Ø'=> 'O', 'Ó'=>'O', 'Ò'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'Oe',
'Ş'=> 'S', 'Ś'=>'S', 'Ș'=>'S', 'Š'=>'S',
'Ț'=> 'T',
'Ù'=> 'U', 'Û'=>'U', 'Ú'=>'U', 'Ü'=>'Ue',
'Ý'=> 'Y',
'Ź'=> 'Z', 'Ž'=>'Z', 'Ż'=>'Z',
'â'=> 'a', 'ǎ'=>'a', 'ą'=>'a', 'á'=>'a', 'ă'=>'a', 'ã'=>'a', 'Ǎ'=>'a', 'а'=>'a', 'А'=>'a', 'å'=>'a', 'à'=>'a', 'א'=>'a', 'Ǻ'=>'a', 'Ā'=>'a', 'ǻ'=>'a', 'ā'=>'a', 'ä'=>'ae', 'æ'=>'ae', 'Ǽ'=>'ae', 'ǽ'=>'ae',
'б'=> 'b', 'ב'=>'b', 'Б'=>'b', 'þ'=>'b',
'ĉ'=> 'c', 'Ĉ'=>'c', 'Ċ'=>'c', 'ć'=>'c', 'ç'=>'c', 'ц'=>'c', 'צ'=>'c', 'ċ'=>'c', 'Ц'=>'c', 'Č'=>'c', 'č'=>'c', 'Ч'=>'ch', 'ч'=>'ch',
'ד'=> 'd', 'ď'=>'d', 'Đ'=>'d', 'Ď'=>'d', 'đ'=>'d', 'д'=>'d', 'Д'=>'D', 'ð'=>'d',
'є'=> 'e', 'ע'=>'e', 'е'=>'e', 'Е'=>'e', 'Ə'=>'e', 'ę'=>'e', 'ĕ'=>'e', 'ē'=>'e', 'Ē'=>'e', 'Ė'=>'e', 'ė'=>'e', 'ě'=>'e', 'Ě'=>'e', 'Є'=>'e', 'Ĕ'=>'e', 'ê'=>'e', 'ə'=>'e', 'è'=>'e', 'ë'=>'e', 'é'=>'e',
'ф'=> 'f', 'ƒ'=>'f', 'Ф'=>'f',
'ġ'=> 'g', 'Ģ'=>'g', 'Ġ'=>'g', 'Ĝ'=>'g', 'Г'=>'g', 'г'=>'g', 'ĝ'=>'g', 'ğ'=>'g', 'ג'=>'g', 'Ґ'=>'g', 'ґ'=>'g', 'ģ'=>'g',
'ח'=> 'h', 'ħ'=>'h', 'Х'=>'h', 'Ħ'=>'h', 'Ĥ'=>'h', 'ĥ'=>'h', 'х'=>'h', 'ה'=>'h',
'î'=> 'i', 'ï'=>'i', 'í'=>'i', 'ì'=>'i', 'į'=>'i', 'ĭ'=>'i', 'ı'=>'i', 'Ĭ'=>'i', 'И'=>'i', 'ĩ'=>'i', 'ǐ'=>'i', 'Ĩ'=>'i', 'Ǐ'=>'i', 'и'=>'i', 'Į'=>'i', 'י'=>'i', 'Ї'=>'i', 'Ī'=>'i', 'І'=>'i', 'ї'=>'i', 'і'=>'i', 'ī'=>'i', 'ij'=>'ij', 'IJ'=>'ij',
'й'=> 'j', 'Й'=>'j', 'Ĵ'=>'j', 'ĵ'=>'j', 'я'=>'ja', 'Я'=>'ja', 'Э'=>'je', 'э'=>'je', 'ё'=>'jo', 'Ё'=>'jo', 'ю'=>'ju', 'Ю'=>'ju',
'ĸ'=> 'k', 'כ'=>'k', 'Ķ'=>'k', 'К'=>'k', 'к'=>'k', 'ķ'=>'k', 'ך'=>'k',
'Ŀ'=> 'l', 'ŀ'=>'l', 'Л'=>'l', 'ł'=>'l', 'ļ'=>'l', 'ĺ'=>'l', 'Ĺ'=>'l', 'Ļ'=>'l', 'л'=>'l', 'Ľ'=>'l', 'ľ'=>'l', 'ל'=>'l',
'מ'=> 'm', 'М'=>'m', 'ם'=>'m', 'м'=>'m',
// 'ñ'=>'n', // for spanish cono != coño
'н'=> 'n', 'Ņ'=>'n', 'ן'=>'n', 'ŋ'=>'n', 'נ'=>'n', 'Н'=>'n', 'ń'=>'n',
'Ŋ'=> 'n', 'ņ'=>'n', 'ʼn'=>'n', 'Ň'=>'n', 'ň'=>'n',
'о'=> 'o', 'О'=>'o', 'ő'=>'o', 'õ'=>'o', 'ô'=>'o', 'Ő'=>'o', 'ŏ'=>'o', 'Ŏ'=>'o', 'Ō'=>'o', 'ō'=>'o', 'ø'=>'o', 'ǿ'=>'o', 'ǒ'=>'o', 'ò'=>'o', 'Ǿ'=>'o', 'Ǒ'=>'o', 'ơ'=>'o', 'ó'=>'o', 'Ơ'=>'o', 'œ'=>'oe', 'Œ'=>'oe', 'ö'=>'oe',
'פ'=> 'p', 'ף'=>'p', 'п'=>'p', 'П'=>'p',
'ק'=> 'q',
'ŕ'=> 'r', 'ř'=>'r', 'Ř'=>'r', 'ŗ'=>'r', 'Ŗ'=>'r', 'ר'=>'r', 'Ŕ'=>'r', 'Р'=>'r', 'р'=>'r',
'ș'=> 's', 'с'=>'s', 'Ŝ'=>'s', 'š'=>'s', 'ś'=>'s', 'ס'=>'s', 'ş'=>'s', 'С'=>'s', 'ŝ'=>'s', 'Щ'=>'sch', 'щ'=>'sch', 'ш'=>'sh', 'Ш'=>'sh', 'ß'=>'ss',
'т'=> 't', 'ט'=>'t', 'ŧ'=>'t', 'ת'=>'t', 'ť'=>'t', 'ţ'=>'t', 'Ţ'=>'t', 'Т'=>'t', 'ț'=>'t', 'Ŧ'=>'t', 'Ť'=>'t', '™'=>'tm',
'ū'=> 'u', 'у'=>'u', 'Ũ'=>'u', 'ũ'=>'u', 'Ư'=>'u', 'ư'=>'u', 'Ū'=>'u', 'Ǔ'=>'u', 'ų'=>'u', 'Ų'=>'u', 'ŭ'=>'u', 'Ŭ'=>'u', 'Ů'=>'u', 'ů'=>'u', 'ű'=>'u', 'Ű'=>'u', 'Ǖ'=>'u', 'ǔ'=>'u', 'Ǜ'=>'u', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'У'=>'u', 'ǚ'=>'u', 'ǜ'=>'u', 'Ǚ'=>'u', 'Ǘ'=>'u', 'ǖ'=>'u', 'ǘ'=>'u', 'ü'=>'ue',
'в'=> 'v', 'ו'=>'v', 'В'=>'v',
'ש'=> 'w', 'ŵ'=>'w', 'Ŵ'=>'w',
'ы'=> 'y', 'ŷ'=>'y', 'ý'=>'y', 'ÿ'=>'y', 'Ÿ'=>'y', 'Ŷ'=>'y',
'Ы'=> 'y', 'ž'=>'z', 'З'=>'z', 'з'=>'z', 'ź'=>'z', 'ז'=>'z', 'ż'=>'z', 'ſ'=>'z', 'Ж'=>'zh', 'ж'=>'zh', 'ά' => 'α', 'έ' => 'ε', 'ή' => 'η', 'ί' => 'ι', 'ό' => 'ο', 'ύ' => 'υ', 'ώ' => 'ω',
];
return strtr($string, $replace);
} | Remove accents or special characters from a string.
@param string $string
@return string | entailment |
public function getServerInfo()
{
return sprintf('%s:%s%s%s', $this->host, $this->port, $this->path, $this->core);
} | Return unique resource identifier for solr core
@return string | entailment |
public function __isset($key)
{
if (!$this->_isParsed)
{
$this->_parseData();
$this->_isParsed = true;
}
return isset($this->_parsedData->$key);
} | Magic function for isset function on parsed data
@param string $key
@return boolean | entailment |
protected function _parseData()
{
//An alternative would be to use Zend_Json::decode(...)
$data = json_decode($this->_response->getBody());
// check that we receive a valid JSON response - we should never receive a null
if ($data === null)
{
throw new Apache_Solr_ParserException('Solr response does not appear to be valid JSON, please examine the raw response with getRawResponse() method');
}
//if we're configured to collapse single valued arrays or to convert them to Apache_Solr_Document objects
//and we have response documents, then try to collapse the values and / or convert them now
if (($this->_createDocuments || $this->_collapseSingleValueArrays) && isset($data->response) && is_array($data->response->docs))
{
$documents = array();
foreach ($data->response->docs as $originalDocument)
{
if ($this->_createDocuments)
{
$document = new Apache_Solr_Document();
}
else
{
$document = $originalDocument;
}
foreach ($originalDocument as $key => $value)
{
//If a result is an array with only a single
//value then its nice to be able to access
//it as if it were always a single value
if ($this->_collapseSingleValueArrays && is_array($value) && count($value) <= 1)
{
$value = array_shift($value);
}
$document->$key = $value;
}
$documents[] = $document;
}
$data->response->docs = $documents;
}
$this->_parsedData = $data;
} | Parse the raw response into the parsed_data array for access
@throws Apache_Solr_ParserException If the data could not be parsed | entailment |
public static function build($array, Closure $callback)
{
$results = array();
foreach ($array as $key => $value)
{
list($innerKey, $innerValue) = call_user_func($callback, $key, $value);
$results[$innerKey] = $innerValue;
}
return $results;
} | Build a new array using a callback.
@param array $array
@param \Closure $callback
@return array | entailment |
public function tokenize($code)
{
$code = trim((string) $code);
if (empty($code)) {
throw new \InvalidArgumentException('Cannot tokenize empty string.');
}
$this->code = $code;
$this->tokens = array();
$tokenArray = explode(' ', $this->code);
if (!is_array($tokenArray) || empty($tokenArray)) {
throw new \InvalidArgumentException(
sprintf('Cannot tokenize string: %s, please use " "(empty space for delimeter betwwen tokens)', $this->code)
);
}
foreach ($tokenArray as $t) {
if (array_key_exists($t, static::$operatorsMap)) {
$token = new Operator(
$t,
static::$operatorsMap[$t]['priority'],
static::$operatorsMap[$t]['associativity']
);
} elseif (is_numeric($t)) {
$token = new Token((float) $t, Token::T_OPERAND);
}elseif('(' === $t) {
$token = new Token($t, Token::T_LEFT_BRACKET);
}elseif(')' === $t) {
$token = new Token($t, Token::T_RIGHT_BRACKET);
}elseif('' === $t) {
continue;
}else {
throw new \InvalidArgumentException(sprintf('Syntax error: unknown token "%s"', $t));
}
$this->tokens[] = $token;
}
return $this->tokens;
} | Tokenize matematical expression.
@param type $code
@return array Collection of Token instances
@throws \InvalidArgumentException | entailment |
public function getDatasource()
{
$adapter = $this->getAdapter();
if ($adapter) {
return $adapter;
}
$engine = $this->dsn->engine;
return 'Database/' . ucfirst($engine);
} | getDatasource
Get the engine to use for this dsn. Defaults to `Database/Enginename`
@return string | entailment |
public function flush()
{
if (!empty($this->documents)) {
$this->resource->addDocuments($this->storeId, $this->documents);
$this->clearDocuments();
}
} | Commit previously added documents to Solr and clear queue
@return void | entailment |
public static function getDefaultStatusMessage($statusCode)
{
$statusCode = (int) $statusCode;
if (isset(self::$_defaultStatusMessages[$statusCode]))
{
return self::$_defaultStatusMessages[$statusCode];
}
return "Unknown Status";
} | Get the HTTP status message based on status code
@return string | entailment |
public function publish(Message $message)
{
// Check if required message parameters are set
if (!$message->getShortMessage() || !$message->getHost()) {
throw new \UnexpectedValueException(
'Missing required data parameter: "version", "short_message" and "host" are required.'
);
}
// Set Graylog protocol version
$message->setVersion(self::GRAYLOG2_PROTOCOL_VERSION);
// Encode the message as json string and compress it using gzip
$preparedMessage = $this->getPreparedMessage($message);
// Open a udp connection to graylog server
$socket = $this->getSocketConnection();
// Several udp writes are required to publish the message
if ($this->isMessageSizeGreaterChunkSize($preparedMessage)) {
// A unique id which consists of the microtime and a random value
$messageId = $this->getMessageId();
// Split the message into chunks
$messageChunks = $this->getMessageChunks($preparedMessage);
$messageChunksCount = count($messageChunks);
// Send chunks to graylog server
foreach (array_values($messageChunks) as $messageChunkIndex => $messageChunk) {
$bytesWritten = $this->writeMessageChunkToSocket(
$socket,
$messageId,
$messageChunk,
$messageChunkIndex,
$messageChunksCount
);
if (false === $bytesWritten) {
// Abort due to write error
return false;
}
}
} else {
// A single write is enough to get the message published
if (false === $this->writeMessageToSocket($socket, $preparedMessage)) {
// Abort due to write error
return false;
}
}
// This increases stability a lot if messages are sent in a loop
// A value of 20 means 0.02 ms
usleep(20);
// Message successful sent
return true;
} | Publishes a Message, returns false if an error occured during write
@throws \UnexpectedValueException
@param Message $message
@return boolean | entailment |
protected function _constructUrl($servlet, $params = array())
{
if (count($params))
{
//escape all parameters appropriately for inclusion in the query string
$escapedParams = array();
foreach ($params as $key => $value)
{
$escapedParams[] = urlencode($key) . '=' . urlencode($value);
}
$queryString = $this->_queryDelimiter . implode($this->_queryStringDelimiter, $escapedParams);
}
else
{
$queryString = '';
}
return 'http://' . $this->_host . ':' . $this->_port . $this->_path . $servlet . $queryString;
} | Return a valid http URL given this server's host, port and path and a provided servlet name
@param string $servlet
@return string | entailment |
protected function _initUrls()
{
//Initialize our full servlet URLs now that we have server information
$this->_extractUrl = $this->_constructUrl(self::EXTRACT_SERVLET);
$this->_pingUrl = $this->_constructUrl(self::PING_SERVLET);
$this->_searchUrl = $this->_constructUrl(self::SEARCH_SERVLET);
$this->_systemUrl = $this->_constructUrl(self::SYSTEM_SERVLET, array('wt' => self::SOLR_WRITER));
$this->_threadsUrl = $this->_constructUrl(self::THREADS_SERVLET, array('wt' => self::SOLR_WRITER ));
$this->_updateUrl = $this->_constructUrl(self::UPDATE_SERVLET, array('wt' => self::SOLR_WRITER ));
$this->_urlsInited = true;
} | Construct the Full URLs for the three servlets we reference | entailment |
protected function _sendRawGet($url, $timeout = FALSE)
{
$httpTransport = $this->getHttpTransport();
$httpResponse = $httpTransport->performGetRequest($url, $timeout);
$solrResponse = new Apache_Solr_Response($httpResponse, $this->_createDocuments, $this->_collapseSingleValueArrays);
if ($solrResponse->getHttpStatus() != 200)
{
throw new Apache_Solr_HttpTransportException($solrResponse);
}
return $solrResponse;
} | Central method for making a get operation against this Solr Server
@param string $url
@param float $timeout Read timeout in seconds
@return Apache_Solr_Response
@throws Apache_Solr_HttpTransportException If a non 200 response status is returned | entailment |
protected function _sendRawPost($url, $rawPost, $timeout = FALSE, $contentType = 'text/xml; charset=UTF-8')
{
$httpTransport = $this->getHttpTransport();
$httpResponse = $httpTransport->performPostRequest($url, $rawPost, $contentType, $timeout);
$solrResponse = new Apache_Solr_Response($httpResponse, $this->_createDocuments, $this->_collapseSingleValueArrays);
if ($solrResponse->getHttpStatus() != 200 && $solrResponse->getHttpStatus() != 0)
{
throw new Apache_Solr_HttpTransportException($solrResponse);
}
return $solrResponse;
} | Central method for making a post operation against this Solr Server
@param string $url
@param string $rawPost
@param float $timeout Read timeout in seconds
@param string $contentType
@return Apache_Solr_Response
@throws Apache_Solr_HttpTransportException If a non 200 response status is returned | entailment |
public function setHost($host)
{
//Use the provided host or use the default
if (empty($host))
{
throw new Apache_Solr_InvalidArgumentException('Host parameter is empty');
}
else
{
$this->_host = $host;
}
if ($this->_urlsInited)
{
$this->_initUrls();
}
} | Set the host used. If empty will fallback to constants
@param string $host
@throws Apache_Solr_InvalidArgumentException If the host parameter is empty | entailment |
public function setPort($port)
{
//Use the provided port or use the default
$port = (int) $port;
if ($port <= 0)
{
throw new Apache_Solr_InvalidArgumentException('Port is not a valid port number');
}
else
{
$this->_port = $port;
}
if ($this->_urlsInited)
{
$this->_initUrls();
}
} | Set the port used. If empty will fallback to constants
@param integer $port
@throws Apache_Solr_InvalidArgumentException If the port parameter is empty | entailment |
public function setPath($path)
{
$path = trim($path, '/');
if (strlen($path) > 0)
{
$this->_path = '/' . $path . '/';
}
else
{
$this->_path = '/';
}
if ($this->_urlsInited)
{
$this->_initUrls();
}
} | Set the path used. If empty will fallback to constants
@param string $path | entailment |
public function setNamedListTreatment($namedListTreatment)
{
switch ((string) $namedListTreatment)
{
case Apache_Solr_Service::NAMED_LIST_FLAT:
$this->_namedListTreatment = Apache_Solr_Service::NAMED_LIST_FLAT;
break;
case Apache_Solr_Service::NAMED_LIST_MAP:
$this->_namedListTreatment = Apache_Solr_Service::NAMED_LIST_MAP;
break;
default:
throw new Apache_Solr_InvalidArgumentException('Not a valid named list treatement option');
}
} | Set how NamedLists should be formatted in the response data. This mainly effects
the facet counts format.
@param string $namedListTreatment
@throws Apache_Solr_InvalidArgumentException If invalid option is set | entailment |
public function ping($timeout = 2)
{
$start = microtime(true);
$httpTransport = $this->getHttpTransport();
$httpResponse = $httpTransport->performHeadRequest($this->_pingUrl, $timeout);
$solrResponse = new Apache_Solr_Response($httpResponse, $this->_createDocuments, $this->_collapseSingleValueArrays);
if ($solrResponse->getHttpStatus() == 200)
{
return microtime(true) - $start;
}
else
{
return false;
}
} | Call the /admin/ping servlet, can be used to quickly tell if a connection to the
server is able to be made.
@param float $timeout maximum time to wait for ping in seconds, -1 for unlimited (default is 2)
@return float Actual time taken to ping the server, FALSE if timeout or HTTP error status occurs | entailment |
public function addDocument(Apache_Solr_Document $document, $allowDups = false, $overwritePending = true, $overwriteCommitted = true, $commitWithin = 0)
{
$documentXmlFragment = $this->_documentToXmlFragment($document);
return $this->addRawDocuments(
$documentXmlFragment,
$allowDups,
$overwritePending,
$overwriteCommitted,
$commitWithin
);
} | Add a Solr Document to the index
@param Apache_Solr_Document $document
@param boolean $allowDups
@param boolean $overwritePending
@param boolean $overwriteCommitted
@param integer $commitWithin The number of milliseconds that a document must be committed within, see @{link http://wiki.apache.org/solr/UpdateXmlMessages#The_Update_Schema} for details. If left empty this property will not be set in the request.
@return Apache_Solr_Response
@throws Apache_Solr_HttpTransportException If an error occurs during the service call | entailment |
public function addDocuments($documents, $allowDups = false, $overwritePending = true, $overwriteCommitted = true, $commitWithin = 0)
{
$documentsXmlFragment = '';
foreach ($documents as $document)
{
if ($document instanceof Apache_Solr_Document)
{
$documentsXmlFragment .= $this->_documentToXmlFragment($document);
}
}
return $this->addRawDocuments(
$documentsXmlFragment,
$allowDups,
$overwritePending,
$overwriteCommitted,
$commitWithin
);
} | Add an array of Solr Documents to the index all at once
@param array $documents Should be an array of Apache_Solr_Document instances
@param boolean $allowDups
@param boolean $overwritePending
@param boolean $overwriteCommitted
@param integer $commitWithin The number of milliseconds that a document must be committed within, see @{link http://wiki.apache.org/solr/UpdateXmlMessages#The_Update_Schema} for details. If left empty this property will not be set in the request.
@return Apache_Solr_Response
@throws Apache_Solr_HttpTransportException If an error occurs during the service call | entailment |
protected function _documentToXmlFragment(Apache_Solr_Document $document)
{
$xml = '<doc';
if ($document->getBoost() !== false)
{
$xml .= ' boost="' . $document->getBoost() . '"';
}
$xml .= '>';
foreach ($document as $key => $value)
{
$fieldBoost = $document->getFieldBoost($key);
$key = htmlspecialchars($key, ENT_QUOTES, 'UTF-8');
if (is_array($value))
{
foreach ($value as $multivalue)
{
$xml .= '<field name="' . $key . '"';
if ($fieldBoost !== false)
{
$xml .= ' boost="' . $fieldBoost . '"';
// only set the boost for the first field in the set
$fieldBoost = false;
}
$multivalue = htmlspecialchars($multivalue, ENT_NOQUOTES, 'UTF-8');
$xml .= '>' . $multivalue . '</field>';
}
}
else
{
$xml .= '<field name="' . $key . '"';
if ($fieldBoost !== false)
{
$xml .= ' boost="' . $fieldBoost . '"';
}
$value = htmlspecialchars($value, ENT_NOQUOTES, 'UTF-8');
$xml .= '>' . $value . '</field>';
}
}
$xml .= '</doc>';
// replace any control characters to avoid Solr XML parser exception
return $this->_stripCtrlChars($xml);
} | Create an XML fragment from a {@link Apache_Solr_Document} instance appropriate for use inside a Solr add call
@return string | entailment |
public function commit($expungeDeletes = false, $waitFlush = true, $waitSearcher = true, $timeout = 3600, $softCommit = false)
{
$rawPost = $this->getCompatibilityLayer()->createCommitXml(
$expungeDeletes,
$waitFlush,
$waitSearcher,
$timeout,
$softCommit
);
return $this->_sendRawPost($this->_updateUrl, $rawPost, $timeout);
} | Send a commit command. Will be synchronous unless both wait parameters are set to false.
@param boolean $expungeDeletes Defaults to false, merge segments with deletes away
@param boolean $waitFlush Defaults to true, block until index changes are flushed to disk
@param boolean $waitSearcher Defaults to true, block until a new searcher is opened and registered as the main query searcher, making the changes visible
@param float $timeout Maximum expected duration (in seconds) of the commit operation on the server (otherwise, will throw a communication exception). Defaults to 1 hour
@param boolean $softCommit Whether to perform a soft commit instead of a hard commit.
@return Apache_Solr_Response
@throws Apache_Solr_HttpTransportException If an error occurs during the service call | entailment |
public function softCommit($expungeDeletes = false, $waitFlush = true, $waitSearcher = true, $timeout = 3600)
{
return $this->commit($expungeDeletes, $waitFlush, $waitSearcher, $timeout, true);
} | Send a soft commit command. Will be synchronous unless both wait parameters are set to false.
@param boolean $expungeDeletes Defaults to false, merge segments with deletes away
@param boolean $waitFlush Defaults to true, block until index changes are flushed to disk
@param boolean $waitSearcher Defaults to true, block until a new searcher is opened and registered as the main query searcher, making the changes visible
@param float $timeout Maximum expected duration (in seconds) of the commit operation on the server (otherwise, will throw a communication exception). Defaults to 1 hour
@return Apache_Solr_Response
@throws Apache_Solr_HttpTransportException If an error occurs during the service call | entailment |
public function deleteById($id, $fromPending = true, $fromCommitted = true, $timeout = 3600)
{
$pendingValue = $fromPending ? 'true' : 'false';
$committedValue = $fromCommitted ? 'true' : 'false';
//escape special xml characters
$id = htmlspecialchars($id, ENT_NOQUOTES, 'UTF-8');
$rawPost = '<delete fromPending="' . $pendingValue . '" fromCommitted="' . $committedValue . '"><id>' . $id . '</id></delete>';
return $this->delete($rawPost, $timeout);
} | Create a delete document based on document ID
@param string $id Expected to be utf-8 encoded
@param boolean $fromPending
@param boolean $fromCommitted
@param float $timeout Maximum expected duration of the delete operation on the server (otherwise, will throw a communication exception)
@return Apache_Solr_Response
@throws Apache_Solr_HttpTransportException If an error occurs during the service call | entailment |
public function deleteByMultipleIds($ids, $fromPending = true, $fromCommitted = true, $timeout = 3600)
{
$pendingValue = $fromPending ? 'true' : 'false';
$committedValue = $fromCommitted ? 'true' : 'false';
$rawPost = '<delete fromPending="' . $pendingValue . '" fromCommitted="' . $committedValue . '">';
foreach ($ids as $id)
{
//escape special xml characters
$id = htmlspecialchars($id, ENT_NOQUOTES, 'UTF-8');
$rawPost .= '<id>' . $id . '</id>';
}
$rawPost .= '</delete>';
return $this->delete($rawPost, $timeout);
} | Create and post a delete document based on multiple document IDs.
@param array $ids Expected to be utf-8 encoded strings
@param boolean $fromPending
@param boolean $fromCommitted
@param float $timeout Maximum expected duration of the delete operation on the server (otherwise, will throw a communication exception)
@return Apache_Solr_Response
@throws Apache_Solr_HttpTransportException If an error occurs during the service call | entailment |
public function deleteByQuery($rawQuery, $fromPending = true, $fromCommitted = true, $timeout = 3600)
{
$pendingValue = $fromPending ? 'true' : 'false';
$committedValue = $fromCommitted ? 'true' : 'false';
// escape special xml characters
$rawQuery = htmlspecialchars($rawQuery, ENT_NOQUOTES, 'UTF-8');
$rawPost = '<delete fromPending="' . $pendingValue . '" fromCommitted="' . $committedValue . '"><query>' . $rawQuery . '</query></delete>';
return $this->delete($rawPost, $timeout);
} | Create a delete document based on a query and submit it
@param string $rawQuery Expected to be utf-8 encoded
@param boolean $fromPending
@param boolean $fromCommitted
@param float $timeout Maximum expected duration of the delete operation on the server (otherwise, will throw a communication exception)
@return Apache_Solr_Response
@throws Apache_Solr_HttpTransportException If an error occurs during the service call | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.