_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q249000 | HydraExtension.getMappingDriverBundleConfigDefaults | validation | protected function getMappingDriverBundleConfigDefaults(array $bundleConfig, \ReflectionClass $bundle, ContainerBuilder $container)
{
$bundleDir = dirname($bundle->getFilename());
if (!$bundleConfig['type']) {
$bundleConfig['type'] = $this->detectMetadataDriver($bundleDir, $container);
}
if (!$bundleConfig['type']) {
// skip this bundle, no mapping information was found.
return false;
}
if (!$bundleConfig['dir']) {
if (in_array($bundleConfig['type'], array('annotation', 'staticphp'))) {
$bundleConfig['dir'] = $bundleDir.'/'.$this->getMappingObjectDefaultName();
} else {
$bundleConfig['dir'] = $bundleDir.'/'.$this->getMappingResourceConfigDirectory();
}
} else {
$bundleConfig['dir'] = $bundleDir.'/'.$bundleConfig['dir'];
}
if (!$bundleConfig['prefix']) {
$bundleConfig['prefix'] = $bundle->getNamespaceName().'\\'.$this->getMappingObjectDefaultName();
}
return $bundleConfig;
} | php | {
"resource": ""
} |
q249001 | HydraExtension.detectMetadataDriver | validation | protected function detectMetadataDriver($dir, ContainerBuilder $container)
{
// add the closest existing directory as a resource
$configPath = $this->getMappingResourceConfigDirectory();
$resource = $dir.'/'.$configPath;
while (!is_dir($resource)) {
$resource = dirname($resource);
}
$container->addResource(new FileResource($resource));
$extension = $this->getMappingResourceExtension();
if (($files = glob($dir.'/'.$configPath.'/*.'.$extension.'.xml')) && count($files)) {
return 'xml';
} elseif (($files = glob($dir.'/'.$configPath.'/*.'.$extension.'.yml')) && count($files)) {
return 'yml';
} elseif (($files = glob($dir.'/'.$configPath.'/*.'.$extension.'.php')) && count($files)) {
return 'php';
}
// add the directory itself as a resource
$container->addResource(new FileResource($dir));
if (is_dir($dir.'/'.$this->getMappingObjectDefaultName())) {
return 'annotation';
}
return null;
} | php | {
"resource": ""
} |
q249002 | HydraExtension.validateMappingConfiguration | validation | protected function validateMappingConfiguration(array $mappingConfig, $mappingName)
{
if (!$mappingConfig['type'] || !$mappingConfig['dir'] || !$mappingConfig['prefix']) {
throw new \InvalidArgumentException(
sprintf('Hydra mapping definitions for "%s" require at least the "type", "dir" and "prefix" options.', $mappingName)
);
}
if (!is_dir($mappingConfig['dir'])) {
throw new \InvalidArgumentException(
sprintf('Specified non-existing directory "%s" as Hydra mapping source.', $mappingConfig['dir'])
);
}
if (!in_array($mappingConfig['type'], array('xml', 'yml', 'annotation', 'php', 'staticphp'))) {
// FIXXME Make sure hydra.metadata_driver exists
throw new \InvalidArgumentException(
'Can only configure "xml", "yml", "annotation", "php" or '.
'"staticphp" through the HydraBundle. Use your own bundle to configure other metadata drivers. '.
'You can register them by adding a new driver to the '.
'"hydra.metadata_driver" service definition.'
);
}
} | php | {
"resource": ""
} |
q249003 | HydraApi.getContext | validation | public function getContext($exposedClassName)
{
$classes = $this->metadata->getAllMetadata();
$metadata = null;
foreach ($classes as $class) {
if ($class->getExposeAs() === $exposedClassName) {
$metadata = $class;
break;
}
}
if (null === $metadata) {
return null;
}
$context = array(
'hydra' => 'http://www.w3.org/ns/hydra/core#',
'vocab' => $this->vocabUrl . '#'
);
$context[$exposedClassName] = ($metadata->isExternalReference())
? $metadata->getIri()
: 'vocab:' . $metadata->getIri();
foreach ($metadata->getProperties() as $property) {
// If something is exposed as keyword, no context definition is necessary
if (0 === strncmp($property->getExposeAs(), '@', 1)) {
// TODO Make this check more reliable by just checking for actual keywords
// What should we do if we serialize to RDFa for instance?
continue;
}
$termDefinition = ($property->isExternalReference())
? $property->getIri()
: 'vocab:' . $property->getIri();
// TODO Make this check more robust
if ($property->getRoute()) {
$termDefinition = array('@id' => $termDefinition, '@type' => '@id');
} elseif ($this->hasNormalizer($property->getType())) {
$normalizer = $this->getNormalizer($property->getType());
$termDefinition = array('@id' => $termDefinition, '@type' => $normalizer->getTypeIri());
}
$context[$property->getExposeAs()] = $termDefinition;
}
return array('@context' => $context);
} | php | {
"resource": ""
} |
q249004 | HydraApi.getDocumentation | validation | public function getDocumentation()
{
$metadata = $this->metadata->getAllMetadata();
$docu = array(
'@context' => array(
'vocab' => $this->vocabUrl . '#',
'hydra' => 'http://www.w3.org/ns/hydra/core#',
'ApiDocumentation' => 'hydra:ApiDocumentation',
'property' => array('@id' => 'hydra:property', '@type' => '@id'),
'readonly' => 'hydra:readonly',
'writeonly' => 'hydra:writeonly',
'supportedClass' => 'hydra:supportedClass',
'supportedProperty' => 'hydra:supportedProperty',
'supportedOperation' => 'hydra:supportedOperation',
'method' => 'hydra:method',
'expects' => array('@id' => 'hydra:expects', '@type' => '@id'),
'returns' => array('@id' => 'hydra:returns', '@type' => '@id'),
'statusCodes' => 'hydra:statusCodes',
'code' => 'hydra:statusCode',
'rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
'rdfs' => 'http://www.w3.org/2000/01/rdf-schema#',
'label' => 'rdfs:label',
'description' => 'rdfs:comment',
'domain' => array('@id' => 'rdfs:domain', '@type' => '@id'),
'range' => array('@id' => 'rdfs:range', '@type' => '@id'),
'subClassOf' => array('@id' => 'rdfs:subClassOf', '@type' => '@id'),
),
'@id' => $this->vocabUrl,
'@type' => 'ApiDocumentation',
'supportedClass' => array()
);
foreach ($metadata as $class) {
if ($class->isExternalReference()) {
$docu['supportedClass'][] = array(
'@id' => $class->getIri(),
'@type' => 'hydra:Class',
'hydra:title' => $class->getTitle(),
'hydra:description' => $class->getDescription(),
'supportedOperation' => $this->documentOperations($class->getOperations()),
'supportedProperty' => $this->documentClassProperties($class),
);
} else {
if (false !== ($superclass = get_parent_class($class->getName()))) {
try {
$superclass = $this->metadata->getMetadataFor($superclass);
$superclass = $superclass->isExternalReference()
? $superclass->getIri()
: 'vocab:' . $superclass->getIri();
} catch (\Exception $e) {
$superclass = null;
}
} else {
$superclass = null;
}
$docu['supportedClass'][] = array(
'@id' => 'vocab:' . $class->getIri(),
'@type' => 'hydra:Class',
'subClassOf' => $superclass,
'label' => $class->getTitle(),
'description' => $class->getDescription(),
'supportedOperation' => $this->documentOperations($class->getOperations()),
'supportedProperty' => $this->documentClassProperties($class),
);
}
}
return $docu;
} | php | {
"resource": ""
} |
q249005 | HydraApi.documentOperations | validation | private function documentOperations($operations)
{
if (null === $operations) {
return null;
}
$result = array();
foreach ($operations as $operation) {
$statusCodes = array();
foreach ($operation->getStatusCodes() as $code => $description) {
$statusCodes[] = array(
'code' => $code,
'description' => $description
);
}
$result[] = array(
'@id' => '_:' . $operation->getName(),
'@type' => $operation->getType() ?: 'hydra:Operation',
'method' => $operation->getMethod(),
'label' => ($operation->getTitle())
?
: $operation->getDescription(),
'description' => (null === $operation->getTitle())
? null
: $operation->getDescription(),
'expects' => $this->getTypeReferenceIri($operation->getExpects()),
'returns' => $this->getTypeReferenceIri($operation->getReturns()),
'statusCodes' => $statusCodes
);
}
return $result;
} | php | {
"resource": ""
} |
q249006 | HydraApi.documentClassProperties | validation | private function documentClassProperties(\ML\HydraBundle\Mapping\ClassMetadata $class)
{
$result = array();
$propertyDomain = $this->getTypeReferenceIri($class->getName());
foreach ($class->getProperties() as $property) {
if (0 === strncmp('@', $property->getExposeAs(), 1)) {
continue; // ignore properties that are mapped to keywords
}
$result[] = array(
'property' => ($property->isExternalReference())
? $property->getIri()
: array(
'@id' => 'vocab:' . $property->getIri(),
'@type' => ($property->getRoute())
? 'hydra:Link'
: 'rdf:Property',
'label' => $property->getTitle(),
'description' => $property->getDescription(),
'domain' => $propertyDomain,
'range' => $this->getTypeReferenceIri($property->getType()),
'supportedOperation' => $this->documentOperations($property->getOperations())
),
'hydra:title' => $property->getTitle(),
'hydra:description' => $property->getDescription(),
'required' => $property->getRequired(),
'readonly' => $property->isReadOnly(),
'writeonly' => $property->isWriteOnly()
);
}
return $result;
} | php | {
"resource": ""
} |
q249007 | DocumentationGeneratorController.getContextAction | validation | public function getContextAction($type)
{
$context = $this->get('hydra.api')->getContext($type);
if (null === $context) {
$this->createNotFoundException();
}
return new JsonLdResponse($context);
} | php | {
"resource": ""
} |
q249008 | DriverChain.loadMetadataForClass | validation | public function loadMetadataForClass($className)
{
foreach ($this->drivers as $namespace => $driver) {
if (strpos($className, $namespace) === 0) {
return $driver->loadMetadataForClass($className);
}
}
return null;
} | php | {
"resource": ""
} |
q249009 | Violin.validate | validation | public function validate(array $data, $rules = [])
{
$this->clearErrors();
$this->clearFieldAliases();
$data = $this->extractFieldAliases($data);
// If the rules array is empty, then it means we are
// receiving the rules directly with the input, so we need
// to extract the information.
if (empty($rules)) {
$rules = $this->extractRules($data);
$data = $this->extractInput($data);
}
$this->input = $data;
// Loop through all of the before callbacks and execute them.
foreach ($this->before as $before) {
call_user_func_array($before, [ $this ]);
}
foreach ($data as $field => $value) {
$fieldRules = explode('|', $rules[$field]);
foreach ($fieldRules as $rule) {
$continue = $this->validateAgainstRule(
$field,
$value,
$this->getRuleName($rule),
$this->getRuleArgs($rule)
);
// If the rule hasn't passed and it isn't skippable, then we
// don't need to validate the rest of the rules in the current
// field.
if (! $continue) {
break;
}
}
}
return $this;
} | php | {
"resource": ""
} |
q249010 | Violin.passes | validation | public function passes()
{
// Loop through all of the after callbacks and execute them.
foreach ($this->after as $after) {
call_user_func_array($after, [ $this ]);
}
return empty($this->errors);
} | php | {
"resource": ""
} |
q249011 | Violin.errors | validation | public function errors()
{
$messages = [];
foreach ($this->errors as $rule => $items) {
foreach ($items as $item) {
$field = $item['field'];
$message = $this->fetchMessage($field, $rule);
// If there is any alias for the current field, swap it.
if (isset($this->fieldAliases[$field])) {
$item['field'] = $this->fieldAliases[$field];
}
$messages[$field][] = $this->replaceMessageFormat($message, $item);
}
}
return new MessageBag($messages);
} | php | {
"resource": ""
} |
q249012 | Violin.fetchMessage | validation | protected function fetchMessage($field, $rule)
{
if (isset($this->fieldMessages[$field][$rule])) {
return $this->fieldMessages[$field][$rule];
}
if (isset($this->ruleMessages[$rule])) {
return $this->ruleMessages[$rule];
}
return $this->usedRules[$rule]->error();
} | php | {
"resource": ""
} |
q249013 | Violin.replaceMessageFormat | validation | protected function replaceMessageFormat($message, array $item)
{
$keys = array_keys($item);
if (!empty($item['args'])) {
$args = $item['args'];
$argReplace = array_map(function($i) {
return "{\${$i}}";
}, array_keys($args));
// Number of arguments
$args[] = count($item['args']);
$argReplace[] = '{$#}';
// All arguments
$args[] = implode(', ', $item['args']);
$argReplace[] = '{$*}';
// Replace arguments
$message = str_replace($argReplace, $args, $message);
}
// Replace field and value
$message = str_replace(
['{field}', '{value}'],
[$item['field'], $item['value']],
$message
);
return $message;
} | php | {
"resource": ""
} |
q249014 | Violin.validateAgainstRule | validation | protected function validateAgainstRule($field, $value, $rule, array $args)
{
$ruleToCall = $this->getRuleToCall($rule);
$passed = call_user_func_array($ruleToCall, [
$value,
$this->input,
$args
]);
if (!$passed) {
// If the rule didn't pass the validation, we will handle the error,
// and we check if we need to skip the next rules.
$this->handleError($field, $value, $rule, $args);
return $this->canSkipRule($ruleToCall, $value);
}
return true;
} | php | {
"resource": ""
} |
q249015 | Violin.canSkipRule | validation | protected function canSkipRule($ruleToCall, $value)
{
return (
(is_array($ruleToCall) &&
method_exists($ruleToCall[0], 'canSkip') &&
$ruleToCall[0]->canSkip()) ||
empty($value) &&
!is_array($value)
);
} | php | {
"resource": ""
} |
q249016 | Violin.handleError | validation | protected function handleError($field, $value, $rule, array $args)
{
$this->errors[$rule][] = [
'field' => $field,
'value' => $value,
'args' => $args,
];
} | php | {
"resource": ""
} |
q249017 | Violin.getRuleArgs | validation | protected function getRuleArgs($rule)
{
if (!$this->ruleHasArgs($rule)) {
return [];
}
list($ruleName, $argsWithBracketAtTheEnd) = explode('(', $rule);
$args = rtrim($argsWithBracketAtTheEnd, ')');
$args = preg_replace('/\s+/', '', $args);
$args = explode(',', $args);
return $args;
} | php | {
"resource": ""
} |
q249018 | Violin.extractFieldAliases | validation | protected function extractFieldAliases(array $data)
{
foreach ($data as $field => $fieldRules) {
$extraction = explode('|', $field);
if (isset($extraction[1])) {
$updatedField = $extraction[0];
$alias = $extraction[1];
$this->fieldAliases[$updatedField] = $alias;
$data[$updatedField] = $data[$field];
unset($data[$field]);
}
}
return $data;
} | php | {
"resource": ""
} |
q249019 | Violin.extractInput | validation | protected function extractInput(array $data)
{
$input = [];
foreach ($data as $field => $fieldData) {
$input[$field] = $fieldData[0];
}
return $input;
} | php | {
"resource": ""
} |
q249020 | Violin.extractRules | validation | protected function extractRules(array $data)
{
$rules = [];
foreach ($data as $field => $fieldData) {
$rules[$field] = $fieldData[1];
}
return $rules;
} | php | {
"resource": ""
} |
q249021 | Validator.validate_unique | validation | public function validate_unique($value, $input, $args)
{
$table = $args[0];
$column = $args[1];
$value = trim($value);
$exists = $this->db->prepare("
SELECT count(*) as count
FROM {$table}
WHERE {$column} = :value
");
$exists->execute([
'value' => $value
]);
return ! (bool) $exists->fetchObject()->count;
} | php | {
"resource": ""
} |
q249022 | MessageBag.get | validation | public function get($key)
{
if (array_key_exists($key, $this->messages)) {
return !empty($this->messages[$key]) ? $this->messages[$key] : null;
}
return null;
} | php | {
"resource": ""
} |
q249023 | Timezone.init | validation | public function init()
{
$this->actionRoute = Url::toRoute($this->actionRoute);
$this->name = Yii::$app->session->get('timezone');
if ($this->name == null) {
$this->registerTimezoneScript($this->actionRoute);
$this->name = date_default_timezone_get();
}
Yii::$app->setTimeZone($this->name);
} | php | {
"resource": ""
} |
q249024 | Timezone.registerTimezoneScript | validation | public function registerTimezoneScript($actionRoute)
{
Yii::$app->on(Controller::EVENT_BEFORE_ACTION, function ($event) use ($actionRoute) {
$view = $event->sender->view;
$js = <<<JS
var timezone = '';
var timezoneAbbr = '';
try {
var timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
var timezoneAbbr = /\((.*)\)/.exec(new Date().toString())[1];
}
catch(err) {
console.log(err);
}
$.post("$actionRoute", {
timezone: timezone,
timezoneAbbr: timezoneAbbr,
timezoneOffset: -new Date().getTimezoneOffset() / 60
});
JS;
$view->registerJs($js);
});
} | php | {
"resource": ""
} |
q249025 | Reader.addParser | validation | public function addParser($name, $class, $before = null)
{
if ($before === null) {
$this->parsers[$name] = $class;
return $this;
}
if (($offset = array_search($before, array_keys($this->parsers))) !== false) {
$this->parsers = array_slice($this->parsers, 0, $offset, true)
+ array($name => $class)
+ array_slice($this->parsers, $offset, null, true);
return $this;
}
throw new \RuntimeException(sprintf('Parser "%s" does not exist.', $before));
} | php | {
"resource": ""
} |
q249026 | Reader.setStatementClass | validation | public function setStatementClass($statementClass)
{
if (!is_callable($statementClass) && !class_exists($statementClass)) {
throw new \InvalidArgumentException('$statementClass must be a valid classname or a PHP callable');
}
$this->statementClass = $statementClass;
return $this;
} | php | {
"resource": ""
} |
q249027 | Reader.createStatement | validation | public function createStatement(AccountInterface $account, $number)
{
return $this->createObject($this->statementClass, 'Jejik\MT940\StatementInterface', array($account, $number));
} | php | {
"resource": ""
} |
q249028 | Reader.setAccountClass | validation | public function setAccountClass($accountClass)
{
if (!is_callable($accountClass) && !class_exists($accountClass)) {
throw new \InvalidArgumentException('$accountClass must be a valid classname or a PHP callable');
}
$this->accountClass = $accountClass;
return $this;
} | php | {
"resource": ""
} |
q249029 | Reader.setContraAccountClass | validation | public function setContraAccountClass($contraAccountClass)
{
if (!is_callable($contraAccountClass) && !class_exists($contraAccountClass)) {
throw new \InvalidArgumentException('$contraAccountClass must be a valid classname or a PHP callable');
}
$this->contraAccountClass = $contraAccountClass;
return $this;
} | php | {
"resource": ""
} |
q249030 | Reader.setTransactionClass | validation | public function setTransactionClass($transactionClass)
{
if (!is_callable($transactionClass) && !class_exists($transactionClass)) {
throw new \InvalidArgumentException('$transactionClass must be a valid classname or a PHP callable');
}
$this->transactionClass = $transactionClass;
return $this;
} | php | {
"resource": ""
} |
q249031 | Reader.setOpeningBalanceClass | validation | public function setOpeningBalanceClass($openingBalanceClass)
{
if (!is_callable($openingBalanceClass) && !class_exists($openingBalanceClass)) {
throw new \InvalidArgumentException('$openingBalanceClass must be a valid classname or a PHP callable');
}
$this->openingBalanceClass = $openingBalanceClass;
return $this;
} | php | {
"resource": ""
} |
q249032 | Reader.setClosingBalanceClass | validation | public function setClosingBalanceClass($closingBalanceClass)
{
if (!is_callable($closingBalanceClass) && !class_exists($closingBalanceClass)) {
throw new \InvalidArgumentException('$closingBalanceClass must be a valid classname or a PHP callable');
}
$this->closingBalanceClass = $closingBalanceClass;
return $this;
} | php | {
"resource": ""
} |
q249033 | Reader.createObject | validation | protected function createObject($className, $interface, $params = array())
{
if (is_string($className) && class_exists($className)) {
$object = new $className();
} elseif (is_callable($className)) {
$object = call_user_func_array($className, $params);
} else {
throw new \InvalidArgumentException('$className must be a valid classname or a PHP callable');
}
if (null !== $object && !($object instanceof $interface)) {
throw new \InvalidArgumentException(sprintf('%s must implement %s', get_class($object), $interface));
}
return $object;
} | php | {
"resource": ""
} |
q249034 | Reader.getStatements | validation | public function getStatements($text)
{
if (!$this->parsers) {
$this->addParsers($this->getDefaultParsers());
}
foreach ($this->parsers as $class) {
$parser = new $class($this);
if ($parser->accept($text)) {
return $parser->parse($text);
}
}
throw new \RuntimeException('No suitable parser found.');
} | php | {
"resource": ""
} |
q249035 | Triodos.accountNumber | validation | protected function accountNumber($text)
{
if ($account = $this->getLine('25', $text)) {
return ltrim(substr($account, 12), '0');
}
return null;
} | php | {
"resource": ""
} |
q249036 | Rabobank.statementBody | validation | protected function statementBody($text)
{
switch (substr($this->getLine('20', $text), 0, 4)) {
case '940A':
$this->format = self::FORMAT_CLASSIC;
break;
case '940S':
$this->format = self::FORMAT_STRUCTURED;
break;
default:
throw new \RuntimeException('Unknown file format');
}
return parent::statementBody($text);
} | php | {
"resource": ""
} |
q249037 | Rabobank.accountNumber | validation | protected function accountNumber($text)
{
$format = $this->format == self::FORMAT_CLASSIC ? '/^[0-9.]+/' : '/^[0-9A-Z]+/';
if ($account = $this->getLine('25', $text)) {
if (preg_match($format, $account, $match)) {
return str_replace('.', '', $match[0]);
}
}
return null;
} | php | {
"resource": ""
} |
q249038 | Rabobank.statementNumber | validation | protected function statementNumber($text)
{
if ($line = $this->getLine('60F', $text)) {
if (preg_match('/(C|D)(\d{6})([A-Z]{3})([0-9,]{1,15})/', $line, $match)) {
return $match[2];
}
}
return null;
} | php | {
"resource": ""
} |
q249039 | AbstractParser.parse | validation | public function parse($text)
{
$statements = array();
foreach ($this->splitStatements($text) as $chunk) {
if ($statement = $this->statement($chunk)) {
$statements[] = $statement;
}
}
return $statements;
} | php | {
"resource": ""
} |
q249040 | AbstractParser.getLine | validation | protected function getLine($id, $text, $offset = 0, &$position = null, &$length = null)
{
$pcre = '/(?:^|\r?\n)\:(' . $id . ')\:' // ":<id>:" at the start of a line
. '(.+)' // Contents of the line
. '(:?$|\r?\n\:[[:alnum:]]{2,3}\:)' // End of the text or next ":<id>:"
. '/Us'; // Ungreedy matching
// Offset manually, so the start of the offset can match ^
if (preg_match($pcre, substr($text, $offset), $match, PREG_OFFSET_CAPTURE)) {
$position = $offset + $match[1][1] - 1;
$length = strlen($match[2][0]);
return rtrim($match[2][0]);
}
return '';
} | php | {
"resource": ""
} |
q249041 | AbstractParser.splitStatements | validation | protected function splitStatements($text)
{
$chunks = preg_split('/^:20:/m', $text, -1);
$chunks = array_filter(array_map('trim', array_slice($chunks, 1)));
// Re-add the :20: at the beginning
return array_map(function ($statement) {
return ':20:' . $statement;
}, $chunks);
} | php | {
"resource": ""
} |
q249042 | AbstractParser.splitTransactions | validation | protected function splitTransactions($text)
{
$offset = 0;
$length = 0;
$position = 0;
$transactions = array();
while ($line = $this->getLine('61', $text, $offset, $offset, $length)) {
$offset += 4 + $length + 2;
$transaction = array($line);
// See if the next description line belongs to this transaction line.
// The description line should immediately follow the transaction line.
$description = array();
while ($line = $this->getLine('86', $text, $offset, $position, $length)) {
if ($position == $offset) {
$offset += 4 + $length + 2;
$description[] = $line;
} else {
break;
}
}
if ($description) {
$transaction[] = implode("\r\n", $description);
}
$transactions[] = $transaction;
}
return $transactions;
} | php | {
"resource": ""
} |
q249043 | AbstractParser.statement | validation | protected function statement($text)
{
$text = trim($text);
if (($pos = strpos($text, ':20:')) === false) {
throw new \RuntimeException('Not an MT940 statement');
}
$this->statementHeader(substr($text, 0, $pos));
return $this->statementBody(substr($text, $pos));
} | php | {
"resource": ""
} |
q249044 | AbstractParser.statementBody | validation | protected function statementBody($text)
{
$accountNumber = $this->accountNumber($text);
$account = $this->reader->createAccount($accountNumber);
if (!($account instanceof AccountInterface)) {
return null;
}
$account->setNumber($accountNumber);
$number = $this->statementNumber($text);
$statement = $this->reader->createStatement($account, $number);
if (!($statement instanceof StatementInterface)) {
return null;
}
$statement->setAccount($account)
->setNumber($this->statementNumber($text))
->setOpeningBalance($this->openingBalance($text))
->setClosingBalance($this->closingBalance($text));
foreach ($this->splitTransactions($text) as $chunk) {
$statement->addTransaction($this->transaction($chunk));
}
return $statement;
} | php | {
"resource": ""
} |
q249045 | AbstractParser.balance | validation | protected function balance(BalanceInterface $balance, $text)
{
if (!preg_match('/(C|D)(\d{6})([A-Z]{3})([0-9,]{1,15})/', $text, $match)) {
throw new \RuntimeException(sprintf('Cannot parse balance: "%s"', $text));
}
$amount = (float) str_replace(',', '.', $match[4]);
if ($match[1] === 'D') {
$amount *= -1;
}
$date = \DateTime::createFromFormat('ymd', $match[2]);
$date->setTime(0, 0, 0);
$balance->setCurrency($match[3])
->setAmount($amount)
->setDate($date);
return $balance;
} | php | {
"resource": ""
} |
q249046 | AbstractParser.openingBalance | validation | protected function openingBalance($text)
{
if ($line = $this->getLine('60F|60M', $text)) {
return $this->balance($this->reader->createOpeningBalance(), $line);
}
} | php | {
"resource": ""
} |
q249047 | AbstractParser.getNearestDateTimeFromDayAndMonth | validation | protected function getNearestDateTimeFromDayAndMonth(\DateTime $target, $day, $month)
{
$initialGuess = new \DateTime();
$initialGuess->setDate($target->format('Y'), $month, $day);
$initialGuess->setTime(0, 0, 0);
$initialGuessDiff = $target->diff($initialGuess);
$yearEarlier = clone $initialGuess;
$yearEarlier->modify('-1 year');
$yearEarlierDiff = $target->diff($yearEarlier);
if ($yearEarlierDiff->days < $initialGuessDiff->days) {
return $yearEarlier;
}
$yearLater = clone $initialGuess;
$yearLater->modify('+1 year');
$yearLaterDiff = $target->diff($yearLater);
if ($yearLaterDiff->days < $initialGuessDiff->days) {
return $yearLater;
}
return $initialGuess;
} | php | {
"resource": ""
} |
q249048 | PostFinance.closingBalance | validation | protected function closingBalance($text)
{
if ($line = $this->getLine('62M', $text)) {
return $this->balance($this->reader->createClosingBalance(), $line);
}
} | php | {
"resource": ""
} |
q249049 | Configuration.setCurlNumRetries | validation | public function setCurlNumRetries($retries)
{
if (!is_numeric($retries) || $retries < 0) {
throw new \InvalidArgumentException('Retries value must be numeric and a non-negative number.');
}
$this->curlNumRetries = $retries;
return $this;
} | php | {
"resource": ""
} |
q249050 | Configuration.toDebugReport | validation | public static function toDebugReport()
{
$report = 'PHP SDK (zipMoney) Debug Report:' . PHP_EOL;
$report .= ' OS: ' . php_uname() . PHP_EOL;
$report .= ' PHP Version: ' . phpversion() . PHP_EOL;
$report .= ' OpenAPI Spec Version: 2017-03-01' . PHP_EOL;
$report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL;
return $report;
} | php | {
"resource": ""
} |
q249051 | Configuration.getPackageVersion | validation | public function getPackageVersion()
{
$package_config = file_get_contents(dirname(__FILE__)."./../composer.json");
if($package_config){
$package_config_object = json_decode($package_config);
if(is_object($package_config_object) && isset($package_config_object->version)){
return $package_config_object->version;
}
}
return null;
} | php | {
"resource": ""
} |
q249052 | jDateTime.filterArray | validation | private static function filterArray($needle, $heystack, $always = array())
{
foreach($heystack as $k => $v)
{
if( !in_array($v, $needle) && !in_array($v, $always) )
unset($heystack[$k]);
}
return $heystack;
} | php | {
"resource": ""
} |
q249053 | jDateTime.toJalaliStr | validation | public static function toJalaliStr($g_date, $curSep = '-', $newSep = '/')
{
$arr = explode($curSep, $g_date);
if (count($arr) < 3 || intval($arr[2]) == 0) //invalid dates
return "";
else
$j_date = jDateTime::toJalali($arr[0],$arr[1],$arr[2]);
$j_date_rev = array($j_date[2],$j_date[1],$j_date[0]);
return implode($newSep,$j_date_rev);
} | php | {
"resource": ""
} |
q249054 | jDateTime.toGregorianStr | validation | public static function toGregorianStr($j_date, $sep = '/')
{
$arr = explode($sep,$j_date);
if (count($arr) < 3 || intval($arr[0]) == 0) // invalid date
return "";
else
$g_date = jDateTime::toGregorian($arr[2],$arr[1],$arr[0]);
return implode($sep,$g_date);
} | php | {
"resource": ""
} |
q249055 | DataTablesComponent._processRequest | validation | private function _processRequest()
{
// -- check whether it is an ajax call from data tables server-side plugin or a normal request
$this->_isAjaxRequest = $this->request->is('ajax');
// -- add limit
if( isset($this->request->query['length']) && !empty($this->request->query['length']) )
{
$this->config('length', $this->request->query['length']);
}
// -- add offset
if( isset($this->request->query['start']) && !empty($this->request->query['start']) )
{
$this->config('start', (int)$this->request->query['start']);
}
// -- add order
if( isset($this->request->query['order']) && !empty($this->request->query['order']) )
{
$order = $this->config('order');
foreach($this->request->query['order'] as $item) {
$order[$this->request->query['columns'][$item['column']]['name']] = $item['dir'];
}
$this->config('order', $order);
}
// -- add draw (an additional field of data tables plugin)
if( isset($this->request->query['draw']) && !empty($this->request->query['draw']) )
{
$this->_viewVars['draw'] = (int)$this->request->query['draw'];
}
// -- don't support any search if columns data missing
if( !isset($this->request->query['columns']) ||
empty($this->request->query['columns']) )
{
return;
}
// -- check table search field
$globalSearch = (isset($this->request->query['search']['value']) ?
$this->request->query['search']['value'] : false);
// -- add conditions for both table-wide and column search fields
foreach($this->request->query['columns'] as $column)
{
if( $globalSearch && $column['searchable'] == 'true' ) {
$this->_addCondition( $column['name'], $globalSearch, 'or' );
}
$localSearch = $column['search']['value'];
/* In some circumstances (no "table-search" row present), DataTables
fills in all column searches with the global search. Compromise:
Ignore local field if it matches global search. */
if( !empty($localSearch) && ($localSearch !== $globalSearch) ) {
$this->_addCondition( $column['name'], $column['search']['value'] );
}
}
} | php | {
"resource": ""
} |
q249056 | EndaEditor.uploadImgFile | validation | public static function uploadImgFile($path){
try{
// File Upload
if (Request::hasFile('image')){
$pic = Request::file('image');
if($pic->isValid()){
$newName = md5(rand(1,1000).$pic->getClientOriginalName()).".".$pic->getClientOriginalExtension();
$pic->move($path,$newName);
$url = asset($path.'/'.$newName);
}else{
self::addError('The file is invalid');
}
}else{
self::addError('Not File');
}
}catch (\Exception $e){
self::addError($e->getMessage());
}
$data = array(
'status'=>empty($message)?0:1,
'message'=>self::getLastError(),
'url'=>!empty($url)?$url:''
);
return $data;
} | php | {
"resource": ""
} |
q249057 | Callback.event | validation | public function event(string $event): self
{
$events = [
'MESSAGE_RECEIVED',
'MESSAGE_SENT',
'MESSAGE_FAILED',
];
if (!in_array($event, $events)) {
abort(500, sprintf('Event %s not available.', $event));
}
$this->event = $event;
return $this;
} | php | {
"resource": ""
} |
q249058 | Callback.secret | validation | public function secret(string $secret = ''): self
{
if (empty($secret)) {
$secret = str_random(15);
}
$this->secret = $secret;
return $this;
} | php | {
"resource": ""
} |
q249059 | Callback.create | validation | public function create(): ?array
{
$body = Body::json([
'name' => $this->name,
'event' => $this->event,
'device_id' => $this->device,
'filter_type' => '',
'filter' => '',
'method' => 'http',
'action' => $this->url,
'secret' => $this->secret,
]);
$response = Request::post($this->baseUrl.'callback', [], $body);
if ($response->code != 200) {
if (!empty($response->body->message)) {
Log::error($response->body->message);
}
}
return [
'code' => $response->code,
'message' => ($response->code == 200) ? 'OK' : $response->body->message ?? '',
'data' => $response->body,
];
} | php | {
"resource": ""
} |
q249060 | YamlPipelineRepository.settle | validation | public function settle()
{
$this->files->makeDirectory($this->path, 0755, true, true);
$this->files->put($this->getSource(), '');
} | php | {
"resource": ""
} |
q249061 | YamlPipelineRepository.store | validation | public function store($pipeline, array $pipes)
{
$workflow = [$pipeline => $pipes];
$yaml = $this->parser->dump($workflow);
$this->files->append($this->getSource(), $yaml);
} | php | {
"resource": ""
} |
q249062 | YamlPipelineRepository.update | validation | public function update($pipeline, array $attachments, array $detachments)
{
$this->detach($this->pipelines[$pipeline], $detachments);
$this->attach($this->pipelines[$pipeline], $attachments);
$this->refreshPipelines();
} | php | {
"resource": ""
} |
q249063 | YamlPipelineRepository.refreshPipelines | validation | protected function refreshPipelines()
{
$yaml = $this->parser->dump($this->pipelines);
$this->files->put($this->getSource(), $yaml);
} | php | {
"resource": ""
} |
q249064 | UpdateWorkflowCommand.updateWorkflow | validation | protected function updateWorkflow($workflow)
{
$attachments = $this->getNamespacedPipesByOption('attach');
$detachments = $this->getNamespacedPipesByOption('detach');
$this->pipelines->update($workflow, $attachments, $detachments);
} | php | {
"resource": ""
} |
q249065 | Geometry.getHalfWidth | validation | public function getHalfWidth($up = false)
{
$number = $this->getTotalWidth();
return $this->roundHalf($number, $up);
} | php | {
"resource": ""
} |
q249066 | Geometry.getTotalWidth | validation | protected function getTotalWidth()
{
$borders = (static::BORDER_WIDTH + static::MIN_SPACE_FROM_BORDER_X) * 2;
if(empty($this->pipes))
{
return $borders + $this->getCoreLength();
}
$borders *= count($this->pipes);
$name = ($this->getLongestPipeLength() + static::SPACE_FROM_ARROW) * 2;
return $borders + $name + static::ARROW_WIDTH;
} | php | {
"resource": ""
} |
q249067 | Geometry.getLongestPipeLength | validation | protected function getLongestPipeLength()
{
if(empty($this->pipes)) return 0;
return array_reduce($this->pipes, function($carry, $pipe)
{
return strlen($pipe) > $carry ? strlen($pipe) : $carry;
}, static::MIN_PIPE_LENGTH);
} | php | {
"resource": ""
} |
q249068 | Geometry.getSpacedPipe | validation | public function getSpacedPipe($pipe, $arrow, $method)
{
$left = $this->getSpacesByWord($pipe);
$arrow = $this->addSpacesToArrow($arrow);
$right = $this->getSpacesByWord($method);
return $left.$pipe.$arrow.$method.$right;
} | php | {
"resource": ""
} |
q249069 | Geometry.getSpacesByWord | validation | protected function getSpacesByWord($word)
{
$length = $this->getSideBordersLength() + static::SPACE_FROM_ARROW + static::ARROW_WIDTH;
$extra = $this->getHalfWidth(true) - $length - strlen($word);
return $extra > 0 ? str_repeat(' ', $extra) : '';
} | php | {
"resource": ""
} |
q249070 | Geometry.getLeftBordersWith | validation | public function getLeftBordersWith($border)
{
$border = str_repeat($border, static::BORDER_WIDTH);
$space = str_repeat(' ', static::MIN_SPACE_FROM_BORDER_X);
return str_repeat("{$border}{$space}", $this->nesting);
} | php | {
"resource": ""
} |
q249071 | Geometry.getRightBordersWith | validation | public function getRightBordersWith($border)
{
$space = str_repeat(' ', static::MIN_SPACE_FROM_BORDER_X);
$border = str_repeat($border, static::BORDER_WIDTH);
return str_repeat("{$space}{$border}", $this->nesting);
} | php | {
"resource": ""
} |
q249072 | Geometry.getSpacedCore | validation | public function getSpacedCore()
{
$left = $this->getSpacesByCore();
$right = $this->getSpacesByCore(true);
return $left.$this->core.$right;
} | php | {
"resource": ""
} |
q249073 | Geometry.getSpacesByCore | validation | protected function getSpacesByCore($up = false)
{
$free = $this->getTotalWidth() - $this->getBordersLength() - $this->getCoreLength();
return $free < 1 ? '' : str_repeat(' ', $this->roundHalf($free, $up));
} | php | {
"resource": ""
} |
q249074 | AttachesPipesTrait.generatePipes | validation | protected function generatePipes()
{
foreach ($this->getPipesByOption('attach') as $pipe)
{
$this->currentPipe = $pipe;
parent::fire();
}
} | php | {
"resource": ""
} |
q249075 | AttachesPipesTrait.getPipesByOption | validation | protected function getPipesByOption($option)
{
$pipes = $this->option($option);
preg_match_all('/\w+/', $pipes, $matches);
return array_map('ucfirst', $matches[0]);
} | php | {
"resource": ""
} |
q249076 | AttachesPipesTrait.getWorkflowsNamespace | validation | protected function getWorkflowsNamespace()
{
$relative = ltrim(config('workflow.path'), app_path());
$chunks = array_map('ucfirst', explode('/', $relative));
return implode('\\', $chunks);
} | php | {
"resource": ""
} |
q249077 | DeleteWorkflowCommand.deleteAllFilesOfWorkflowIfForced | validation | protected function deleteAllFilesOfWorkflowIfForced($workflow)
{
$files = $this->pipelines->getPipesByPipeline($workflow);
$files[] = $this->inflector->getRequest();
$files[] = $this->inflector->getJob();
$this->deleteIfForced($files);
} | php | {
"resource": ""
} |
q249078 | SmsServiceProvider.register | validation | public function register()
{
$className = studly_case(strtolower(config('message.vendor', 'smsgatewayme')));
$classPath = '\Yugo\SMSGateway\Vendors\\'.$className;
if (!class_exists($classPath)) {
abort(500, sprintf(
'SMS vendor %s is not available.',
$className
));
}
app()->bind(SMS::class, $classPath);
} | php | {
"resource": ""
} |
q249079 | Contact.create | validation | public function create(string $name, array $numbers): ?array
{
$body = Body::json([
[
'name' => $name,
'phone_numbers' => $numbers,
],
]);
$response = Request::post($this->baseUrl.'contact', [], $body);
if ($response->code != 200) {
if (!empty($response->body->message)) {
Log::error($response->body->message);
}
}
return [
'code' => $response->code,
'message' => ($response->code == 200) ? 'OK' : $response->body->message ?? '',
'data' => $response->body,
];
} | php | {
"resource": ""
} |
q249080 | Contact.info | validation | public function info(int $id): ?array
{
$response = Request::get($this->baseUrl.'contact/'.$id);
if ($response->code != 200) {
if (!empty($response->body->message)) {
Log::error($response->body->message);
}
}
return [
'code' => $response->code,
'message' => ($response->code == 200) ? 'OK' : $response->body->message ?? '',
'data' => $response->body,
];
} | php | {
"resource": ""
} |
q249081 | Contact.addNumber | validation | public function addNumber(int $id, string $number): ?array
{
$response = Request::put($this->baseUrl.sprintf('contact/%d/phone-number/%s', $id, $number));
if ($response->code != 200) {
if (!empty($response->body->message)) {
Log::error($response->body->message);
}
}
return [
'code' => $response->code,
'message' => ($response->code == 200) ? 'OK' : $response->body->message ?? '',
'data' => $response->body,
];
} | php | {
"resource": ""
} |
q249082 | Contact.removeNumber | validation | public function removeNumber(int $id, string $number): ?array
{
$response = Request::delete($this->baseUrl.sprintf('contact/%d/phone-number/%s', $id, $number));
if ($response->code != 200) {
if (!empty($response->body->message)) {
Log::error($response->body->message);
}
}
return [
'code' => $response->code,
'message' => ($response->code == 200) ? 'OK' : $response->body->message ?? '',
'data' => $response->body,
];
} | php | {
"resource": ""
} |
q249083 | AbstractPipe.handle | validation | public function handle($job, Closure $next)
{
$this->callBefore($job);
$handled = $next($job);
$this->callAfter($handled, $job);
return $handled;
} | php | {
"resource": ""
} |
q249084 | AbstractPipe.callIfExists | validation | private function callIfExists($method, array $parameters = [])
{
if(method_exists($this, $method))
{
$this->container->call([$this, $method], $parameters);
}
} | php | {
"resource": ""
} |
q249085 | Smsgatewayme.device | validation | public function device(?int $id = null): ?array
{
if (is_null($id)) {
$id = $this->device;
}
$key = sprintf('smsgatewayme.device.%s', $id);
$device = Cache::remember($key, 3600 * 24 * 7, function () use (&$response, $id) {
$response = Request::get($this->baseUrl.'device/'.$id);
if ($response->code != 200) {
if (!empty($response->body->message)) {
Log::error($response->body->message);
}
}
return $response->body;
});
return [
'code' => $response->code ?? 200,
'message' => 'OK',
'data' => $device,
];
} | php | {
"resource": ""
} |
q249086 | Smsgatewayme.send | validation | public function send(array $destinations, string $text): ?array
{
$this->checkConfig();
$messages = [];
foreach ($destinations as $destination) {
$messages[] = [
'phone_number' => $destination,
'message' => $text,
'device_id' => $this->device,
];
}
$body = Body::json($messages);
$response = Request::post($this->baseUrl.'message/send', [], $body);
if ($response->code == 200) {
return [
'code' => $response->code,
'message' => 'OK',
'data' => $response->body,
];
} else {
if (!empty($response->body->message)) {
Log::error($response->body->message);
}
return [
'code' => $response->code,
'message' => $response->body->message ?? '',
'data' => $response->body,
];
}
} | php | {
"resource": ""
} |
q249087 | Smsgatewayme.cancel | validation | public function cancel(array $identifiers = []): ?array
{
$this->checkConfig();
if (empty($identifiers)) {
return null;
}
$messages = [];
foreach ($identifiers as $id) {
$messages[] = ['id' => (int) $id];
}
$body = Body::json($messages);
$response = Request::post($this->baseUrl.'message/cancel', [], $body);
if ($response->code == 200) {
return [
'code' => $response->code,
'message' => 'OK',
'data' => $response->body,
];
} else {
if (!empty($response->body->message)) {
Log::error($response->body->message);
}
return [
'code' => $response->code,
'message' => $response->body->message ?? '',
'data' => $response->body,
];
}
} | php | {
"resource": ""
} |
q249088 | Smsgatewayme.info | validation | public function info(int $id): ?array
{
$this->checkConfig();
$key = sprintf('smsgatewayme.info.%s', $id);
if ($this->cache === true and Cache::has($key)) {
$message = [
'code' => 200,
'message' => 'OK',
'data' => Cache::get($key),
];
} else {
$response = Request::get($this->baseUrl.'message/'.$id);
if ($response->code == 200) {
Cache::put($key, $response->body, 3600 * 24);
} else {
if (!empty($response->body->message)) {
Log::error($response->body->message);
}
}
$message = [
'code' => $response->code,
'message' => ($response->code == 200) ? 'OK' : $response->body->message ?? '',
'data' => $response->body,
];
}
return $message;
} | php | {
"resource": ""
} |
q249089 | Smsgatewayme.checkConfig | validation | private function checkConfig(): void
{
if (empty($this->device)) {
Log::warning('Config "message.smsgatewayme.device" is not defined.');
}
if (empty($this->token)) {
Log::warning('Config "message.smsgatewayme.token" is not defined.');
}
} | php | {
"resource": ""
} |
q249090 | MarshalDispatcher.dispatchFrom | validation | public function dispatchFrom($command, ArrayAccess $source, array $extras = [])
{
$this->command = $command;
$this->values = array_merge((array) $source, $extras);
return $this->dispatcher->dispatch($this->marshal());
} | php | {
"resource": ""
} |
q249091 | MarshalDispatcher.marshal | validation | protected function marshal()
{
$reflection = new ReflectionClass($this->command);
$constructor = $reflection->getConstructor();
$params = $this->getParamsToInject($constructor->getParameters());
return $reflection->newInstanceArgs($params);
} | php | {
"resource": ""
} |
q249092 | MarshalDispatcher.grabParameter | validation | protected function grabParameter(ReflectionParameter $parameter)
{
if (isset($this->values[$parameter->name]))
{
return $this->values[$parameter->name];
}
if ($parameter->isDefaultValueAvailable())
{
return $parameter->getDefaultValue();
}
throw new Exception("Unable to map parameter [{$parameter->name}] to command [{$this->command}]");
} | php | {
"resource": ""
} |
q249093 | Workflow.dispatchWorkflow | validation | protected function dispatchWorkflow($workflow)
{
$job = $this->inflector->getJob();
$request = $this->resolveRequest();
$pipes = $this->pipelines->getPipesByPipeline($workflow);
$parameters = $this->container->make('router')->current()->parameters();
return $this->dispatcher->pipeThrough($pipes)->dispatchFrom($job, $request, $parameters);
} | php | {
"resource": ""
} |
q249094 | Workflow.resolveRequest | validation | protected function resolveRequest()
{
if(class_exists($request = $this->inflector->getRequest()))
{
return $this->container->make($request);
}
return $this->container->make('Illuminate\Http\Request');
} | php | {
"resource": ""
} |
q249095 | DeleteIfForcedTrait.deleteIfForced | validation | protected function deleteIfForced(array $files)
{
if( ! $this->option('force')) return;
foreach ($files as $file)
{
if($this->files->exists($path = $this->getPath($file)))
{
$this->files->delete($path);
}
}
} | php | {
"resource": ""
} |
q249096 | WorkflowServiceProvider.boot | validation | public function boot()
{
$this->publishConfig();
$this->commands($this->commands);
$facade = 'Cerbero\Workflow\Facades\Workflow';
AliasLoader::getInstance()->alias('Workflow', $facade);
} | php | {
"resource": ""
} |
q249097 | WorkflowServiceProvider.publishConfig | validation | private function publishConfig()
{
$config = __DIR__ . '/config/workflow.php';
$this->publishes([$config => config_path('workflow.php')]);
$this->mergeConfigFrom($config, 'workflow');
} | php | {
"resource": ""
} |
q249098 | WorkflowServiceProvider.register | validation | public function register()
{
$this->registerPipelineRepository();
$this->registerInflector();
$this->registerDispatcher();
$this->registerWorkflow();
$this->registerWorkflowRunnersHook();
$this->registerCommands();
} | php | {
"resource": ""
} |
q249099 | WorkflowServiceProvider.registerPipelineRepository | validation | private function registerPipelineRepository()
{
$abstract = 'Cerbero\Workflow\Repositories\PipelineRepositoryInterface';
$this->app->bind($abstract, function($app)
{
return new YamlPipelineRepository
(
new SymfonyYamlParser,
new \Illuminate\Filesystem\Filesystem,
config('workflow.path')
);
});
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.