repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
commerceguys/intl | src/Formatter/NumberFormatter.php | NumberFormatter.parse | public function parse($number, array $options = [])
{
$this->validateOptions($options);
$options = array_replace($this->defaultOptions, $options);
$numberFormat = $this->getNumberFormat($options['locale']);
$number = $this->parseNumber($number, $numberFormat);
return $number;
} | php | public function parse($number, array $options = [])
{
$this->validateOptions($options);
$options = array_replace($this->defaultOptions, $options);
$numberFormat = $this->getNumberFormat($options['locale']);
$number = $this->parseNumber($number, $numberFormat);
return $number;
} | [
"public",
"function",
"parse",
"(",
"$",
"number",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"validateOptions",
"(",
"$",
"options",
")",
";",
"$",
"options",
"=",
"array_replace",
"(",
"$",
"this",
"->",
"defaultOptions... | {@inheritdoc} | [
"{"
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Formatter/NumberFormatter.php#L91-L99 |
commerceguys/intl | src/Formatter/NumberFormatter.php | NumberFormatter.getNumberFormat | protected function getNumberFormat($locale)
{
if (!isset($this->numberFormats[$locale])) {
$this->numberFormats[$locale] = $this->numberFormatRepository->get($locale);
}
return $this->numberFormats[$locale];
} | php | protected function getNumberFormat($locale)
{
if (!isset($this->numberFormats[$locale])) {
$this->numberFormats[$locale] = $this->numberFormatRepository->get($locale);
}
return $this->numberFormats[$locale];
} | [
"protected",
"function",
"getNumberFormat",
"(",
"$",
"locale",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"numberFormats",
"[",
"$",
"locale",
"]",
")",
")",
"{",
"$",
"this",
"->",
"numberFormats",
"[",
"$",
"locale",
"]",
"=",
"$",... | Gets the number format for the provided locale.
@param string $locale The locale.
@return NumberFormat | [
"Gets",
"the",
"number",
"format",
"for",
"the",
"provided",
"locale",
"."
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Formatter/NumberFormatter.php#L108-L115 |
commerceguys/intl | src/Formatter/NumberFormatter.php | NumberFormatter.validateOptions | protected function validateOptions(array $options)
{
foreach ($options as $option => $value) {
if (!array_key_exists($option, $this->defaultOptions)) {
throw new InvalidArgumentException(sprintf('Unrecognized option "%s".', $option));
}
}
if (isset($options['use_grouping']) && !is_bool($options['use_grouping'])) {
throw new InvalidArgumentException('The option "use_grouping" must be a boolean.');
}
foreach (['minimum_fraction_digits', 'maximum_fraction_digits'] as $option) {
if (array_key_exists($option, $options) && !is_numeric($options[$option])) {
throw new InvalidArgumentException(sprintf('The option "%s" must be numeric.', $option));
}
}
$roundingModes = [
PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN,
PHP_ROUND_HALF_EVEN, PHP_ROUND_HALF_ODD, 'none',
];
if (!empty($options['rounding_mode']) && !in_array($options['rounding_mode'], $roundingModes)) {
throw new InvalidArgumentException(sprintf('Unrecognized rounding mode "%s".', $options['rounding_mode']));
}
if (!empty($options['style']) && !in_array($options['style'], ['decimal', 'percent'])) {
throw new InvalidArgumentException(sprintf('Unrecognized style "%s".', $options['style']));
}
} | php | protected function validateOptions(array $options)
{
foreach ($options as $option => $value) {
if (!array_key_exists($option, $this->defaultOptions)) {
throw new InvalidArgumentException(sprintf('Unrecognized option "%s".', $option));
}
}
if (isset($options['use_grouping']) && !is_bool($options['use_grouping'])) {
throw new InvalidArgumentException('The option "use_grouping" must be a boolean.');
}
foreach (['minimum_fraction_digits', 'maximum_fraction_digits'] as $option) {
if (array_key_exists($option, $options) && !is_numeric($options[$option])) {
throw new InvalidArgumentException(sprintf('The option "%s" must be numeric.', $option));
}
}
$roundingModes = [
PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN,
PHP_ROUND_HALF_EVEN, PHP_ROUND_HALF_ODD, 'none',
];
if (!empty($options['rounding_mode']) && !in_array($options['rounding_mode'], $roundingModes)) {
throw new InvalidArgumentException(sprintf('Unrecognized rounding mode "%s".', $options['rounding_mode']));
}
if (!empty($options['style']) && !in_array($options['style'], ['decimal', 'percent'])) {
throw new InvalidArgumentException(sprintf('Unrecognized style "%s".', $options['style']));
}
} | [
"protected",
"function",
"validateOptions",
"(",
"array",
"$",
"options",
")",
"{",
"foreach",
"(",
"$",
"options",
"as",
"$",
"option",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"option",
",",
"$",
"this",
"->",
"defa... | Validates the provided options.
Ensures the absence of unknown keys, correct data types and values.
@param array $options The options.
@throws \InvalidArgumentException | [
"Validates",
"the",
"provided",
"options",
"."
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Formatter/NumberFormatter.php#L137-L162 |
commerceguys/intl | src/Currency/CurrencyRepository.php | CurrencyRepository.get | public function get($currencyCode, $locale = null)
{
$currencyCode = strtoupper($currencyCode);
$baseDefinitions = $this->getBaseDefinitions();
if (!isset($baseDefinitions[$currencyCode])) {
throw new UnknownCurrencyException($currencyCode);
}
$locale = $locale ?: $this->defaultLocale;
$locale = Locale::resolve($this->availableLocales, $locale, $this->fallbackLocale);
$definitions = $this->loadDefinitions($locale);
$currency = new Currency([
'currency_code' => $currencyCode,
'numeric_code' => $baseDefinitions[$currencyCode][0],
'fraction_digits' => $baseDefinitions[$currencyCode][1],
'locale' => $locale,
] + $definitions[$currencyCode]);
return $currency;
} | php | public function get($currencyCode, $locale = null)
{
$currencyCode = strtoupper($currencyCode);
$baseDefinitions = $this->getBaseDefinitions();
if (!isset($baseDefinitions[$currencyCode])) {
throw new UnknownCurrencyException($currencyCode);
}
$locale = $locale ?: $this->defaultLocale;
$locale = Locale::resolve($this->availableLocales, $locale, $this->fallbackLocale);
$definitions = $this->loadDefinitions($locale);
$currency = new Currency([
'currency_code' => $currencyCode,
'numeric_code' => $baseDefinitions[$currencyCode][0],
'fraction_digits' => $baseDefinitions[$currencyCode][1],
'locale' => $locale,
] + $definitions[$currencyCode]);
return $currency;
} | [
"public",
"function",
"get",
"(",
"$",
"currencyCode",
",",
"$",
"locale",
"=",
"null",
")",
"{",
"$",
"currencyCode",
"=",
"strtoupper",
"(",
"$",
"currencyCode",
")",
";",
"$",
"baseDefinitions",
"=",
"$",
"this",
"->",
"getBaseDefinitions",
"(",
")",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Currency/CurrencyRepository.php#L86-L104 |
commerceguys/intl | src/Currency/CurrencyRepository.php | CurrencyRepository.getAll | public function getAll($locale = null)
{
$locale = $locale ?: $this->defaultLocale;
$locale = Locale::resolve($this->availableLocales, $locale, $this->fallbackLocale);
$baseDefinitions = $this->getBaseDefinitions();
$definitions = $this->loadDefinitions($locale);
$currencies = [];
foreach ($definitions as $currencyCode => $definition) {
$currencies[$currencyCode] = new Currency([
'currency_code' => $currencyCode,
'numeric_code' => $baseDefinitions[$currencyCode][0],
'fraction_digits' => $baseDefinitions[$currencyCode][1],
'locale' => $locale,
] + $definition);
}
return $currencies;
} | php | public function getAll($locale = null)
{
$locale = $locale ?: $this->defaultLocale;
$locale = Locale::resolve($this->availableLocales, $locale, $this->fallbackLocale);
$baseDefinitions = $this->getBaseDefinitions();
$definitions = $this->loadDefinitions($locale);
$currencies = [];
foreach ($definitions as $currencyCode => $definition) {
$currencies[$currencyCode] = new Currency([
'currency_code' => $currencyCode,
'numeric_code' => $baseDefinitions[$currencyCode][0],
'fraction_digits' => $baseDefinitions[$currencyCode][1],
'locale' => $locale,
] + $definition);
}
return $currencies;
} | [
"public",
"function",
"getAll",
"(",
"$",
"locale",
"=",
"null",
")",
"{",
"$",
"locale",
"=",
"$",
"locale",
"?",
":",
"$",
"this",
"->",
"defaultLocale",
";",
"$",
"locale",
"=",
"Locale",
"::",
"resolve",
"(",
"$",
"this",
"->",
"availableLocales",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Currency/CurrencyRepository.php#L109-L126 |
commerceguys/intl | src/Currency/CurrencyRepository.php | CurrencyRepository.getList | public function getList($locale = null)
{
$locale = $locale ?: $this->defaultLocale;
$locale = Locale::resolve($this->availableLocales, $locale, $this->fallbackLocale);
$definitions = $this->loadDefinitions($locale);
$list = [];
foreach ($definitions as $currencyCode => $definition) {
$list[$currencyCode] = $definition['name'];
}
return $list;
} | php | public function getList($locale = null)
{
$locale = $locale ?: $this->defaultLocale;
$locale = Locale::resolve($this->availableLocales, $locale, $this->fallbackLocale);
$definitions = $this->loadDefinitions($locale);
$list = [];
foreach ($definitions as $currencyCode => $definition) {
$list[$currencyCode] = $definition['name'];
}
return $list;
} | [
"public",
"function",
"getList",
"(",
"$",
"locale",
"=",
"null",
")",
"{",
"$",
"locale",
"=",
"$",
"locale",
"?",
":",
"$",
"this",
"->",
"defaultLocale",
";",
"$",
"locale",
"=",
"Locale",
"::",
"resolve",
"(",
"$",
"this",
"->",
"availableLocales",... | {@inheritdoc} | [
"{"
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Currency/CurrencyRepository.php#L131-L142 |
commerceguys/intl | src/Formatter/CurrencyFormatter.php | CurrencyFormatter.format | public function format($number, $currencyCode, array $options = [])
{
if (!is_numeric($number)) {
$message = sprintf('The provided value "%s" is not a valid number or numeric string.', $number);
throw new InvalidArgumentException($message);
}
$this->validateOptions($options);
$options = array_replace($this->defaultOptions, $options);
$numberFormat = $this->getNumberFormat($options['locale']);
$currency = $this->getCurrency($currencyCode, $options['locale']);
// Use the currency defaults if the values weren't set by the caller.
if (!isset($options['minimum_fraction_digits'])) {
$options['minimum_fraction_digits'] = $currency->getFractionDigits();
}
if (!isset($options['maximum_fraction_digits'])) {
$options['maximum_fraction_digits'] = $currency->getFractionDigits();
}
$number = (string) $number;
$number = $this->formatNumber($number, $numberFormat, $options);
if ($options['currency_display'] == 'symbol') {
$number = str_replace('¤', $currency->getSymbol(), $number);
} elseif ($options['currency_display'] == 'code') {
$number = str_replace('¤', $currency->getCurrencyCode(), $number);
} else {
// No symbol should be displayed. Remove leftover whitespace.
$number = str_replace('¤', '', $number);
$number = trim($number, " \xC2\xA0");
}
return $number;
} | php | public function format($number, $currencyCode, array $options = [])
{
if (!is_numeric($number)) {
$message = sprintf('The provided value "%s" is not a valid number or numeric string.', $number);
throw new InvalidArgumentException($message);
}
$this->validateOptions($options);
$options = array_replace($this->defaultOptions, $options);
$numberFormat = $this->getNumberFormat($options['locale']);
$currency = $this->getCurrency($currencyCode, $options['locale']);
// Use the currency defaults if the values weren't set by the caller.
if (!isset($options['minimum_fraction_digits'])) {
$options['minimum_fraction_digits'] = $currency->getFractionDigits();
}
if (!isset($options['maximum_fraction_digits'])) {
$options['maximum_fraction_digits'] = $currency->getFractionDigits();
}
$number = (string) $number;
$number = $this->formatNumber($number, $numberFormat, $options);
if ($options['currency_display'] == 'symbol') {
$number = str_replace('¤', $currency->getSymbol(), $number);
} elseif ($options['currency_display'] == 'code') {
$number = str_replace('¤', $currency->getCurrencyCode(), $number);
} else {
// No symbol should be displayed. Remove leftover whitespace.
$number = str_replace('¤', '', $number);
$number = trim($number, " \xC2\xA0");
}
return $number;
} | [
"public",
"function",
"format",
"(",
"$",
"number",
",",
"$",
"currencyCode",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"is_numeric",
"(",
"$",
"number",
")",
")",
"{",
"$",
"message",
"=",
"sprintf",
"(",
"'The provided ... | {@inheritdoc} | [
"{"
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Formatter/CurrencyFormatter.php#L93-L125 |
commerceguys/intl | src/Formatter/CurrencyFormatter.php | CurrencyFormatter.parse | public function parse($number, $currencyCode, array $options = [])
{
$this->validateOptions($options);
$options = array_replace($this->defaultOptions, $options);
$numberFormat = $this->getNumberFormat($options['locale']);
$currency = $this->getCurrency($currencyCode, $options['locale']);
$replacements = [
// Strip the currency code or symbol.
$currency->getCurrencyCode() => '',
$currency->getSymbol() => '',
];
$number = strtr($number, $replacements);
$number = $this->parseNumber($number, $numberFormat);
return $number;
} | php | public function parse($number, $currencyCode, array $options = [])
{
$this->validateOptions($options);
$options = array_replace($this->defaultOptions, $options);
$numberFormat = $this->getNumberFormat($options['locale']);
$currency = $this->getCurrency($currencyCode, $options['locale']);
$replacements = [
// Strip the currency code or symbol.
$currency->getCurrencyCode() => '',
$currency->getSymbol() => '',
];
$number = strtr($number, $replacements);
$number = $this->parseNumber($number, $numberFormat);
return $number;
} | [
"public",
"function",
"parse",
"(",
"$",
"number",
",",
"$",
"currencyCode",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"validateOptions",
"(",
"$",
"options",
")",
";",
"$",
"options",
"=",
"array_replace",
"(",
"$",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Formatter/CurrencyFormatter.php#L130-L145 |
commerceguys/intl | src/Formatter/CurrencyFormatter.php | CurrencyFormatter.getCurrency | protected function getCurrency($currencyCode, $locale)
{
if (!isset($this->currencies[$currencyCode][$locale])) {
try {
$currency = $this->currencyRepository->get($currencyCode, $locale);
} catch (UnknownCurrencyException $e) {
// The requested currency was not found. Fall back
// to a dummy object to show just the currency code.
$currency = new Currency([
'currency_code' => $currencyCode,
'name' => $currencyCode,
'numeric_code' => '000',
'locale' => $locale,
]);
}
$this->currencies[$currencyCode][$locale] = $currency;
}
return $this->currencies[$currencyCode][$locale];
} | php | protected function getCurrency($currencyCode, $locale)
{
if (!isset($this->currencies[$currencyCode][$locale])) {
try {
$currency = $this->currencyRepository->get($currencyCode, $locale);
} catch (UnknownCurrencyException $e) {
// The requested currency was not found. Fall back
// to a dummy object to show just the currency code.
$currency = new Currency([
'currency_code' => $currencyCode,
'name' => $currencyCode,
'numeric_code' => '000',
'locale' => $locale,
]);
}
$this->currencies[$currencyCode][$locale] = $currency;
}
return $this->currencies[$currencyCode][$locale];
} | [
"protected",
"function",
"getCurrency",
"(",
"$",
"currencyCode",
",",
"$",
"locale",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"currencies",
"[",
"$",
"currencyCode",
"]",
"[",
"$",
"locale",
"]",
")",
")",
"{",
"try",
"{",
"$",
"... | Gets the currency for the provided currency code and locale.
@param string $currencyCode The currency code.
@param string $locale The locale.
@return Currency | [
"Gets",
"the",
"currency",
"for",
"the",
"provided",
"currency",
"code",
"and",
"locale",
"."
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Formatter/CurrencyFormatter.php#L171-L190 |
commerceguys/intl | src/Language/LanguageRepository.php | LanguageRepository.get | public function get($languageCode, $locale = null)
{
$locale = $locale ?: $this->defaultLocale;
$locale = Locale::resolve($this->availableLocales, $locale, $this->fallbackLocale);
$definitions = $this->loadDefinitions($locale);
$languageCode = Locale::canonicalize($languageCode);
if (!isset($definitions[$languageCode])) {
throw new UnknownLanguageException($languageCode);
}
$language = new Language([
'language_code' => $languageCode,
'name' => $definitions[$languageCode],
'locale' => $locale,
]);
return $language;
} | php | public function get($languageCode, $locale = null)
{
$locale = $locale ?: $this->defaultLocale;
$locale = Locale::resolve($this->availableLocales, $locale, $this->fallbackLocale);
$definitions = $this->loadDefinitions($locale);
$languageCode = Locale::canonicalize($languageCode);
if (!isset($definitions[$languageCode])) {
throw new UnknownLanguageException($languageCode);
}
$language = new Language([
'language_code' => $languageCode,
'name' => $definitions[$languageCode],
'locale' => $locale,
]);
return $language;
} | [
"public",
"function",
"get",
"(",
"$",
"languageCode",
",",
"$",
"locale",
"=",
"null",
")",
"{",
"$",
"locale",
"=",
"$",
"locale",
"?",
":",
"$",
"this",
"->",
"defaultLocale",
";",
"$",
"locale",
"=",
"Locale",
"::",
"resolve",
"(",
"$",
"this",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Language/LanguageRepository.php#L93-L109 |
commerceguys/intl | src/Language/LanguageRepository.php | LanguageRepository.getAll | public function getAll($locale = null)
{
$locale = $locale ?: $this->defaultLocale;
$locale = Locale::resolve($this->availableLocales, $locale, $this->fallbackLocale);
$definitions = $this->loadDefinitions($locale);
$languages = [];
foreach ($definitions as $languageCode => $languageName) {
$languages[$languageCode] = new Language([
'language_code' => $languageCode,
'name' => $languageName,
'locale' => $locale,
]);
}
return $languages;
} | php | public function getAll($locale = null)
{
$locale = $locale ?: $this->defaultLocale;
$locale = Locale::resolve($this->availableLocales, $locale, $this->fallbackLocale);
$definitions = $this->loadDefinitions($locale);
$languages = [];
foreach ($definitions as $languageCode => $languageName) {
$languages[$languageCode] = new Language([
'language_code' => $languageCode,
'name' => $languageName,
'locale' => $locale,
]);
}
return $languages;
} | [
"public",
"function",
"getAll",
"(",
"$",
"locale",
"=",
"null",
")",
"{",
"$",
"locale",
"=",
"$",
"locale",
"?",
":",
"$",
"this",
"->",
"defaultLocale",
";",
"$",
"locale",
"=",
"Locale",
"::",
"resolve",
"(",
"$",
"this",
"->",
"availableLocales",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Language/LanguageRepository.php#L114-L129 |
commerceguys/intl | src/Language/LanguageRepository.php | LanguageRepository.getList | public function getList($locale = null)
{
$locale = $locale ?: $this->defaultLocale;
$locale = Locale::resolve($this->availableLocales, $locale, $this->fallbackLocale);
$definitions = $this->loadDefinitions($locale);
$list = [];
foreach ($definitions as $languageCode => $languageName) {
$list[$languageCode] = $languageName;
}
return $list;
} | php | public function getList($locale = null)
{
$locale = $locale ?: $this->defaultLocale;
$locale = Locale::resolve($this->availableLocales, $locale, $this->fallbackLocale);
$definitions = $this->loadDefinitions($locale);
$list = [];
foreach ($definitions as $languageCode => $languageName) {
$list[$languageCode] = $languageName;
}
return $list;
} | [
"public",
"function",
"getList",
"(",
"$",
"locale",
"=",
"null",
")",
"{",
"$",
"locale",
"=",
"$",
"locale",
"?",
":",
"$",
"this",
"->",
"defaultLocale",
";",
"$",
"locale",
"=",
"Locale",
"::",
"resolve",
"(",
"$",
"this",
"->",
"availableLocales",... | {@inheritdoc} | [
"{"
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Language/LanguageRepository.php#L134-L145 |
commerceguys/intl | src/Formatter/FormatterTrait.php | FormatterTrait.formatNumber | protected function formatNumber($number, NumberFormat $numberFormat, array $options = [])
{
$parsedPattern = $this->getParsedPattern($numberFormat, $options['style']);
// Start by rounding the number, if rounding is enabled.
if (is_int($options['rounding_mode'])) {
$number = Calculator::round($number, $options['maximum_fraction_digits'], $options['rounding_mode']);
}
$negative = (Calculator::compare('0', $number, 12) == 1);
// Ensure that the value is positive and has the right number of digits.
$signMultiplier = $negative ? '-1' : '1';
$number = bcdiv($number, $signMultiplier, $options['maximum_fraction_digits']);
// Split the number into major and minor digits.
$numberParts = explode('.', $number);
$majorDigits = $numberParts[0];
// Account for maximumFractionDigits = 0, where the number won't
// have a decimal point, and $numberParts[1] won't be set.
$minorDigits = isset($numberParts[1]) ? $numberParts[1] : '';
if ($options['use_grouping'] && $parsedPattern->isGroupingUsed()) {
// Reverse the major digits, since they are grouped from the right.
$majorDigits = array_reverse(str_split($majorDigits));
// Group the major digits.
$groups = [];
$groups[] = array_splice($majorDigits, 0, $parsedPattern->getPrimaryGroupSize());
while (!empty($majorDigits)) {
$groups[] = array_splice($majorDigits, 0, $parsedPattern->getSecondaryGroupSize());
}
// Reverse the groups and the digits inside of them.
$groups = array_reverse($groups);
foreach ($groups as &$group) {
$group = implode(array_reverse($group));
}
// Reconstruct the major digits.
$majorDigits = implode(',', $groups);
}
if ($options['minimum_fraction_digits'] < $options['maximum_fraction_digits']) {
// Strip any trailing zeroes.
$minorDigits = rtrim($minorDigits, '0');
if (strlen($minorDigits) < $options['minimum_fraction_digits']) {
// Now there are too few digits, re-add trailing zeroes
// until the desired length is reached.
$neededZeroes = $options['minimum_fraction_digits'] - strlen($minorDigits);
$minorDigits .= str_repeat('0', $neededZeroes);
}
}
// Assemble the final number and insert it into the pattern.
$number = strlen($minorDigits) ? $majorDigits . '.' . $minorDigits : $majorDigits;
$pattern = $negative ? $parsedPattern->getNegativePattern() : $parsedPattern->getPositivePattern();
$number = preg_replace('/#(?:[\.,]#+)*0(?:[,\.][0#]+)*/', $number, $pattern);
$number = $this->localizeNumber($number, $numberFormat);
return $number;
} | php | protected function formatNumber($number, NumberFormat $numberFormat, array $options = [])
{
$parsedPattern = $this->getParsedPattern($numberFormat, $options['style']);
// Start by rounding the number, if rounding is enabled.
if (is_int($options['rounding_mode'])) {
$number = Calculator::round($number, $options['maximum_fraction_digits'], $options['rounding_mode']);
}
$negative = (Calculator::compare('0', $number, 12) == 1);
// Ensure that the value is positive and has the right number of digits.
$signMultiplier = $negative ? '-1' : '1';
$number = bcdiv($number, $signMultiplier, $options['maximum_fraction_digits']);
// Split the number into major and minor digits.
$numberParts = explode('.', $number);
$majorDigits = $numberParts[0];
// Account for maximumFractionDigits = 0, where the number won't
// have a decimal point, and $numberParts[1] won't be set.
$minorDigits = isset($numberParts[1]) ? $numberParts[1] : '';
if ($options['use_grouping'] && $parsedPattern->isGroupingUsed()) {
// Reverse the major digits, since they are grouped from the right.
$majorDigits = array_reverse(str_split($majorDigits));
// Group the major digits.
$groups = [];
$groups[] = array_splice($majorDigits, 0, $parsedPattern->getPrimaryGroupSize());
while (!empty($majorDigits)) {
$groups[] = array_splice($majorDigits, 0, $parsedPattern->getSecondaryGroupSize());
}
// Reverse the groups and the digits inside of them.
$groups = array_reverse($groups);
foreach ($groups as &$group) {
$group = implode(array_reverse($group));
}
// Reconstruct the major digits.
$majorDigits = implode(',', $groups);
}
if ($options['minimum_fraction_digits'] < $options['maximum_fraction_digits']) {
// Strip any trailing zeroes.
$minorDigits = rtrim($minorDigits, '0');
if (strlen($minorDigits) < $options['minimum_fraction_digits']) {
// Now there are too few digits, re-add trailing zeroes
// until the desired length is reached.
$neededZeroes = $options['minimum_fraction_digits'] - strlen($minorDigits);
$minorDigits .= str_repeat('0', $neededZeroes);
}
}
// Assemble the final number and insert it into the pattern.
$number = strlen($minorDigits) ? $majorDigits . '.' . $minorDigits : $majorDigits;
$pattern = $negative ? $parsedPattern->getNegativePattern() : $parsedPattern->getPositivePattern();
$number = preg_replace('/#(?:[\.,]#+)*0(?:[,\.][0#]+)*/', $number, $pattern);
$number = $this->localizeNumber($number, $numberFormat);
return $number;
} | [
"protected",
"function",
"formatNumber",
"(",
"$",
"number",
",",
"NumberFormat",
"$",
"numberFormat",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"parsedPattern",
"=",
"$",
"this",
"->",
"getParsedPattern",
"(",
"$",
"numberFormat",
",",
"... | Formats the number according to the number format.
@param string $number The number.
@param NumberFormat $numberFormat The number format.
@return string The formatted number. | [
"Formats",
"the",
"number",
"according",
"to",
"the",
"number",
"format",
"."
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Formatter/FormatterTrait.php#L50-L104 |
commerceguys/intl | src/Formatter/FormatterTrait.php | FormatterTrait.localizeNumber | protected function localizeNumber($number, NumberFormat $numberFormat)
{
// Localize digits.
$numberingSystem = $numberFormat->getNumberingSystem();
if (isset($this->digits[$numberingSystem])) {
$number = strtr($number, $this->digits[$numberingSystem]);
}
// Localize symbols.
$replacements = [
'.' => $numberFormat->getDecimalSeparator(),
',' => $numberFormat->getGroupingSeparator(),
'+' => $numberFormat->getPlusSign(),
'-' => $numberFormat->getMinusSign(),
'%' => $numberFormat->getPercentSign(),
];
$number = strtr($number, $replacements);
return $number;
} | php | protected function localizeNumber($number, NumberFormat $numberFormat)
{
// Localize digits.
$numberingSystem = $numberFormat->getNumberingSystem();
if (isset($this->digits[$numberingSystem])) {
$number = strtr($number, $this->digits[$numberingSystem]);
}
// Localize symbols.
$replacements = [
'.' => $numberFormat->getDecimalSeparator(),
',' => $numberFormat->getGroupingSeparator(),
'+' => $numberFormat->getPlusSign(),
'-' => $numberFormat->getMinusSign(),
'%' => $numberFormat->getPercentSign(),
];
$number = strtr($number, $replacements);
return $number;
} | [
"protected",
"function",
"localizeNumber",
"(",
"$",
"number",
",",
"NumberFormat",
"$",
"numberFormat",
")",
"{",
"// Localize digits.",
"$",
"numberingSystem",
"=",
"$",
"numberFormat",
"->",
"getNumberingSystem",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
... | Localizes the number according to the number format.
Both the digits and the symbols are replaced
with their localized equivalents.
@param string $number The number.
@param NumberFormat $numberFormat The number format.
@return string The localized number.
@see http://cldr.unicode.org/translation/number-symbols | [
"Localizes",
"the",
"number",
"according",
"to",
"the",
"number",
"format",
"."
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Formatter/FormatterTrait.php#L119-L137 |
commerceguys/intl | src/Formatter/FormatterTrait.php | FormatterTrait.parseNumber | protected function parseNumber($number, NumberFormat $numberFormat)
{
$replacements = [
$numberFormat->getGroupingSeparator() => '',
// Convert the localized symbols back to their original form.
$numberFormat->getDecimalSeparator() => '.',
$numberFormat->getPlusSign() => '+',
$numberFormat->getMinusSign() => '-',
$numberFormat->getPercentSign() => '%',
// Strip whitespace (spaces and non-breaking spaces).
' ' => '',
chr(0xC2) . chr(0xA0) => '',
];
$numberingSystem = $numberFormat->getNumberingSystem();
if (isset($this->digits[$numberingSystem])) {
// Convert the localized digits back to latin.
$replacements += array_flip($this->digits[$numberingSystem]);
}
$number = strtr($number, $replacements);
// Convert the accounting format for negative numbers.
if (substr($number, 0, 1) == '(' && substr($number, -1, 1) == ')') {
$number = '-' . str_replace(['(', ')'], '', $number);
}
// Convert percentages back to their decimal form.
if (strpos($number, '%') !== false) {
$number = str_replace('%', '', $number);
$number = Calculator::divide($number, '100');
}
return is_numeric($number) ? $number : false;
} | php | protected function parseNumber($number, NumberFormat $numberFormat)
{
$replacements = [
$numberFormat->getGroupingSeparator() => '',
// Convert the localized symbols back to their original form.
$numberFormat->getDecimalSeparator() => '.',
$numberFormat->getPlusSign() => '+',
$numberFormat->getMinusSign() => '-',
$numberFormat->getPercentSign() => '%',
// Strip whitespace (spaces and non-breaking spaces).
' ' => '',
chr(0xC2) . chr(0xA0) => '',
];
$numberingSystem = $numberFormat->getNumberingSystem();
if (isset($this->digits[$numberingSystem])) {
// Convert the localized digits back to latin.
$replacements += array_flip($this->digits[$numberingSystem]);
}
$number = strtr($number, $replacements);
// Convert the accounting format for negative numbers.
if (substr($number, 0, 1) == '(' && substr($number, -1, 1) == ')') {
$number = '-' . str_replace(['(', ')'], '', $number);
}
// Convert percentages back to their decimal form.
if (strpos($number, '%') !== false) {
$number = str_replace('%', '', $number);
$number = Calculator::divide($number, '100');
}
return is_numeric($number) ? $number : false;
} | [
"protected",
"function",
"parseNumber",
"(",
"$",
"number",
",",
"NumberFormat",
"$",
"numberFormat",
")",
"{",
"$",
"replacements",
"=",
"[",
"$",
"numberFormat",
"->",
"getGroupingSeparator",
"(",
")",
"=>",
"''",
",",
"// Convert the localized symbols back to the... | Parses the number according to the number format.
Both the digits and the symbols are replaced
with their non-localized equivalents.
@param string $number The number.
@param NumberFormat $numberFormat The number format.
@return string The localized number. | [
"Parses",
"the",
"number",
"according",
"to",
"the",
"number",
"format",
"."
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Formatter/FormatterTrait.php#L150-L182 |
commerceguys/intl | src/Formatter/FormatterTrait.php | FormatterTrait.getParsedPattern | protected function getParsedPattern(NumberFormat $numberFormat, $style)
{
$locale = $numberFormat->getLocale();
if (!isset($this->parsedPatterns[$locale][$style])) {
$availablePatterns = $this->getAvailablePatterns($numberFormat);
if (!isset($availablePatterns[$style])) {
throw new InvalidArgumentException(sprintf('Unrecognized style "%s".', $style));
}
$this->parsedPatterns[$locale][$style] = new ParsedPattern($availablePatterns[$style]);
}
return $this->parsedPatterns[$locale][$style];
} | php | protected function getParsedPattern(NumberFormat $numberFormat, $style)
{
$locale = $numberFormat->getLocale();
if (!isset($this->parsedPatterns[$locale][$style])) {
$availablePatterns = $this->getAvailablePatterns($numberFormat);
if (!isset($availablePatterns[$style])) {
throw new InvalidArgumentException(sprintf('Unrecognized style "%s".', $style));
}
$this->parsedPatterns[$locale][$style] = new ParsedPattern($availablePatterns[$style]);
}
return $this->parsedPatterns[$locale][$style];
} | [
"protected",
"function",
"getParsedPattern",
"(",
"NumberFormat",
"$",
"numberFormat",
",",
"$",
"style",
")",
"{",
"$",
"locale",
"=",
"$",
"numberFormat",
"->",
"getLocale",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"parsedPatterns"... | Gets the pattern for the provided number format.
@param NumberFormat $numberFormat The number format.
@param string $style The formatter style.
@return ParsedPattern | [
"Gets",
"the",
"pattern",
"for",
"the",
"provided",
"number",
"format",
"."
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Formatter/FormatterTrait.php#L192-L205 |
commerceguys/intl | src/Calculator.php | Calculator.add | public static function add($first_number, $second_number, $scale = 6)
{
self::assertNumberFormat($first_number);
self::assertNumberFormat($second_number);
$result = bcadd($first_number, $second_number, $scale);
return self::trim($result);
} | php | public static function add($first_number, $second_number, $scale = 6)
{
self::assertNumberFormat($first_number);
self::assertNumberFormat($second_number);
$result = bcadd($first_number, $second_number, $scale);
return self::trim($result);
} | [
"public",
"static",
"function",
"add",
"(",
"$",
"first_number",
",",
"$",
"second_number",
",",
"$",
"scale",
"=",
"6",
")",
"{",
"self",
"::",
"assertNumberFormat",
"(",
"$",
"first_number",
")",
";",
"self",
"::",
"assertNumberFormat",
"(",
"$",
"second... | Adds the second number to the first number.
@param string $first_number The first number.
@param string $second_number The second number.
@param int $scale The maximum number of digits after the
decimal place. Any digit after $scale will
be truncated.
@return string The result. | [
"Adds",
"the",
"second",
"number",
"to",
"the",
"first",
"number",
"."
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Calculator.php#L27-L34 |
commerceguys/intl | src/Calculator.php | Calculator.subtract | public static function subtract($first_number, $second_number, $scale = 6)
{
self::assertNumberFormat($first_number);
self::assertNumberFormat($second_number);
$result = bcsub($first_number, $second_number, $scale);
return self::trim($result);
} | php | public static function subtract($first_number, $second_number, $scale = 6)
{
self::assertNumberFormat($first_number);
self::assertNumberFormat($second_number);
$result = bcsub($first_number, $second_number, $scale);
return self::trim($result);
} | [
"public",
"static",
"function",
"subtract",
"(",
"$",
"first_number",
",",
"$",
"second_number",
",",
"$",
"scale",
"=",
"6",
")",
"{",
"self",
"::",
"assertNumberFormat",
"(",
"$",
"first_number",
")",
";",
"self",
"::",
"assertNumberFormat",
"(",
"$",
"s... | Subtracts the second number from the first number.
@param string $first_number The first number.
@param string $second_number The second number.
@param int $scale The maximum number of digits after the
decimal place. Any digit after $scale will
be truncated.
@return string The result. | [
"Subtracts",
"the",
"second",
"number",
"from",
"the",
"first",
"number",
"."
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Calculator.php#L47-L54 |
commerceguys/intl | src/Calculator.php | Calculator.multiply | public static function multiply($first_number, $second_number, $scale = 6)
{
self::assertNumberFormat($first_number);
self::assertNumberFormat($second_number);
$result = bcmul($first_number, $second_number, $scale);
return self::trim($result);
} | php | public static function multiply($first_number, $second_number, $scale = 6)
{
self::assertNumberFormat($first_number);
self::assertNumberFormat($second_number);
$result = bcmul($first_number, $second_number, $scale);
return self::trim($result);
} | [
"public",
"static",
"function",
"multiply",
"(",
"$",
"first_number",
",",
"$",
"second_number",
",",
"$",
"scale",
"=",
"6",
")",
"{",
"self",
"::",
"assertNumberFormat",
"(",
"$",
"first_number",
")",
";",
"self",
"::",
"assertNumberFormat",
"(",
"$",
"s... | Multiplies the first number by the second number.
@param string $first_number The first number.
@param string $second_number The second number.
@param int $scale The maximum number of digits after the
decimal place. Any digit after $scale will
be truncated.
@return string The result. | [
"Multiplies",
"the",
"first",
"number",
"by",
"the",
"second",
"number",
"."
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Calculator.php#L67-L74 |
commerceguys/intl | src/Calculator.php | Calculator.divide | public static function divide($first_number, $second_number, $scale = 6)
{
self::assertNumberFormat($first_number);
self::assertNumberFormat($second_number);
$result = bcdiv($first_number, $second_number, $scale);
return self::trim($result);
} | php | public static function divide($first_number, $second_number, $scale = 6)
{
self::assertNumberFormat($first_number);
self::assertNumberFormat($second_number);
$result = bcdiv($first_number, $second_number, $scale);
return self::trim($result);
} | [
"public",
"static",
"function",
"divide",
"(",
"$",
"first_number",
",",
"$",
"second_number",
",",
"$",
"scale",
"=",
"6",
")",
"{",
"self",
"::",
"assertNumberFormat",
"(",
"$",
"first_number",
")",
";",
"self",
"::",
"assertNumberFormat",
"(",
"$",
"sec... | Divides the first number by the second number.
@param string $first_number The first number.
@param string $second_number The second number.
@param int $scale The maximum number of digits after the
decimal place. Any digit after $scale will
be truncated.
@return string The result. | [
"Divides",
"the",
"first",
"number",
"by",
"the",
"second",
"number",
"."
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Calculator.php#L87-L94 |
commerceguys/intl | src/Calculator.php | Calculator.ceil | public static function ceil($number)
{
if (self::compare($number, 0) == 1) {
$result = bcadd($number, '1', 0);
} else {
$result = bcadd($number, '0', 0);
}
return $result;
} | php | public static function ceil($number)
{
if (self::compare($number, 0) == 1) {
$result = bcadd($number, '1', 0);
} else {
$result = bcadd($number, '0', 0);
}
return $result;
} | [
"public",
"static",
"function",
"ceil",
"(",
"$",
"number",
")",
"{",
"if",
"(",
"self",
"::",
"compare",
"(",
"$",
"number",
",",
"0",
")",
"==",
"1",
")",
"{",
"$",
"result",
"=",
"bcadd",
"(",
"$",
"number",
",",
"'1'",
",",
"0",
")",
";",
... | Calculates the next highest whole value of a number.
@param string $number The number.
@return string The result. | [
"Calculates",
"the",
"next",
"highest",
"whole",
"value",
"of",
"a",
"number",
"."
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Calculator.php#L103-L112 |
commerceguys/intl | src/Calculator.php | Calculator.floor | public static function floor($number)
{
if (self::compare($number, 0) == 1) {
$result = bcadd($number, '0', 0);
} else {
$result = bcadd($number, '-1', 0);
}
return $result;
} | php | public static function floor($number)
{
if (self::compare($number, 0) == 1) {
$result = bcadd($number, '0', 0);
} else {
$result = bcadd($number, '-1', 0);
}
return $result;
} | [
"public",
"static",
"function",
"floor",
"(",
"$",
"number",
")",
"{",
"if",
"(",
"self",
"::",
"compare",
"(",
"$",
"number",
",",
"0",
")",
"==",
"1",
")",
"{",
"$",
"result",
"=",
"bcadd",
"(",
"$",
"number",
",",
"'0'",
",",
"0",
")",
";",
... | Calculates the next lowest whole value of a number.
@param string $number The number.
@return string The result. | [
"Calculates",
"the",
"next",
"lowest",
"whole",
"value",
"of",
"a",
"number",
"."
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Calculator.php#L121-L130 |
commerceguys/intl | src/Calculator.php | Calculator.round | public static function round($number, $precision = 0, $mode = PHP_ROUND_HALF_UP)
{
self::assertNumberFormat($number);
if (!is_numeric($precision) || $precision < 0) {
throw new \InvalidArgumentException('The provided precision should be a positive number');
}
// Round the number in both directions (up/down) before choosing one.
$rounding_increment = bcdiv('1', pow(10, $precision), $precision);
if (self::compare($number, '0') == 1) {
$rounded_up = bcadd($number, $rounding_increment, $precision);
} else {
$rounded_up = bcsub($number, $rounding_increment, $precision);
}
$rounded_down = bcsub($number, 0, $precision);
// The rounding direction is based on the first decimal after $precision.
$number_parts = explode('.', $number);
$decimals = !empty($number_parts[1]) ? $number_parts[1] : '0';
$relevant_decimal = isset($decimals[$precision]) ? $decimals[$precision] : 0;
if ($relevant_decimal < 5) {
$number = $rounded_down;
} elseif ($relevant_decimal == 5) {
if ($mode == PHP_ROUND_HALF_UP) {
$number = $rounded_up;
} elseif ($mode == PHP_ROUND_HALF_DOWN) {
$number = $rounded_down;
} elseif ($mode == PHP_ROUND_HALF_EVEN) {
$integer = bcmul($rounded_up, pow(10, $precision), 0);
$number = bcmod($integer, '2') == 0 ? $rounded_up : $rounded_down;
} elseif ($mode == PHP_ROUND_HALF_ODD) {
$integer = bcmul($rounded_up, pow(10, $precision), 0);
$number = bcmod($integer, '2') != 0 ? $rounded_up : $rounded_down;
}
} elseif ($relevant_decimal > 5) {
$number = $rounded_up;
}
return $number;
} | php | public static function round($number, $precision = 0, $mode = PHP_ROUND_HALF_UP)
{
self::assertNumberFormat($number);
if (!is_numeric($precision) || $precision < 0) {
throw new \InvalidArgumentException('The provided precision should be a positive number');
}
// Round the number in both directions (up/down) before choosing one.
$rounding_increment = bcdiv('1', pow(10, $precision), $precision);
if (self::compare($number, '0') == 1) {
$rounded_up = bcadd($number, $rounding_increment, $precision);
} else {
$rounded_up = bcsub($number, $rounding_increment, $precision);
}
$rounded_down = bcsub($number, 0, $precision);
// The rounding direction is based on the first decimal after $precision.
$number_parts = explode('.', $number);
$decimals = !empty($number_parts[1]) ? $number_parts[1] : '0';
$relevant_decimal = isset($decimals[$precision]) ? $decimals[$precision] : 0;
if ($relevant_decimal < 5) {
$number = $rounded_down;
} elseif ($relevant_decimal == 5) {
if ($mode == PHP_ROUND_HALF_UP) {
$number = $rounded_up;
} elseif ($mode == PHP_ROUND_HALF_DOWN) {
$number = $rounded_down;
} elseif ($mode == PHP_ROUND_HALF_EVEN) {
$integer = bcmul($rounded_up, pow(10, $precision), 0);
$number = bcmod($integer, '2') == 0 ? $rounded_up : $rounded_down;
} elseif ($mode == PHP_ROUND_HALF_ODD) {
$integer = bcmul($rounded_up, pow(10, $precision), 0);
$number = bcmod($integer, '2') != 0 ? $rounded_up : $rounded_down;
}
} elseif ($relevant_decimal > 5) {
$number = $rounded_up;
}
return $number;
} | [
"public",
"static",
"function",
"round",
"(",
"$",
"number",
",",
"$",
"precision",
"=",
"0",
",",
"$",
"mode",
"=",
"PHP_ROUND_HALF_UP",
")",
"{",
"self",
"::",
"assertNumberFormat",
"(",
"$",
"number",
")",
";",
"if",
"(",
"!",
"is_numeric",
"(",
"$"... | Rounds the given number.
Replicates PHP's support for rounding to the nearest even/odd number
even if that number is decimal ($precision > 0).
@param string $number The number.
@param int $precision The number of decimals to round to.
@param int $mode The rounding mode. One of the following constants:
PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN,
PHP_ROUND_HALF_EVEN, PHP_ROUND_HALF_ODD.
@return string The rounded number.
@throws \InvalidArgumentException | [
"Rounds",
"the",
"given",
"number",
"."
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Calculator.php#L148-L186 |
commerceguys/intl | src/Calculator.php | Calculator.compare | public static function compare($first_number, $second_number, $scale = 6)
{
self::assertNumberFormat($first_number);
self::assertNumberFormat($second_number);
return bccomp($first_number, $second_number, $scale);
} | php | public static function compare($first_number, $second_number, $scale = 6)
{
self::assertNumberFormat($first_number);
self::assertNumberFormat($second_number);
return bccomp($first_number, $second_number, $scale);
} | [
"public",
"static",
"function",
"compare",
"(",
"$",
"first_number",
",",
"$",
"second_number",
",",
"$",
"scale",
"=",
"6",
")",
"{",
"self",
"::",
"assertNumberFormat",
"(",
"$",
"first_number",
")",
";",
"self",
"::",
"assertNumberFormat",
"(",
"$",
"se... | Compares the first number to the second number.
@param string $first_number The first number.
@param string $second_number The second number.
@param int $scale The maximum number of digits after the
decimal place. Any digit after $scale will
be truncated.
@return int 0 if both numbers are equal, 1 if the first one is greater,
-1 otherwise. | [
"Compares",
"the",
"first",
"number",
"to",
"the",
"second",
"number",
"."
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Calculator.php#L200-L206 |
commerceguys/intl | src/Calculator.php | Calculator.trim | public static function trim($number)
{
if (strpos($number, '.') != false) {
// The number is decimal, strip trailing zeroes.
// If no digits remain after the decimal point, strip it as well.
$number = rtrim($number, '0');
$number = rtrim($number, '.');
}
return $number;
} | php | public static function trim($number)
{
if (strpos($number, '.') != false) {
// The number is decimal, strip trailing zeroes.
// If no digits remain after the decimal point, strip it as well.
$number = rtrim($number, '0');
$number = rtrim($number, '.');
}
return $number;
} | [
"public",
"static",
"function",
"trim",
"(",
"$",
"number",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"number",
",",
"'.'",
")",
"!=",
"false",
")",
"{",
"// The number is decimal, strip trailing zeroes.",
"// If no digits remain after the decimal point, strip it as well... | Trims the given number.
By default bcmath returns numbers with the number of digits according
to $scale. This means that bcadd('2', '2', 6) will return '4.00000'.
Trimming the number removes the excess zeroes.
@param string $number The number to trim.
@return string The trimmed number. | [
"Trims",
"the",
"given",
"number",
"."
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Calculator.php#L219-L229 |
commerceguys/intl | src/Calculator.php | Calculator.assertNumberFormat | public static function assertNumberFormat($number)
{
if (is_float($number)) {
throw new \InvalidArgumentException(sprintf('The provided value "%s" must be a string, not a float.', $number));
}
if (!is_numeric($number)) {
throw new \InvalidArgumentException(sprintf('The provided value "%s" is not a numeric value.', $number));
}
} | php | public static function assertNumberFormat($number)
{
if (is_float($number)) {
throw new \InvalidArgumentException(sprintf('The provided value "%s" must be a string, not a float.', $number));
}
if (!is_numeric($number)) {
throw new \InvalidArgumentException(sprintf('The provided value "%s" is not a numeric value.', $number));
}
} | [
"public",
"static",
"function",
"assertNumberFormat",
"(",
"$",
"number",
")",
"{",
"if",
"(",
"is_float",
"(",
"$",
"number",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'The provided value \"%s\" must be a string, not a f... | Assert that the given number is a numeric string value.
@param string $number The number to check.
@throws \InvalidArgumentException | [
"Assert",
"that",
"the",
"given",
"number",
"is",
"a",
"numeric",
"string",
"value",
"."
] | train | https://github.com/commerceguys/intl/blob/0fc176165f45d9f3dd9af50a05293c3fa99e4691/src/Calculator.php#L238-L246 |
willdurand/BazingaHateoasBundle | DependencyInjection/Configuration.php | Configuration.getConfigTreeBuilder | public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('bazinga_hateoas');
if (\method_exists($treeBuilder, 'getRootNode')) {
$rootNode = $treeBuilder->getRootNode();
} else {
// BC layer for symfony/config 4.1 and older
$rootNode = $treeBuilder->root('bazinga_hateoas');
}
$rootNode
->children()
->arrayNode('metadata')
->addDefaultsIfNotSet()
->children()
->scalarNode('cache')->defaultValue('file')->end()
->arrayNode('file_cache')
->addDefaultsIfNotSet()
->children()
->scalarNode('dir')->defaultValue('%kernel.cache_dir%/hateoas')->end()
->end()
->end()
->end()
->end()
->arrayNode('serializer')
->addDefaultsIfNotSet()
->children()
->scalarNode('json')->defaultValue('hateoas.serializer.json_hal')->end()
->scalarNode('xml')->defaultValue('hateoas.serializer.xml')->end()
->end()
->end()
->arrayNode('twig_extension')
->addDefaultsIfNotSet()
->canBeDisabled()
->end();
return $treeBuilder;
} | php | public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('bazinga_hateoas');
if (\method_exists($treeBuilder, 'getRootNode')) {
$rootNode = $treeBuilder->getRootNode();
} else {
// BC layer for symfony/config 4.1 and older
$rootNode = $treeBuilder->root('bazinga_hateoas');
}
$rootNode
->children()
->arrayNode('metadata')
->addDefaultsIfNotSet()
->children()
->scalarNode('cache')->defaultValue('file')->end()
->arrayNode('file_cache')
->addDefaultsIfNotSet()
->children()
->scalarNode('dir')->defaultValue('%kernel.cache_dir%/hateoas')->end()
->end()
->end()
->end()
->end()
->arrayNode('serializer')
->addDefaultsIfNotSet()
->children()
->scalarNode('json')->defaultValue('hateoas.serializer.json_hal')->end()
->scalarNode('xml')->defaultValue('hateoas.serializer.xml')->end()
->end()
->end()
->arrayNode('twig_extension')
->addDefaultsIfNotSet()
->canBeDisabled()
->end();
return $treeBuilder;
} | [
"public",
"function",
"getConfigTreeBuilder",
"(",
")",
":",
"TreeBuilder",
"{",
"$",
"treeBuilder",
"=",
"new",
"TreeBuilder",
"(",
"'bazinga_hateoas'",
")",
";",
"if",
"(",
"\\",
"method_exists",
"(",
"$",
"treeBuilder",
",",
"'getRootNode'",
")",
")",
"{",
... | Generates the configuration tree builder.
@return TreeBuilder The tree builder | [
"Generates",
"the",
"configuration",
"tree",
"builder",
"."
] | train | https://github.com/willdurand/BazingaHateoasBundle/blob/c2dccbdad5f3f88d405fdc1729705cba904a5888/DependencyInjection/Configuration.php#L23-L60 |
willdurand/BazingaHateoasBundle | DependencyInjection/Compiler/CacheWarmupPass.php | CacheWarmupPass.process | public function process(ContainerBuilder $container)
{
try {
$warmupService = clone $container->findDefinition('jms_serializer.cache.cache_warmer');
$warmupService->setArgument(1, $container->findDefinition('hateoas.configuration.metadata_factory'));
$container->setDefinition('hateoas.configuration.metadata.cache.cache_warmer', $warmupService);
} catch (ServiceNotFoundException $exception) {
}
} | php | public function process(ContainerBuilder $container)
{
try {
$warmupService = clone $container->findDefinition('jms_serializer.cache.cache_warmer');
$warmupService->setArgument(1, $container->findDefinition('hateoas.configuration.metadata_factory'));
$container->setDefinition('hateoas.configuration.metadata.cache.cache_warmer', $warmupService);
} catch (ServiceNotFoundException $exception) {
}
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"try",
"{",
"$",
"warmupService",
"=",
"clone",
"$",
"container",
"->",
"findDefinition",
"(",
"'jms_serializer.cache.cache_warmer'",
")",
";",
"$",
"warmupService",
"->",
"setAr... | {@inheritdoc} | [
"{"
] | train | https://github.com/willdurand/BazingaHateoasBundle/blob/c2dccbdad5f3f88d405fdc1729705cba904a5888/DependencyInjection/Compiler/CacheWarmupPass.php#L22-L31 |
willdurand/BazingaHateoasBundle | DependencyInjection/Compiler/RelationProviderPass.php | RelationProviderPass.process | public function process(ContainerBuilder $container)
{
$registryDefinition = $container->findDefinition('hateoas.configuration.provider');
$relationProviderDefinitions = [];
foreach (array_keys($container->findTaggedServiceIds('hateoas.relation_provider')) as $id) {
$definition = $container->getDefinition($id);
$this->assertProvider($container, $definition);
$relationProviderDefinitions[] = $definition;
}
$registryDefinition->replaceArgument(0, $relationProviderDefinitions);
} | php | public function process(ContainerBuilder $container)
{
$registryDefinition = $container->findDefinition('hateoas.configuration.provider');
$relationProviderDefinitions = [];
foreach (array_keys($container->findTaggedServiceIds('hateoas.relation_provider')) as $id) {
$definition = $container->getDefinition($id);
$this->assertProvider($container, $definition);
$relationProviderDefinitions[] = $definition;
}
$registryDefinition->replaceArgument(0, $relationProviderDefinitions);
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"registryDefinition",
"=",
"$",
"container",
"->",
"findDefinition",
"(",
"'hateoas.configuration.provider'",
")",
";",
"$",
"relationProviderDefinitions",
"=",
"[",
"]",
";",... | {@inheritdoc} | [
"{"
] | train | https://github.com/willdurand/BazingaHateoasBundle/blob/c2dccbdad5f3f88d405fdc1729705cba904a5888/DependencyInjection/Compiler/RelationProviderPass.php#L24-L36 |
willdurand/BazingaHateoasBundle | DependencyInjection/Compiler/UrlGeneratorPass.php | UrlGeneratorPass.process | public function process(ContainerBuilder $container)
{
$registryDefinition = $container->getDefinition('hateoas.generator.registry');
foreach ($container->findTaggedServiceIds('hateoas.url_generator') as $id => $attributes) {
$name = !empty($attributes[0]['alias']) ? $attributes[0]['alias'] : $id;
if ($this->isSymfonyUrlGenerator($container, $container->getDefinition($id))) {
$definition = new Definition(
'Hateoas\UrlGenerator\SymfonyUrlGenerator',
[new Reference($id)]
);
$definition->setPublic(false);
$id = 'hateoas.generator.user.' . $name;
$container->setDefinition($id, $definition);
}
$registryDefinition->addMethodCall(
'set',
[$name, new Reference($id)]
);
}
} | php | public function process(ContainerBuilder $container)
{
$registryDefinition = $container->getDefinition('hateoas.generator.registry');
foreach ($container->findTaggedServiceIds('hateoas.url_generator') as $id => $attributes) {
$name = !empty($attributes[0]['alias']) ? $attributes[0]['alias'] : $id;
if ($this->isSymfonyUrlGenerator($container, $container->getDefinition($id))) {
$definition = new Definition(
'Hateoas\UrlGenerator\SymfonyUrlGenerator',
[new Reference($id)]
);
$definition->setPublic(false);
$id = 'hateoas.generator.user.' . $name;
$container->setDefinition($id, $definition);
}
$registryDefinition->addMethodCall(
'set',
[$name, new Reference($id)]
);
}
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"registryDefinition",
"=",
"$",
"container",
"->",
"getDefinition",
"(",
"'hateoas.generator.registry'",
")",
";",
"foreach",
"(",
"$",
"container",
"->",
"findTaggedServiceId... | {@inheritdoc} | [
"{"
] | train | https://github.com/willdurand/BazingaHateoasBundle/blob/c2dccbdad5f3f88d405fdc1729705cba904a5888/DependencyInjection/Compiler/UrlGeneratorPass.php#L23-L47 |
willdurand/BazingaHateoasBundle | BazingaHateoasBundle.php | BazingaHateoasBundle.build | public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new UrlGeneratorPass());
$container->addCompilerPass(new RelationProviderPass());
$container->addCompilerPass(new ExtensionDriverPass());
$container->addCompilerPass(new CacheWarmupPass());
} | php | public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new UrlGeneratorPass());
$container->addCompilerPass(new RelationProviderPass());
$container->addCompilerPass(new ExtensionDriverPass());
$container->addCompilerPass(new CacheWarmupPass());
} | [
"public",
"function",
"build",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"parent",
"::",
"build",
"(",
"$",
"container",
")",
";",
"$",
"container",
"->",
"addCompilerPass",
"(",
"new",
"UrlGeneratorPass",
"(",
")",
")",
";",
"$",
"container",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/willdurand/BazingaHateoasBundle/blob/c2dccbdad5f3f88d405fdc1729705cba904a5888/BazingaHateoasBundle.php#L25-L33 |
willdurand/BazingaHateoasBundle | DependencyInjection/Compiler/ExtensionDriverPass.php | ExtensionDriverPass.process | public function process(ContainerBuilder $container)
{
$extensionDriver = $container->getDefinition('hateoas.configuration.metadata.extension_driver');
foreach ($container->findTaggedServiceIds('hateoas.configuration_extension') as $id => $tags) {
$extensionDefinition = $container->getDefinition($id);
if (!$this->implementsConfigurationExtensionInterface($container, $extensionDefinition)) {
throw new InvalidArgumentException(
sprintf(
'Service %s tagged with hateoas.configuration_extension must implement %s',
$id,
'Hateoas\Configuration\Metadata\ConfigurationExtensionInterface'
)
);
}
$extensionDriver->addMethodCall('registerExtension', [$extensionDefinition]);
}
} | php | public function process(ContainerBuilder $container)
{
$extensionDriver = $container->getDefinition('hateoas.configuration.metadata.extension_driver');
foreach ($container->findTaggedServiceIds('hateoas.configuration_extension') as $id => $tags) {
$extensionDefinition = $container->getDefinition($id);
if (!$this->implementsConfigurationExtensionInterface($container, $extensionDefinition)) {
throw new InvalidArgumentException(
sprintf(
'Service %s tagged with hateoas.configuration_extension must implement %s',
$id,
'Hateoas\Configuration\Metadata\ConfigurationExtensionInterface'
)
);
}
$extensionDriver->addMethodCall('registerExtension', [$extensionDefinition]);
}
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"extensionDriver",
"=",
"$",
"container",
"->",
"getDefinition",
"(",
"'hateoas.configuration.metadata.extension_driver'",
")",
";",
"foreach",
"(",
"$",
"container",
"->",
"f... | {@inheritdoc} | [
"{"
] | train | https://github.com/willdurand/BazingaHateoasBundle/blob/c2dccbdad5f3f88d405fdc1729705cba904a5888/DependencyInjection/Compiler/ExtensionDriverPass.php#L23-L42 |
willdurand/BazingaHateoasBundle | Expression/LinkExpressionFunction.php | LinkExpressionFunction.getFunctions | public function getFunctions()
{
return [
new ExpressionFunction('link', static function ($object, $rel, $absolute = false) {
return sprintf('$container->get(\'hateoas.helper.link\')->getLinkHref(%s, %s, %s)', $object, $rel, $absolute);
}, static function ($context, $object, $rel, $absolute = false) {
return $context['container']->get('hateoas.helper.link')->getLinkHref($object, $rel, $absolute);
}),
];
} | php | public function getFunctions()
{
return [
new ExpressionFunction('link', static function ($object, $rel, $absolute = false) {
return sprintf('$container->get(\'hateoas.helper.link\')->getLinkHref(%s, %s, %s)', $object, $rel, $absolute);
}, static function ($context, $object, $rel, $absolute = false) {
return $context['container']->get('hateoas.helper.link')->getLinkHref($object, $rel, $absolute);
}),
];
} | [
"public",
"function",
"getFunctions",
"(",
")",
"{",
"return",
"[",
"new",
"ExpressionFunction",
"(",
"'link'",
",",
"static",
"function",
"(",
"$",
"object",
",",
"$",
"rel",
",",
"$",
"absolute",
"=",
"false",
")",
"{",
"return",
"sprintf",
"(",
"'$con... | @return ExpressionFunction[]
@phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingReturnTypeHint
@phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.UselessReturnAnnotation | [
"@return",
"ExpressionFunction",
"[]"
] | train | https://github.com/willdurand/BazingaHateoasBundle/blob/c2dccbdad5f3f88d405fdc1729705cba904a5888/Expression/LinkExpressionFunction.php#L18-L27 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Actions/Filterable.php | Filterable.filterAll | public function filterAll(array $filters)
{
$filterList = [];
foreach ($filters as $key => $value) {
$filterList[] = $key . ':' . $value;
}
$result = $this->connection()->get($this->getEndpoint(), ['filter' => implode(',', $filterList)], true);
return $this->collectionFromResult($result);
} | php | public function filterAll(array $filters)
{
$filterList = [];
foreach ($filters as $key => $value) {
$filterList[] = $key . ':' . $value;
}
$result = $this->connection()->get($this->getEndpoint(), ['filter' => implode(',', $filterList)], true);
return $this->collectionFromResult($result);
} | [
"public",
"function",
"filterAll",
"(",
"array",
"$",
"filters",
")",
"{",
"$",
"filterList",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"filters",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"filterList",
"[",
"]",
"=",
"$",
"key",
".",
"... | @param array $filters
@return mixed
@throws \Picqer\Financials\Moneybird\Exceptions\ApiException | [
"@param",
"array",
"$filters",
"@return",
"mixed"
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Actions/Filterable.php#L35-L45 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Entities/Estimate.php | Estimate.sendEstimate | public function sendEstimate($deliveryMethodOrOptions = SendInvoiceOptions::METHOD_EMAIL)
{
if (is_string($deliveryMethodOrOptions)) {
$options = new SendInvoiceOptions($deliveryMethodOrOptions);
} else {
$options = $deliveryMethodOrOptions;
}
unset($deliveryMethodOrOptions);
if (! $options instanceof SendInvoiceOptions) {
$options = is_object($options) ? get_class($options) : gettype($options);
throw new InvalidArgumentException("Expected string or options instance. Received: '$options'");
}
$this->connection->patch($this->endpoint . '/' . $this->id . '/send_estimate', json_encode([
'estimate_sending' => $options->jsonSerialize(),
]));
return $this;
} | php | public function sendEstimate($deliveryMethodOrOptions = SendInvoiceOptions::METHOD_EMAIL)
{
if (is_string($deliveryMethodOrOptions)) {
$options = new SendInvoiceOptions($deliveryMethodOrOptions);
} else {
$options = $deliveryMethodOrOptions;
}
unset($deliveryMethodOrOptions);
if (! $options instanceof SendInvoiceOptions) {
$options = is_object($options) ? get_class($options) : gettype($options);
throw new InvalidArgumentException("Expected string or options instance. Received: '$options'");
}
$this->connection->patch($this->endpoint . '/' . $this->id . '/send_estimate', json_encode([
'estimate_sending' => $options->jsonSerialize(),
]));
return $this;
} | [
"public",
"function",
"sendEstimate",
"(",
"$",
"deliveryMethodOrOptions",
"=",
"SendInvoiceOptions",
"::",
"METHOD_EMAIL",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"deliveryMethodOrOptions",
")",
")",
"{",
"$",
"options",
"=",
"new",
"SendInvoiceOptions",
"(",... | Instruct Moneybird to send the estimate to the contact.
@param string|SendInvoiceOptions $deliveryMethodOrOptions
@return $this
@throws ApiException | [
"Instruct",
"Moneybird",
"to",
"send",
"the",
"estimate",
"to",
"the",
"contact",
"."
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Entities/Estimate.php#L106-L125 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Entities/SalesInvoiceReminder.php | SalesInvoiceReminder.send | public function send()
{
$aReminder = $this->json();
$aReminder = json_decode($aReminder, true);
$aReminder['sales_invoice_ids'] = array_map(function ($salesInvoice) {
if (is_object($salesInvoice)) {
return $salesInvoice->id;
} else {
return $salesInvoice;
}
}, $this->sales_invoices);
unset($aReminder['sales_invoices']);
$this->connection->post($this->endpoint . '/send_reminders', json_encode([
'sales_invoice_reminders' => [$aReminder],
]));
} | php | public function send()
{
$aReminder = $this->json();
$aReminder = json_decode($aReminder, true);
$aReminder['sales_invoice_ids'] = array_map(function ($salesInvoice) {
if (is_object($salesInvoice)) {
return $salesInvoice->id;
} else {
return $salesInvoice;
}
}, $this->sales_invoices);
unset($aReminder['sales_invoices']);
$this->connection->post($this->endpoint . '/send_reminders', json_encode([
'sales_invoice_reminders' => [$aReminder],
]));
} | [
"public",
"function",
"send",
"(",
")",
"{",
"$",
"aReminder",
"=",
"$",
"this",
"->",
"json",
"(",
")",
";",
"$",
"aReminder",
"=",
"json_decode",
"(",
"$",
"aReminder",
",",
"true",
")",
";",
"$",
"aReminder",
"[",
"'sales_invoice_ids'",
"]",
"=",
... | Pushes the reminder.
@throws \Picqer\Financials\Moneybird\Exceptions\ApiException | [
"Pushes",
"the",
"reminder",
"."
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Entities/SalesInvoiceReminder.php#L38-L55 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Actions/PrivateDownloadable.php | PrivateDownloadable.download | public function download()
{
$connection = $this->connection();
$client = $connection->connect();
$headers = [
'Accept' => 'application/pdf',
'Content-Type' => 'application/pdf',
'Authorization' => 'Bearer ' . $connection->getAccessToken(),
];
$endpoint = 'https://moneybird.com/' . $connection->getAdministrationId() . '/' . $this->endpoint . '/' . $this->id . '.pdf';
$body = '';
$request = new Request('GET', $endpoint, $headers, $body);
$response = $client->send($request);
return $response->getBody()->getContents();
} | php | public function download()
{
$connection = $this->connection();
$client = $connection->connect();
$headers = [
'Accept' => 'application/pdf',
'Content-Type' => 'application/pdf',
'Authorization' => 'Bearer ' . $connection->getAccessToken(),
];
$endpoint = 'https://moneybird.com/' . $connection->getAdministrationId() . '/' . $this->endpoint . '/' . $this->id . '.pdf';
$body = '';
$request = new Request('GET', $endpoint, $headers, $body);
$response = $client->send($request);
return $response->getBody()->getContents();
} | [
"public",
"function",
"download",
"(",
")",
"{",
"$",
"connection",
"=",
"$",
"this",
"->",
"connection",
"(",
")",
";",
"$",
"client",
"=",
"$",
"connection",
"->",
"connect",
"(",
")",
";",
"$",
"headers",
"=",
"[",
"'Accept'",
"=>",
"'application/pd... | Download invoice as PDF.
@return string PDF file data
@throws \Picqer\Financials\Moneybird\Exceptions\ApiException | [
"Download",
"invoice",
"as",
"PDF",
"."
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Actions/PrivateDownloadable.php#L25-L43 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Entities/SalesInvoice.php | SalesInvoice.findByInvoiceId | public function findByInvoiceId($invoiceId)
{
$result = $this->connection()->get($this->getEndpoint() . '/find_by_invoice_id/' . urlencode($invoiceId));
return $this->makeFromResponse($result);
} | php | public function findByInvoiceId($invoiceId)
{
$result = $this->connection()->get($this->getEndpoint() . '/find_by_invoice_id/' . urlencode($invoiceId));
return $this->makeFromResponse($result);
} | [
"public",
"function",
"findByInvoiceId",
"(",
"$",
"invoiceId",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"connection",
"(",
")",
"->",
"get",
"(",
"$",
"this",
"->",
"getEndpoint",
"(",
")",
".",
"'/find_by_invoice_id/'",
".",
"urlencode",
"(",
"... | Find SalesInvoice by invoice_id.
@param string|int $invoiceId
@return static
@throws \Picqer\Financials\Moneybird\Exceptions\ApiException | [
"Find",
"SalesInvoice",
"by",
"invoice_id",
"."
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Entities/SalesInvoice.php#L147-L152 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Entities/SalesInvoice.php | SalesInvoice.registerPayment | public function registerPayment(SalesInvoicePayment $salesInvoicePayment)
{
if (! isset($salesInvoicePayment->payment_date)) {
throw new ApiException('Required [payment_date] is missing');
}
if (! isset($salesInvoicePayment->price)) {
throw new ApiException('Required [price] is missing');
}
$this->connection()->post($this->endpoint . '/' . $this->id . '/payments',
$salesInvoicePayment->jsonWithNamespace()
);
return $this;
} | php | public function registerPayment(SalesInvoicePayment $salesInvoicePayment)
{
if (! isset($salesInvoicePayment->payment_date)) {
throw new ApiException('Required [payment_date] is missing');
}
if (! isset($salesInvoicePayment->price)) {
throw new ApiException('Required [price] is missing');
}
$this->connection()->post($this->endpoint . '/' . $this->id . '/payments',
$salesInvoicePayment->jsonWithNamespace()
);
return $this;
} | [
"public",
"function",
"registerPayment",
"(",
"SalesInvoicePayment",
"$",
"salesInvoicePayment",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"salesInvoicePayment",
"->",
"payment_date",
")",
")",
"{",
"throw",
"new",
"ApiException",
"(",
"'Required [payment_date] i... | Register a payment for the current invoice.
@param SalesInvoicePayment $salesInvoicePayment (payment_date and price are required)
@return $this
@throws ApiException | [
"Register",
"a",
"payment",
"for",
"the",
"current",
"invoice",
"."
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Entities/SalesInvoice.php#L161-L176 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Entities/SalesInvoice.php | SalesInvoice.deletePayment | public function deletePayment(SalesInvoicePayment $salesInvoicePayment)
{
if (! isset($salesInvoicePayment->id)) {
throw new ApiException('Required [id] is missing');
}
$this->connection()->delete($this->endpoint . '/' . $this->id . '/payments/' . $salesInvoicePayment->id);
return $this;
} | php | public function deletePayment(SalesInvoicePayment $salesInvoicePayment)
{
if (! isset($salesInvoicePayment->id)) {
throw new ApiException('Required [id] is missing');
}
$this->connection()->delete($this->endpoint . '/' . $this->id . '/payments/' . $salesInvoicePayment->id);
return $this;
} | [
"public",
"function",
"deletePayment",
"(",
"SalesInvoicePayment",
"$",
"salesInvoicePayment",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"salesInvoicePayment",
"->",
"id",
")",
")",
"{",
"throw",
"new",
"ApiException",
"(",
"'Required [id] is missing'",
")",
... | Delete a payment for the current invoice.
@param SalesInvoicePayment $salesInvoicePayment (id is required)
@return $this
@throws ApiException | [
"Delete",
"a",
"payment",
"for",
"the",
"current",
"invoice",
"."
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Entities/SalesInvoice.php#L185-L194 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Entities/SalesInvoice.php | SalesInvoice.addNote | public function addNote(Note $note)
{
$this->connection()->post($this->endpoint . '/' . $this->id . '/notes',
$note->jsonWithNamespace()
);
return $this;
} | php | public function addNote(Note $note)
{
$this->connection()->post($this->endpoint . '/' . $this->id . '/notes',
$note->jsonWithNamespace()
);
return $this;
} | [
"public",
"function",
"addNote",
"(",
"Note",
"$",
"note",
")",
"{",
"$",
"this",
"->",
"connection",
"(",
")",
"->",
"post",
"(",
"$",
"this",
"->",
"endpoint",
".",
"'/'",
".",
"$",
"this",
"->",
"id",
".",
"'/notes'",
",",
"$",
"note",
"->",
"... | Add a note to the current invoice.
@param Note $note
@return $this
@throws ApiException | [
"Add",
"a",
"note",
"to",
"the",
"current",
"invoice",
"."
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Entities/SalesInvoice.php#L203-L210 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Entities/SalesInvoice.php | SalesInvoice.duplicateToCreditInvoice | public function duplicateToCreditInvoice()
{
$response = $this->connection()->patch($this->getEndpoint() . '/' . $this->id . '/duplicate_creditinvoice',
json_encode([]) // No body needed for this call. The patch method however needs one.
);
return $this->makeFromResponse($response);
} | php | public function duplicateToCreditInvoice()
{
$response = $this->connection()->patch($this->getEndpoint() . '/' . $this->id . '/duplicate_creditinvoice',
json_encode([]) // No body needed for this call. The patch method however needs one.
);
return $this->makeFromResponse($response);
} | [
"public",
"function",
"duplicateToCreditInvoice",
"(",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"connection",
"(",
")",
"->",
"patch",
"(",
"$",
"this",
"->",
"getEndpoint",
"(",
")",
".",
"'/'",
".",
"$",
"this",
"->",
"id",
".",
"'/duplicat... | Create a credit invoice based on the current invoice.
@return \Picqer\Financials\Moneybird\Entities\SalesInvoice
@throws \Picqer\Financials\Moneybird\Exceptions\ApiException | [
"Create",
"a",
"credit",
"invoice",
"based",
"on",
"the",
"current",
"invoice",
"."
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Entities/SalesInvoice.php#L219-L226 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Entities/SalesInvoice.php | SalesInvoice.addAttachment | public function addAttachment($filename, $contents)
{
$this->connection()->upload($this->endpoint . '/' . $this->id . '/attachments', [
'multipart' => [
[
'name' => 'file',
'contents' => $contents,
'filename' => $filename,
],
],
]);
return $this;
} | php | public function addAttachment($filename, $contents)
{
$this->connection()->upload($this->endpoint . '/' . $this->id . '/attachments', [
'multipart' => [
[
'name' => 'file',
'contents' => $contents,
'filename' => $filename,
],
],
]);
return $this;
} | [
"public",
"function",
"addAttachment",
"(",
"$",
"filename",
",",
"$",
"contents",
")",
"{",
"$",
"this",
"->",
"connection",
"(",
")",
"->",
"upload",
"(",
"$",
"this",
"->",
"endpoint",
".",
"'/'",
".",
"$",
"this",
"->",
"id",
".",
"'/attachments'",... | Add Attachment to this invoice.
You can use fopen('/path/to/file', 'r') in $resource.
@param string $filename The filename of the attachment
@param resource $contents A StreamInterface/resource/string, @see http://docs.guzzlephp.org/en/stable/request-options.html?highlight=multipart#multipart
@return \Picqer\Financials\Moneybird\Entities\SalesInvoice
@throws \Picqer\Financials\Moneybird\Exceptions\ApiException | [
"Add",
"Attachment",
"to",
"this",
"invoice",
"."
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Entities/SalesInvoice.php#L256-L269 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Entities/SalesInvoice.php | SalesInvoice.pauseWorkflow | public function pauseWorkflow()
{
try {
$this->connection()->post($this->endpoint . '/' . $this->id . '/pause', json_encode([]));
} catch (ApiException $exception) {
if (strpos($exception->getMessage(), 'The sales_invoice is already paused') !== false) {
return true; // Everything is fine since the sales invoice was already paused we don't need an error.
}
throw $exception;
}
return true;
} | php | public function pauseWorkflow()
{
try {
$this->connection()->post($this->endpoint . '/' . $this->id . '/pause', json_encode([]));
} catch (ApiException $exception) {
if (strpos($exception->getMessage(), 'The sales_invoice is already paused') !== false) {
return true; // Everything is fine since the sales invoice was already paused we don't need an error.
}
throw $exception;
}
return true;
} | [
"public",
"function",
"pauseWorkflow",
"(",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"connection",
"(",
")",
"->",
"post",
"(",
"$",
"this",
"->",
"endpoint",
".",
"'/'",
".",
"$",
"this",
"->",
"id",
".",
"'/pause'",
",",
"json_encode",
"(",
"[",
... | Pauses the sales invoice. The automatic workflow steps will not be executed while the sales invoice is paused.
@return bool
@throws \Picqer\Financials\Moneybird\Exceptions\ApiException | [
"Pauses",
"the",
"sales",
"invoice",
".",
"The",
"automatic",
"workflow",
"steps",
"will",
"not",
"be",
"executed",
"while",
"the",
"sales",
"invoice",
"is",
"paused",
"."
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Entities/SalesInvoice.php#L278-L291 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Entities/Contact.php | Contact.findByCustomerId | public function findByCustomerId($customerId)
{
$result = $this->connection()->get($this->getEndpoint() . '/customer_id/' . urlencode($customerId));
return $this->makeFromResponse($result);
} | php | public function findByCustomerId($customerId)
{
$result = $this->connection()->get($this->getEndpoint() . '/customer_id/' . urlencode($customerId));
return $this->makeFromResponse($result);
} | [
"public",
"function",
"findByCustomerId",
"(",
"$",
"customerId",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"connection",
"(",
")",
"->",
"get",
"(",
"$",
"this",
"->",
"getEndpoint",
"(",
")",
".",
"'/customer_id/'",
".",
"urlencode",
"(",
"$",
... | @param string|int $customerId
@return static
@throws ApiException | [
"@param",
"string|int",
"$customerId"
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Entities/Contact.php#L96-L101 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Actions/FindAll.php | FindAll.get | public function get($params = [])
{
$result = $this->connection()->get($this->getEndpoint(), $params);
return $this->collectionFromResult($result);
} | php | public function get($params = [])
{
$result = $this->connection()->get($this->getEndpoint(), $params);
return $this->collectionFromResult($result);
} | [
"public",
"function",
"get",
"(",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"connection",
"(",
")",
"->",
"get",
"(",
"$",
"this",
"->",
"getEndpoint",
"(",
")",
",",
"$",
"params",
")",
";",
"return",
"$",
... | @param array $params
@return mixed
@throws \Picqer\Financials\Moneybird\Exceptions\ApiException | [
"@param",
"array",
"$params"
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Actions/FindAll.php#L19-L24 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Actions/FindAll.php | FindAll.getAll | public function getAll($params = [])
{
$result = $this->connection()->get($this->getEndpoint(), $params, true);
return $this->collectionFromResult($result);
} | php | public function getAll($params = [])
{
$result = $this->connection()->get($this->getEndpoint(), $params, true);
return $this->collectionFromResult($result);
} | [
"public",
"function",
"getAll",
"(",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"connection",
"(",
")",
"->",
"get",
"(",
"$",
"this",
"->",
"getEndpoint",
"(",
")",
",",
"$",
"params",
",",
"true",
")",
";",
... | @param array $params
@return mixed
@throws \Picqer\Financials\Moneybird\Exceptions\ApiException | [
"@param",
"array",
"$params"
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Actions/FindAll.php#L33-L38 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Connection.php | Connection.createRequest | private function createRequest($method = 'GET', $endpoint, $body = null, array $params = [], array $headers = [])
{
// Add default json headers to the request
$headers = array_merge($headers, [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
]);
// If access token is not set or token has expired, acquire new token
if (empty($this->accessToken)) {
$this->acquireAccessToken();
}
// If we have a token, sign the request
if (! empty($this->accessToken)) {
$headers['Authorization'] = 'Bearer ' . $this->accessToken;
}
// Create param string
if (! empty($params)) {
$endpoint .= '?' . http_build_query($params);
}
// Create the request
$request = new Request($method, $endpoint, $headers, $body);
return $request;
} | php | private function createRequest($method = 'GET', $endpoint, $body = null, array $params = [], array $headers = [])
{
// Add default json headers to the request
$headers = array_merge($headers, [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
]);
// If access token is not set or token has expired, acquire new token
if (empty($this->accessToken)) {
$this->acquireAccessToken();
}
// If we have a token, sign the request
if (! empty($this->accessToken)) {
$headers['Authorization'] = 'Bearer ' . $this->accessToken;
}
// Create param string
if (! empty($params)) {
$endpoint .= '?' . http_build_query($params);
}
// Create the request
$request = new Request($method, $endpoint, $headers, $body);
return $request;
} | [
"private",
"function",
"createRequest",
"(",
"$",
"method",
"=",
"'GET'",
",",
"$",
"endpoint",
",",
"$",
"body",
"=",
"null",
",",
"array",
"$",
"params",
"=",
"[",
"]",
",",
"array",
"$",
"headers",
"=",
"[",
"]",
")",
"{",
"// Add default json heade... | @param string $method
@param string $endpoint
@param null $body
@param array $params
@param array $headers
@return \GuzzleHttp\Psr7\Request
@throws \Picqer\Financials\Moneybird\Exceptions\ApiException | [
"@param",
"string",
"$method",
"@param",
"string",
"$endpoint",
"@param",
"null",
"$body",
"@param",
"array",
"$params",
"@param",
"array",
"$headers"
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Connection.php#L149-L176 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Connection.php | Connection.parseExceptionForErrorMessages | private function parseExceptionForErrorMessages(Exception $exception)
{
if (! $exception instanceof BadResponseException) {
return new ApiException($exception->getMessage(), 0, $exception);
}
$response = $exception->getResponse();
if (null === $response) {
return new ApiException('Response is NULL.', 0, $exception);
}
Psr7\rewind_body($response);
$responseBody = $response->getBody()->getContents();
$decodedResponseBody = json_decode($responseBody, true);
if (null !== $decodedResponseBody && isset($decodedResponseBody['error']['message']['value'])) {
$errorMessage = $decodedResponseBody['error']['message']['value'];
} else {
$errorMessage = $responseBody;
}
$this->checkWhetherRateLimitHasBeenReached($response, $errorMessage);
return new ApiException('Error ' . $response->getStatusCode() . ': ' . $errorMessage, $response->getStatusCode(), $exception);
} | php | private function parseExceptionForErrorMessages(Exception $exception)
{
if (! $exception instanceof BadResponseException) {
return new ApiException($exception->getMessage(), 0, $exception);
}
$response = $exception->getResponse();
if (null === $response) {
return new ApiException('Response is NULL.', 0, $exception);
}
Psr7\rewind_body($response);
$responseBody = $response->getBody()->getContents();
$decodedResponseBody = json_decode($responseBody, true);
if (null !== $decodedResponseBody && isset($decodedResponseBody['error']['message']['value'])) {
$errorMessage = $decodedResponseBody['error']['message']['value'];
} else {
$errorMessage = $responseBody;
}
$this->checkWhetherRateLimitHasBeenReached($response, $errorMessage);
return new ApiException('Error ' . $response->getStatusCode() . ': ' . $errorMessage, $response->getStatusCode(), $exception);
} | [
"private",
"function",
"parseExceptionForErrorMessages",
"(",
"Exception",
"$",
"exception",
")",
"{",
"if",
"(",
"!",
"$",
"exception",
"instanceof",
"BadResponseException",
")",
"{",
"return",
"new",
"ApiException",
"(",
"$",
"exception",
"->",
"getMessage",
"("... | Parse the response in the Exception to return the Exact error messages.
@param Exception $exception
@return \Picqer\Financials\Moneybird\Exceptions\ApiException
@throws \Picqer\Financials\Moneybird\Exceptions\Api\TooManyRequestsException | [
"Parse",
"the",
"response",
"in",
"the",
"Exception",
"to",
"return",
"the",
"Exact",
"error",
"messages",
"."
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Connection.php#L474-L499 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Connection.php | Connection.checkWhetherRateLimitHasBeenReached | private function checkWhetherRateLimitHasBeenReached(ResponseInterface $response, $errorMessage)
{
$retryAfterHeaders = $response->getHeader('Retry-After');
if ($response->getStatusCode() === 429 && count($retryAfterHeaders) > 0) {
$exception = new TooManyRequestsException('Error ' . $response->getStatusCode() . ': ' . $errorMessage, $response->getStatusCode());
$exception->retryAfterNumberOfSeconds = (int) current($retryAfterHeaders);
throw $exception;
}
} | php | private function checkWhetherRateLimitHasBeenReached(ResponseInterface $response, $errorMessage)
{
$retryAfterHeaders = $response->getHeader('Retry-After');
if ($response->getStatusCode() === 429 && count($retryAfterHeaders) > 0) {
$exception = new TooManyRequestsException('Error ' . $response->getStatusCode() . ': ' . $errorMessage, $response->getStatusCode());
$exception->retryAfterNumberOfSeconds = (int) current($retryAfterHeaders);
throw $exception;
}
} | [
"private",
"function",
"checkWhetherRateLimitHasBeenReached",
"(",
"ResponseInterface",
"$",
"response",
",",
"$",
"errorMessage",
")",
"{",
"$",
"retryAfterHeaders",
"=",
"$",
"response",
"->",
"getHeader",
"(",
"'Retry-After'",
")",
";",
"if",
"(",
"$",
"respons... | @param ResponseInterface $response
@param string $errorMessage
@return void
@throws TooManyRequestsException | [
"@param",
"ResponseInterface",
"$response",
"@param",
"string",
"$errorMessage"
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Connection.php#L509-L518 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Connection.php | Connection.formatUrl | private function formatUrl($url, $method = 'get')
{
if ($this->testing) {
return 'https://httpbin.org/' . $method;
}
return $this->apiUrl . '/' . ($this->administrationId ? $this->administrationId . '/' : '') . $url . '.json';
} | php | private function formatUrl($url, $method = 'get')
{
if ($this->testing) {
return 'https://httpbin.org/' . $method;
}
return $this->apiUrl . '/' . ($this->administrationId ? $this->administrationId . '/' : '') . $url . '.json';
} | [
"private",
"function",
"formatUrl",
"(",
"$",
"url",
",",
"$",
"method",
"=",
"'get'",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"testing",
")",
"{",
"return",
"'https://httpbin.org/'",
".",
"$",
"method",
";",
"}",
"return",
"$",
"this",
"->",
"apiUrl",... | @param string $url
@param string $method
@return string | [
"@param",
"string",
"$url",
"@param",
"string",
"$method"
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Connection.php#L526-L533 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Model.php | Model.getArrayWithNestedObjects | private function getArrayWithNestedObjects($useAttributesAppend = true)
{
$result = [];
$multipleNestedEntities = $this->getMultipleNestedEntities();
foreach ($this->attributes as $attributeName => $attributeValue) {
if (! is_object($attributeValue)) {
$result[$attributeName] = $attributeValue;
}
if (array_key_exists($attributeName, $this->getSingleNestedEntities())) {
$result[$attributeName] = $attributeValue->attributes;
}
if (array_key_exists($attributeName, $multipleNestedEntities)) {
if ($useAttributesAppend) {
$attributeNameToUse = $attributeName . '_attributes';
} else {
$attributeNameToUse = $attributeName;
}
$result[$attributeNameToUse] = [];
foreach ($attributeValue as $attributeEntity) {
$result[$attributeNameToUse][] = $attributeEntity->attributes;
if ($multipleNestedEntities[$attributeName]['type'] === self::NESTING_TYPE_NESTED_OBJECTS) {
$result[$attributeNameToUse] = (object) $result[$attributeNameToUse];
}
}
if (
$multipleNestedEntities[$attributeName]['type'] === self::NESTING_TYPE_NESTED_OBJECTS
&& empty($result[$attributeNameToUse])
) {
$result[$attributeNameToUse] = new \StdClass();
}
}
}
return $result;
} | php | private function getArrayWithNestedObjects($useAttributesAppend = true)
{
$result = [];
$multipleNestedEntities = $this->getMultipleNestedEntities();
foreach ($this->attributes as $attributeName => $attributeValue) {
if (! is_object($attributeValue)) {
$result[$attributeName] = $attributeValue;
}
if (array_key_exists($attributeName, $this->getSingleNestedEntities())) {
$result[$attributeName] = $attributeValue->attributes;
}
if (array_key_exists($attributeName, $multipleNestedEntities)) {
if ($useAttributesAppend) {
$attributeNameToUse = $attributeName . '_attributes';
} else {
$attributeNameToUse = $attributeName;
}
$result[$attributeNameToUse] = [];
foreach ($attributeValue as $attributeEntity) {
$result[$attributeNameToUse][] = $attributeEntity->attributes;
if ($multipleNestedEntities[$attributeName]['type'] === self::NESTING_TYPE_NESTED_OBJECTS) {
$result[$attributeNameToUse] = (object) $result[$attributeNameToUse];
}
}
if (
$multipleNestedEntities[$attributeName]['type'] === self::NESTING_TYPE_NESTED_OBJECTS
&& empty($result[$attributeNameToUse])
) {
$result[$attributeNameToUse] = new \StdClass();
}
}
}
return $result;
} | [
"private",
"function",
"getArrayWithNestedObjects",
"(",
"$",
"useAttributesAppend",
"=",
"true",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"multipleNestedEntities",
"=",
"$",
"this",
"->",
"getMultipleNestedEntities",
"(",
")",
";",
"foreach",
"(",
"$... | @param bool $useAttributesAppend
@return array | [
"@param",
"bool",
"$useAttributesAppend"
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Model.php#L203-L243 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Model.php | Model.selfFromResponse | public function selfFromResponse(array $response)
{
$this->fill($response);
foreach ($this->getSingleNestedEntities() as $key => $value) {
if (isset($response[$key])) {
$entityName = $value;
$this->$key = new $entityName($this->connection, $response[$key]);
}
}
foreach ($this->getMultipleNestedEntities() as $key => $value) {
if (isset($response[$key])) {
$entityName = $value['entity'];
/** @var self $instantiatedEntity */
$instantiatedEntity = new $entityName($this->connection);
$this->$key = $instantiatedEntity->collectionFromResult($response[$key]);
}
}
return $this;
} | php | public function selfFromResponse(array $response)
{
$this->fill($response);
foreach ($this->getSingleNestedEntities() as $key => $value) {
if (isset($response[$key])) {
$entityName = $value;
$this->$key = new $entityName($this->connection, $response[$key]);
}
}
foreach ($this->getMultipleNestedEntities() as $key => $value) {
if (isset($response[$key])) {
$entityName = $value['entity'];
/** @var self $instantiatedEntity */
$instantiatedEntity = new $entityName($this->connection);
$this->$key = $instantiatedEntity->collectionFromResult($response[$key]);
}
}
return $this;
} | [
"public",
"function",
"selfFromResponse",
"(",
"array",
"$",
"response",
")",
"{",
"$",
"this",
"->",
"fill",
"(",
"$",
"response",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getSingleNestedEntities",
"(",
")",
"as",
"$",
"key",
"=>",
"$",
"value",
... | Recreate this object with the response from the API.
@param array $response
@return $this | [
"Recreate",
"this",
"object",
"with",
"the",
"response",
"from",
"the",
"API",
"."
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Model.php#L267-L288 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Model.php | Model.__isset | public function __isset($name)
{
return isset($this->attributes[$name]) && null !== $this->attributes[$name];
} | php | public function __isset($name)
{
return isset($this->attributes[$name]) && null !== $this->attributes[$name];
} | [
"public",
"function",
"__isset",
"(",
"$",
"name",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"attributes",
"[",
"$",
"name",
"]",
")",
"&&",
"null",
"!==",
"$",
"this",
"->",
"attributes",
"[",
"$",
"name",
"]",
";",
"}"
] | Determine if an attribute exists on the model.
@param string $name
@return bool | [
"Determine",
"if",
"an",
"attribute",
"exists",
"on",
"the",
"model",
"."
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Model.php#L357-L360 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Actions/FindOne.php | FindOne.find | public function find($id)
{
$result = $this->connection()->get($this->getEndpoint() . '/' . urlencode($id));
return $this->makeFromResponse($result);
} | php | public function find($id)
{
$result = $this->connection()->get($this->getEndpoint() . '/' . urlencode($id));
return $this->makeFromResponse($result);
} | [
"public",
"function",
"find",
"(",
"$",
"id",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"connection",
"(",
")",
"->",
"get",
"(",
"$",
"this",
"->",
"getEndpoint",
"(",
")",
".",
"'/'",
".",
"urlencode",
"(",
"$",
"id",
")",
")",
";",
"r... | @param string|int $id
@return mixed
@throws \Picqer\Financials\Moneybird\Exceptions\ApiException | [
"@param",
"string|int",
"$id"
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Actions/FindOne.php#L19-L24 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Entities/FinancialMutation.php | FinancialMutation.linkToBooking | public function linkToBooking($bookingType, $bookingId, $priceBase, $price = null, $description = null, $paymentBatchIdentifier = null)
{
if (! in_array($bookingType, self::$allowedBookingTypesToLinkToFinancialMutation, true)) {
throw new ApiException('Invalid booking type to link to FinancialMutation, allowed booking types: ' . implode(', ', self::$allowedBookingTypesToLinkToFinancialMutation));
}
if (! is_numeric($bookingId)) {
throw new ApiException('Invalid Booking identifier to link to FinancialMutation');
}
//Filter out potential NULL values
$parameters = array_filter(
[
'booking_type' => $bookingType,
'booking_id' => $bookingId,
'price_base' => $priceBase,
'price' => $price,
'description' => $description,
'payment_batch_identifier' => $paymentBatchIdentifier,
]
);
return $this->connection->patch($this->endpoint . '/' . $this->id . '/link_booking', json_encode($parameters));
} | php | public function linkToBooking($bookingType, $bookingId, $priceBase, $price = null, $description = null, $paymentBatchIdentifier = null)
{
if (! in_array($bookingType, self::$allowedBookingTypesToLinkToFinancialMutation, true)) {
throw new ApiException('Invalid booking type to link to FinancialMutation, allowed booking types: ' . implode(', ', self::$allowedBookingTypesToLinkToFinancialMutation));
}
if (! is_numeric($bookingId)) {
throw new ApiException('Invalid Booking identifier to link to FinancialMutation');
}
//Filter out potential NULL values
$parameters = array_filter(
[
'booking_type' => $bookingType,
'booking_id' => $bookingId,
'price_base' => $priceBase,
'price' => $price,
'description' => $description,
'payment_batch_identifier' => $paymentBatchIdentifier,
]
);
return $this->connection->patch($this->endpoint . '/' . $this->id . '/link_booking', json_encode($parameters));
} | [
"public",
"function",
"linkToBooking",
"(",
"$",
"bookingType",
",",
"$",
"bookingId",
",",
"$",
"priceBase",
",",
"$",
"price",
"=",
"null",
",",
"$",
"description",
"=",
"null",
",",
"$",
"paymentBatchIdentifier",
"=",
"null",
")",
"{",
"if",
"(",
"!",... | @param string $bookingType
@param string | int $bookingId
@param string | float $priceBase
@param string | float $price
@param string $description
@param string $paymentBatchIdentifier
@return int
@throws \Picqer\Financials\Moneybird\Exceptions\ApiException | [
"@param",
"string",
"$bookingType",
"@param",
"string",
"|",
"int",
"$bookingId",
"@param",
"string",
"|",
"float",
"$priceBase",
"@param",
"string",
"|",
"float",
"$price",
"@param",
"string",
"$description",
"@param",
"string",
"$paymentBatchIdentifier"
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Entities/FinancialMutation.php#L98-L120 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Entities/FinancialMutation.php | FinancialMutation.unlinkFromBooking | public function unlinkFromBooking($bookingType, $bookingId)
{
if (! in_array($bookingType, self::$allowedBookingTypesToUnlinkFromFinancialMutation, true)) {
throw new ApiException('Invalid booking type to unlink from FinancialMutation, allowed booking types: ' . implode(', ', self::$allowedBookingTypesToUnlinkFromFinancialMutation));
}
if (! is_numeric($bookingId)) {
throw new ApiException('Invalid Booking identifier to unlink from FinancialMutation');
}
$parameters = [
'booking_type' => $bookingType,
'booking_id' => $bookingId,
];
return $this->connection->delete($this->endpoint . '/' . $this->id . '/unlink_booking', json_encode($parameters));
} | php | public function unlinkFromBooking($bookingType, $bookingId)
{
if (! in_array($bookingType, self::$allowedBookingTypesToUnlinkFromFinancialMutation, true)) {
throw new ApiException('Invalid booking type to unlink from FinancialMutation, allowed booking types: ' . implode(', ', self::$allowedBookingTypesToUnlinkFromFinancialMutation));
}
if (! is_numeric($bookingId)) {
throw new ApiException('Invalid Booking identifier to unlink from FinancialMutation');
}
$parameters = [
'booking_type' => $bookingType,
'booking_id' => $bookingId,
];
return $this->connection->delete($this->endpoint . '/' . $this->id . '/unlink_booking', json_encode($parameters));
} | [
"public",
"function",
"unlinkFromBooking",
"(",
"$",
"bookingType",
",",
"$",
"bookingId",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"bookingType",
",",
"self",
"::",
"$",
"allowedBookingTypesToUnlinkFromFinancialMutation",
",",
"true",
")",
")",
"{",
"t... | @param string $bookingType
@param string | int $bookingId
@return array
@throws ApiException | [
"@param",
"string",
"$bookingType",
"@param",
"string",
"|",
"int",
"$bookingId"
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Entities/FinancialMutation.php#L129-L144 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Entities/Receipt.php | Receipt.registerPayment | public function registerPayment(ReceiptPayment $receiptPayment)
{
if (! isset($receiptPayment->payment_date)) {
throw new ApiException('Required [payment_date] is missing');
}
if (! isset($receiptPayment->price)) {
throw new ApiException('Required [price] is missing');
}
$this->connection()->post($this->endpoint . '/' . $this->id . '/payments',
$receiptPayment->jsonWithNamespace()
);
return $this;
} | php | public function registerPayment(ReceiptPayment $receiptPayment)
{
if (! isset($receiptPayment->payment_date)) {
throw new ApiException('Required [payment_date] is missing');
}
if (! isset($receiptPayment->price)) {
throw new ApiException('Required [price] is missing');
}
$this->connection()->post($this->endpoint . '/' . $this->id . '/payments',
$receiptPayment->jsonWithNamespace()
);
return $this;
} | [
"public",
"function",
"registerPayment",
"(",
"ReceiptPayment",
"$",
"receiptPayment",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"receiptPayment",
"->",
"payment_date",
")",
")",
"{",
"throw",
"new",
"ApiException",
"(",
"'Required [payment_date] is missing'",
... | Register a payment for the current purchase invoice.
@param ReceiptPayment $receiptPayment (payment_date and price are required)
@return $this
@throws ApiException | [
"Register",
"a",
"payment",
"for",
"the",
"current",
"purchase",
"invoice",
"."
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Entities/Receipt.php#L76-L91 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Actions/Synchronizable.php | Synchronizable.getVersions | public function getVersions(array $ids)
{
$result = $this->connection()->post($this->getEndpoint() . '/synchronization', json_encode([
'ids' => $ids,
]));
return $this->collectionFromResult($result);
} | php | public function getVersions(array $ids)
{
$result = $this->connection()->post($this->getEndpoint() . '/synchronization', json_encode([
'ids' => $ids,
]));
return $this->collectionFromResult($result);
} | [
"public",
"function",
"getVersions",
"(",
"array",
"$",
"ids",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"connection",
"(",
")",
"->",
"post",
"(",
"$",
"this",
"->",
"getEndpoint",
"(",
")",
".",
"'/synchronization'",
",",
"json_encode",
"(",
"... | @param array $ids
@return mixed
@throws \Picqer\Financials\Moneybird\Exceptions\ApiException | [
"@param",
"array",
"$ids",
"@return",
"mixed"
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Actions/Synchronizable.php#L43-L50 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Entities/PurchaseInvoice.php | PurchaseInvoice.registerPayment | public function registerPayment(PurchaseInvoicePayment $purchaseInvoicePayment)
{
if (! isset($purchaseInvoicePayment->payment_date)) {
throw new ApiException('Required [payment_date] is missing');
}
if (! isset($purchaseInvoicePayment->price)) {
throw new ApiException('Required [price] is missing');
}
$this->connection()->patch($this->endpoint . '/' . $this->id . '/register_payment',
$purchaseInvoicePayment->jsonWithNamespace()
);
return $this;
} | php | public function registerPayment(PurchaseInvoicePayment $purchaseInvoicePayment)
{
if (! isset($purchaseInvoicePayment->payment_date)) {
throw new ApiException('Required [payment_date] is missing');
}
if (! isset($purchaseInvoicePayment->price)) {
throw new ApiException('Required [price] is missing');
}
$this->connection()->patch($this->endpoint . '/' . $this->id . '/register_payment',
$purchaseInvoicePayment->jsonWithNamespace()
);
return $this;
} | [
"public",
"function",
"registerPayment",
"(",
"PurchaseInvoicePayment",
"$",
"purchaseInvoicePayment",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"purchaseInvoicePayment",
"->",
"payment_date",
")",
")",
"{",
"throw",
"new",
"ApiException",
"(",
"'Required [paymen... | Register a payment for the current purchase invoice.
@param PurchaseInvoicePayment $purchaseInvoicePayment (payment_date and price are required)
@return $this
@throws ApiException | [
"Register",
"a",
"payment",
"for",
"the",
"current",
"purchase",
"invoice",
"."
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Entities/PurchaseInvoice.php#L86-L101 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Actions/Storable.php | Storable.insert | public function insert()
{
$result = $this->connection()->post($this->getEndpoint(), $this->jsonWithNamespace());
return $this->selfFromResponse($result);
} | php | public function insert()
{
$result = $this->connection()->post($this->getEndpoint(), $this->jsonWithNamespace());
return $this->selfFromResponse($result);
} | [
"public",
"function",
"insert",
"(",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"connection",
"(",
")",
"->",
"post",
"(",
"$",
"this",
"->",
"getEndpoint",
"(",
")",
",",
"$",
"this",
"->",
"jsonWithNamespace",
"(",
")",
")",
";",
"return",
... | @return mixed
@throws \Picqer\Financials\Moneybird\Exceptions\ApiException | [
"@return",
"mixed"
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Actions/Storable.php#L31-L36 |
picqer/moneybird-php-client | src/Picqer/Financials/Moneybird/Actions/Storable.php | Storable.update | public function update()
{
$result = $this->connection()->patch($this->getEndpoint() . '/' . urlencode($this->id), $this->jsonWithNamespace());
if ($result === 200) {
return true;
}
return $this->selfFromResponse($result);
} | php | public function update()
{
$result = $this->connection()->patch($this->getEndpoint() . '/' . urlencode($this->id), $this->jsonWithNamespace());
if ($result === 200) {
return true;
}
return $this->selfFromResponse($result);
} | [
"public",
"function",
"update",
"(",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"connection",
"(",
")",
"->",
"patch",
"(",
"$",
"this",
"->",
"getEndpoint",
"(",
")",
".",
"'/'",
".",
"urlencode",
"(",
"$",
"this",
"->",
"id",
")",
",",
"$... | @return mixed
@throws \Picqer\Financials\Moneybird\Exceptions\ApiException | [
"@return",
"mixed"
] | train | https://github.com/picqer/moneybird-php-client/blob/15c57f25ad29e34201f18d83faa489611c7e5594/src/Picqer/Financials/Moneybird/Actions/Storable.php#L43-L51 |
kassner/log-parser | src/Kassner/LogParser/LogParser.php | LogParser.parse | public function parse($line)
{
if (!preg_match($this->pcreFormat, $line, $matches)) {
throw new FormatException($line);
}
$entry = $this->createEntry();
foreach (array_filter(array_keys($matches), 'is_string') as $key) {
if ('time' === $key && true !== $stamp = strtotime($matches[$key])) {
$entry->stamp = $stamp;
}
$entry->{$key} = $matches[$key];
}
return $entry;
} | php | public function parse($line)
{
if (!preg_match($this->pcreFormat, $line, $matches)) {
throw new FormatException($line);
}
$entry = $this->createEntry();
foreach (array_filter(array_keys($matches), 'is_string') as $key) {
if ('time' === $key && true !== $stamp = strtotime($matches[$key])) {
$entry->stamp = $stamp;
}
$entry->{$key} = $matches[$key];
}
return $entry;
} | [
"public",
"function",
"parse",
"(",
"$",
"line",
")",
"{",
"if",
"(",
"!",
"preg_match",
"(",
"$",
"this",
"->",
"pcreFormat",
",",
"$",
"line",
",",
"$",
"matches",
")",
")",
"{",
"throw",
"new",
"FormatException",
"(",
"$",
"line",
")",
";",
"}",... | Parses one single log line.
@param string $line
@return \stdClass
@throws FormatException | [
"Parses",
"one",
"single",
"log",
"line",
"."
] | train | https://github.com/kassner/log-parser/blob/ea846b7edf24a421c5484902b2501c9c8e065796/src/Kassner/LogParser/LogParser.php#L100-L117 |
vaimo/composer-patches | src/Composer/Commands/PatchCommand.php | PatchCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$configDefaults = new \Vaimo\ComposerPatches\Config\Defaults();
$defaults = $configDefaults->getPatcherConfig();
$composer = $this->getComposer();
$appIO = $this->getIO();
$isExplicit = $input->getOption('explicit') || $input->getOption('show-reapplies');
$isDevMode = !$input->getOption('no-dev');
$behaviourFlags = $this->getBehaviourFlags($input);
$shouldUndo = !$behaviourFlags['redo'] && $behaviourFlags['undo'];
$bootstrapFactory = new \Vaimo\ComposerPatches\Factories\BootstrapFactory($composer, $appIO);
$filters = array(
Patch::SOURCE => $input->getOption('filter'),
Patch::TARGETS => $input->getArgument('targets')
);
$configFactory = new \Vaimo\ComposerPatches\Factories\ConfigFactory($composer, array(
Config::PATCHER_FORCE_REAPPLY => $behaviourFlags['redo'],
Config::PATCHER_FROM_SOURCE => (bool)$input->getOption('from-source'),
Config::PATCHER_GRACEFUL => (bool)$input->getOption('graceful')
|| $behaviourFlags['redo']
|| $behaviourFlags['undo'],
Config::PATCHER_SOURCES => array_fill_keys(array_keys($defaults[Config::PATCHER_SOURCES]), true)
));
if ($behaviourFlags['redo'] && !array_filter($filters)) {
$isExplicit = true;
}
$hasFilers = (bool)array_filter($filters);
if (!$hasFilers && $behaviourFlags['redo']) {
$filters[Patch::SOURCE] = array('*');
}
$listResolver = new ListResolvers\FilteredListResolver($filters);
if ($shouldUndo) {
$listResolver = new ListResolvers\InvertedListResolver($listResolver);
} else {
$listResolver = new ListResolvers\InclusiveListResolver($listResolver);
}
if (!$behaviourFlags['redo'] && !$behaviourFlags['undo']) {
$listResolver = new ListResolvers\ChangesListResolver($listResolver);
}
$runtimeUtils = new \Vaimo\ComposerPatches\Utils\RuntimeUtils();
$outputTriggerFlags = array(
Patch::STATUS_NEW => !$hasFilers,
Patch::STATUS_CHANGED => !$hasFilers,
Patch::STATUS_MATCH => true,
Patch::SOURCE => $isExplicit,
Patch::URL => $isExplicit
);
$outputTriggers = array_keys(
array_filter($outputTriggerFlags)
);
$outputStrategy = new \Vaimo\ComposerPatches\Strategies\OutputStrategy($outputTriggers);
$bootstrap = $bootstrapFactory->create($configFactory, $listResolver, $outputStrategy);
$runtimeUtils->setEnvironmentValues(array(
Environment::FORCE_RESET => (int)(bool)$input->getOption('force')
));
if ($shouldUndo && !array_filter($filters)) {
$bootstrap->stripPatches($isDevMode);
} else {
$lockSanitizer = new \Vaimo\ComposerPatches\Repository\Lock\Sanitizer($appIO);
$bootstrap->applyPatches($isDevMode);
$lockSanitizer->sanitize();
}
$composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_INSTALL_CMD, $isDevMode);
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$configDefaults = new \Vaimo\ComposerPatches\Config\Defaults();
$defaults = $configDefaults->getPatcherConfig();
$composer = $this->getComposer();
$appIO = $this->getIO();
$isExplicit = $input->getOption('explicit') || $input->getOption('show-reapplies');
$isDevMode = !$input->getOption('no-dev');
$behaviourFlags = $this->getBehaviourFlags($input);
$shouldUndo = !$behaviourFlags['redo'] && $behaviourFlags['undo'];
$bootstrapFactory = new \Vaimo\ComposerPatches\Factories\BootstrapFactory($composer, $appIO);
$filters = array(
Patch::SOURCE => $input->getOption('filter'),
Patch::TARGETS => $input->getArgument('targets')
);
$configFactory = new \Vaimo\ComposerPatches\Factories\ConfigFactory($composer, array(
Config::PATCHER_FORCE_REAPPLY => $behaviourFlags['redo'],
Config::PATCHER_FROM_SOURCE => (bool)$input->getOption('from-source'),
Config::PATCHER_GRACEFUL => (bool)$input->getOption('graceful')
|| $behaviourFlags['redo']
|| $behaviourFlags['undo'],
Config::PATCHER_SOURCES => array_fill_keys(array_keys($defaults[Config::PATCHER_SOURCES]), true)
));
if ($behaviourFlags['redo'] && !array_filter($filters)) {
$isExplicit = true;
}
$hasFilers = (bool)array_filter($filters);
if (!$hasFilers && $behaviourFlags['redo']) {
$filters[Patch::SOURCE] = array('*');
}
$listResolver = new ListResolvers\FilteredListResolver($filters);
if ($shouldUndo) {
$listResolver = new ListResolvers\InvertedListResolver($listResolver);
} else {
$listResolver = new ListResolvers\InclusiveListResolver($listResolver);
}
if (!$behaviourFlags['redo'] && !$behaviourFlags['undo']) {
$listResolver = new ListResolvers\ChangesListResolver($listResolver);
}
$runtimeUtils = new \Vaimo\ComposerPatches\Utils\RuntimeUtils();
$outputTriggerFlags = array(
Patch::STATUS_NEW => !$hasFilers,
Patch::STATUS_CHANGED => !$hasFilers,
Patch::STATUS_MATCH => true,
Patch::SOURCE => $isExplicit,
Patch::URL => $isExplicit
);
$outputTriggers = array_keys(
array_filter($outputTriggerFlags)
);
$outputStrategy = new \Vaimo\ComposerPatches\Strategies\OutputStrategy($outputTriggers);
$bootstrap = $bootstrapFactory->create($configFactory, $listResolver, $outputStrategy);
$runtimeUtils->setEnvironmentValues(array(
Environment::FORCE_RESET => (int)(bool)$input->getOption('force')
));
if ($shouldUndo && !array_filter($filters)) {
$bootstrap->stripPatches($isDevMode);
} else {
$lockSanitizer = new \Vaimo\ComposerPatches\Repository\Lock\Sanitizer($appIO);
$bootstrap->applyPatches($isDevMode);
$lockSanitizer->sanitize();
}
$composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_INSTALL_CMD, $isDevMode);
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"configDefaults",
"=",
"new",
"\\",
"Vaimo",
"\\",
"ComposerPatches",
"\\",
"Config",
"\\",
"Defaults",
"(",
")",
";",
"$",
"defaul... | @SuppressWarnings(PHPMD.UnusedFormalParameter)
@param InputInterface $input
@param OutputInterface $output
@return int|void|null | [
"@SuppressWarnings",
"(",
"PHPMD",
".",
"UnusedFormalParameter",
")"
] | train | https://github.com/vaimo/composer-patches/blob/ad127823452de89508070daee3f159225800f0da/src/Composer/Commands/PatchCommand.php#L114-L200 |
vaimo/composer-patches | src/Package/InfoResolver.php | InfoResolver.getSourcePath | public function getSourcePath(PackageInterface $package)
{
return !$package instanceof \Composer\Package\RootPackage
? $this->installationManager->getInstallPath($package)
: realpath(dirname(\Composer\Factory::getComposerFile()));
} | php | public function getSourcePath(PackageInterface $package)
{
return !$package instanceof \Composer\Package\RootPackage
? $this->installationManager->getInstallPath($package)
: realpath(dirname(\Composer\Factory::getComposerFile()));
} | [
"public",
"function",
"getSourcePath",
"(",
"PackageInterface",
"$",
"package",
")",
"{",
"return",
"!",
"$",
"package",
"instanceof",
"\\",
"Composer",
"\\",
"Package",
"\\",
"RootPackage",
"?",
"$",
"this",
"->",
"installationManager",
"->",
"getInstallPath",
... | @SuppressWarnings(PHPMD.StaticAccess)
@param PackageInterface $package
@return bool|string | [
"@SuppressWarnings",
"(",
"PHPMD",
".",
"StaticAccess",
")"
] | train | https://github.com/vaimo/composer-patches/blob/ad127823452de89508070daee3f159225800f0da/src/Package/InfoResolver.php#L50-L55 |
vaimo/composer-patches | src/Utils/PatchListUtils.php | PatchListUtils.embedInfoToItems | public function embedInfoToItems(array $patches, $update, $onlyNew = false)
{
foreach ($patches as $target => $group) {
foreach (array_keys($group) as $path) {
$patches[$target][$path] = is_array($update)
? array_replace(
$patches[$target][$path],
$onlyNew ? array_diff_key($update, array_filter($patches[$target][$path])) : $update
)
: $update;
}
}
return $patches;
} | php | public function embedInfoToItems(array $patches, $update, $onlyNew = false)
{
foreach ($patches as $target => $group) {
foreach (array_keys($group) as $path) {
$patches[$target][$path] = is_array($update)
? array_replace(
$patches[$target][$path],
$onlyNew ? array_diff_key($update, array_filter($patches[$target][$path])) : $update
)
: $update;
}
}
return $patches;
} | [
"public",
"function",
"embedInfoToItems",
"(",
"array",
"$",
"patches",
",",
"$",
"update",
",",
"$",
"onlyNew",
"=",
"false",
")",
"{",
"foreach",
"(",
"$",
"patches",
"as",
"$",
"target",
"=>",
"$",
"group",
")",
"{",
"foreach",
"(",
"array_keys",
"(... | @SuppressWarnings(PHPMD.BooleanArgumentFlag)
@param array $patches
@param array|bool|string $update
@param bool $onlyNew
@return array | [
"@SuppressWarnings",
"(",
"PHPMD",
".",
"BooleanArgumentFlag",
")"
] | train | https://github.com/vaimo/composer-patches/blob/ad127823452de89508070daee3f159225800f0da/src/Utils/PatchListUtils.php#L263-L277 |
vaimo/composer-patches | src/Managers/RepositoryManager.php | RepositoryManager.resetPackage | public function resetPackage(WritableRepositoryInterface $repository, PackageInterface $package)
{
$verbosityLevel = OutputUtils::resetVerbosity($this->appIO, OutputInterface::VERBOSITY_QUIET);
$operation = new ResetOperation($package, 'Package reset due to changes in patches configuration');
if (!$this->packageResetStrategy->shouldAllowReset($package)) {
OutputUtils::resetVerbosity($this->appIO, $verbosityLevel);
throw new \Vaimo\ComposerPatches\Exceptions\PackageResetException(
sprintf('Package reset halted due to encountering local changes: %s', $package->getName())
);
}
try {
$this->installer->install($repository, $operation);
} catch (\Exception $exception) {
OutputUtils::resetVerbosity($this->appIO, $verbosityLevel);
throw $exception;
}
OutputUtils::resetVerbosity($this->appIO, $verbosityLevel);
} | php | public function resetPackage(WritableRepositoryInterface $repository, PackageInterface $package)
{
$verbosityLevel = OutputUtils::resetVerbosity($this->appIO, OutputInterface::VERBOSITY_QUIET);
$operation = new ResetOperation($package, 'Package reset due to changes in patches configuration');
if (!$this->packageResetStrategy->shouldAllowReset($package)) {
OutputUtils::resetVerbosity($this->appIO, $verbosityLevel);
throw new \Vaimo\ComposerPatches\Exceptions\PackageResetException(
sprintf('Package reset halted due to encountering local changes: %s', $package->getName())
);
}
try {
$this->installer->install($repository, $operation);
} catch (\Exception $exception) {
OutputUtils::resetVerbosity($this->appIO, $verbosityLevel);
throw $exception;
}
OutputUtils::resetVerbosity($this->appIO, $verbosityLevel);
} | [
"public",
"function",
"resetPackage",
"(",
"WritableRepositoryInterface",
"$",
"repository",
",",
"PackageInterface",
"$",
"package",
")",
"{",
"$",
"verbosityLevel",
"=",
"OutputUtils",
"::",
"resetVerbosity",
"(",
"$",
"this",
"->",
"appIO",
",",
"OutputInterface"... | @SuppressWarnings(PHPMD.StaticAccess)
@param WritableRepositoryInterface $repository
@param PackageInterface $package
@throws \Vaimo\ComposerPatches\Exceptions\PackageResetException | [
"@SuppressWarnings",
"(",
"PHPMD",
".",
"StaticAccess",
")"
] | train | https://github.com/vaimo/composer-patches/blob/ad127823452de89508070daee3f159225800f0da/src/Managers/RepositoryManager.php#L54-L77 |
vaimo/composer-patches | src/Managers/LockerManager.php | LockerManager.getLockFile | private function getLockFile()
{
$composerFile = \Composer\Factory::getComposerFile();
$lockFile = 'json' === pathinfo($composerFile, PATHINFO_EXTENSION)
? substr($composerFile, 0, -4) . 'lock'
: $composerFile . '.lock';
return new \Composer\Json\JsonFile($lockFile, null, $this->appIO);
} | php | private function getLockFile()
{
$composerFile = \Composer\Factory::getComposerFile();
$lockFile = 'json' === pathinfo($composerFile, PATHINFO_EXTENSION)
? substr($composerFile, 0, -4) . 'lock'
: $composerFile . '.lock';
return new \Composer\Json\JsonFile($lockFile, null, $this->appIO);
} | [
"private",
"function",
"getLockFile",
"(",
")",
"{",
"$",
"composerFile",
"=",
"\\",
"Composer",
"\\",
"Factory",
"::",
"getComposerFile",
"(",
")",
";",
"$",
"lockFile",
"=",
"'json'",
"===",
"pathinfo",
"(",
"$",
"composerFile",
",",
"PATHINFO_EXTENSION",
... | @SuppressWarnings(PHPMD.StaticAccess)
@return \Composer\Json\JsonFile | [
"@SuppressWarnings",
"(",
"PHPMD",
".",
"StaticAccess",
")"
] | train | https://github.com/vaimo/composer-patches/blob/ad127823452de89508070daee3f159225800f0da/src/Managers/LockerManager.php#L51-L60 |
vaimo/composer-patches | src/Shell.php | Shell.execute | public function execute($command, $cwd = null)
{
if (strpos($command, '<') === 0) {
return array(true, trim($command, '< '));
}
$processExecutor = $this->getProcessExecutor();
$logger = $this->logger;
$output = '';
$outputHandler = function ($type, $data) use ($logger, &$output) {
$output .= $data;
$logger->writeVerbose('comment', trim($data));
};
if ($this->logger->getOutputInstance()->isVerbose()) {
$this->logger->writeIndentation();
}
$result = $processExecutor->execute($command, $outputHandler, $cwd);
return array($result === 0, $output);
} | php | public function execute($command, $cwd = null)
{
if (strpos($command, '<') === 0) {
return array(true, trim($command, '< '));
}
$processExecutor = $this->getProcessExecutor();
$logger = $this->logger;
$output = '';
$outputHandler = function ($type, $data) use ($logger, &$output) {
$output .= $data;
$logger->writeVerbose('comment', trim($data));
};
if ($this->logger->getOutputInstance()->isVerbose()) {
$this->logger->writeIndentation();
}
$result = $processExecutor->execute($command, $outputHandler, $cwd);
return array($result === 0, $output);
} | [
"public",
"function",
"execute",
"(",
"$",
"command",
",",
"$",
"cwd",
"=",
"null",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"command",
",",
"'<'",
")",
"===",
"0",
")",
"{",
"return",
"array",
"(",
"true",
",",
"trim",
"(",
"$",
"command",
",",
... | @SuppressWarnings(PHPMD.UnusedLocalVariable)
@param string $command
@param null|string $cwd
@return array | [
"@SuppressWarnings",
"(",
"PHPMD",
".",
"UnusedLocalVariable",
")"
] | train | https://github.com/vaimo/composer-patches/blob/ad127823452de89508070daee3f159225800f0da/src/Shell.php#L36-L61 |
vaimo/composer-patches | src/Repository/PatchesApplier.php | PatchesApplier.apply | public function apply(Repository $repository, array $patches)
{
$packages = $this->packageCollector->collect($repository);
$packagesUpdated = false;
$repositoryState = $this->repositoryStateGenerator->generate($repository);
$applyQueue = $this->queueGenerator->generateApplyQueue($patches, $repositoryState);
$removeQueue = $this->queueGenerator->generateRemovalQueue($applyQueue, $repositoryState);
$resetQueue = $this->queueGenerator->generateResetQueue($applyQueue);
$applyQueue = array_map('array_filter', $applyQueue);
$patchQueueFootprints = $this->patchListUtils->createSimplifiedList($applyQueue);
$labels = array_diff_key($this->statusConfig->getLabels(), array('unknown' => true));
$applyQueue = $this->updateStatusLabels($applyQueue, $labels);
$removeQueue = $this->updateStatusLabels($removeQueue, $labels);
foreach ($packages as $packageName => $package) {
$hasPatches = !empty($applyQueue[$packageName]);
$patchTargets = $hasPatches ?
$this->patchListUtils->getAllTargets(array($applyQueue[$packageName]))
: array($packageName);
$itemsToReset = array_intersect($resetQueue, $patchTargets);
$resetResult = array();
foreach ($itemsToReset as $targetName) {
$resetTarget = $packages[$targetName];
$resetPatches = $this->packageUtils->resetAppliedPatches($resetTarget);
$resetResult[$targetName] = is_array($resetPatches) ? $resetPatches : array();
if (!$hasPatches && $resetPatches && !isset($patchQueueFootprints[$targetName])) {
$this->logger->writeRaw(
'Resetting patched for <info>%s</info> (%s)',
array($targetName, count($resetResult[$targetName]))
);
}
$this->repositoryManager->resetPackage($repository, $resetTarget);
$packagesUpdated = $packagesUpdated || (bool)$resetResult[$targetName];
}
$resetQueue = array_diff($resetQueue, $patchTargets);
if (!$hasPatches) {
continue;
}
$changesMap = array();
foreach ($patchTargets as $targetName) {
$targetQueue = array();
if (isset($patchQueueFootprints[$targetName])) {
$targetQueue = $patchQueueFootprints[$targetName];
}
if (!isset($packages[$targetName])) {
throw new \Vaimo\ComposerPatches\Exceptions\PackageNotFound(
sprintf(
'Unknown target "%s" encountered when checking patch changes for: %s',
$targetName,
implode(',', array_keys($targetQueue))
)
);
}
$changesMap[$targetName] = $this->packageUtils->hasPatchChanges(
$packages[$targetName],
$targetQueue
);
}
$changedTargets = array_keys(array_filter($changesMap));
if (!$changedTargets) {
continue;
}
$queuedPatches = array_filter(
$applyQueue[$packageName],
function ($data) use ($changedTargets) {
return array_intersect($data[Patch::TARGETS], $changedTargets);
}
);
$muteDepth = null;
$patchRemovals = isset($removeQueue[$packageName])
? $removeQueue[$packageName]
: array();
if (!$this->shouldAllowOutput($queuedPatches, $patchRemovals)) {
$muteDepth = $this->logger->mute();
}
try {
$this->logger->writeRaw(
'Applying patches for <info>%s</info> (%s)',
array($packageName, count($queuedPatches))
);
if ($patchRemovals) {
$processIndentation = $this->logger->push('~');
foreach ($patchRemovals as $item) {
$this->patchInfoLogger->outputPatchInfo($item);
}
$this->logger->reset($processIndentation);
}
$this->processPatchesForPackage($repository, $package, $queuedPatches);
} catch (\Exception $exception) {
$this->logger->unMute();
throw $exception;
}
$packagesUpdated = true;
$this->logger->writeNewLine();
if ($muteDepth !== null) {
$this->logger->unMute($muteDepth);
}
}
return $packagesUpdated;
} | php | public function apply(Repository $repository, array $patches)
{
$packages = $this->packageCollector->collect($repository);
$packagesUpdated = false;
$repositoryState = $this->repositoryStateGenerator->generate($repository);
$applyQueue = $this->queueGenerator->generateApplyQueue($patches, $repositoryState);
$removeQueue = $this->queueGenerator->generateRemovalQueue($applyQueue, $repositoryState);
$resetQueue = $this->queueGenerator->generateResetQueue($applyQueue);
$applyQueue = array_map('array_filter', $applyQueue);
$patchQueueFootprints = $this->patchListUtils->createSimplifiedList($applyQueue);
$labels = array_diff_key($this->statusConfig->getLabels(), array('unknown' => true));
$applyQueue = $this->updateStatusLabels($applyQueue, $labels);
$removeQueue = $this->updateStatusLabels($removeQueue, $labels);
foreach ($packages as $packageName => $package) {
$hasPatches = !empty($applyQueue[$packageName]);
$patchTargets = $hasPatches ?
$this->patchListUtils->getAllTargets(array($applyQueue[$packageName]))
: array($packageName);
$itemsToReset = array_intersect($resetQueue, $patchTargets);
$resetResult = array();
foreach ($itemsToReset as $targetName) {
$resetTarget = $packages[$targetName];
$resetPatches = $this->packageUtils->resetAppliedPatches($resetTarget);
$resetResult[$targetName] = is_array($resetPatches) ? $resetPatches : array();
if (!$hasPatches && $resetPatches && !isset($patchQueueFootprints[$targetName])) {
$this->logger->writeRaw(
'Resetting patched for <info>%s</info> (%s)',
array($targetName, count($resetResult[$targetName]))
);
}
$this->repositoryManager->resetPackage($repository, $resetTarget);
$packagesUpdated = $packagesUpdated || (bool)$resetResult[$targetName];
}
$resetQueue = array_diff($resetQueue, $patchTargets);
if (!$hasPatches) {
continue;
}
$changesMap = array();
foreach ($patchTargets as $targetName) {
$targetQueue = array();
if (isset($patchQueueFootprints[$targetName])) {
$targetQueue = $patchQueueFootprints[$targetName];
}
if (!isset($packages[$targetName])) {
throw new \Vaimo\ComposerPatches\Exceptions\PackageNotFound(
sprintf(
'Unknown target "%s" encountered when checking patch changes for: %s',
$targetName,
implode(',', array_keys($targetQueue))
)
);
}
$changesMap[$targetName] = $this->packageUtils->hasPatchChanges(
$packages[$targetName],
$targetQueue
);
}
$changedTargets = array_keys(array_filter($changesMap));
if (!$changedTargets) {
continue;
}
$queuedPatches = array_filter(
$applyQueue[$packageName],
function ($data) use ($changedTargets) {
return array_intersect($data[Patch::TARGETS], $changedTargets);
}
);
$muteDepth = null;
$patchRemovals = isset($removeQueue[$packageName])
? $removeQueue[$packageName]
: array();
if (!$this->shouldAllowOutput($queuedPatches, $patchRemovals)) {
$muteDepth = $this->logger->mute();
}
try {
$this->logger->writeRaw(
'Applying patches for <info>%s</info> (%s)',
array($packageName, count($queuedPatches))
);
if ($patchRemovals) {
$processIndentation = $this->logger->push('~');
foreach ($patchRemovals as $item) {
$this->patchInfoLogger->outputPatchInfo($item);
}
$this->logger->reset($processIndentation);
}
$this->processPatchesForPackage($repository, $package, $queuedPatches);
} catch (\Exception $exception) {
$this->logger->unMute();
throw $exception;
}
$packagesUpdated = true;
$this->logger->writeNewLine();
if ($muteDepth !== null) {
$this->logger->unMute($muteDepth);
}
}
return $packagesUpdated;
} | [
"public",
"function",
"apply",
"(",
"Repository",
"$",
"repository",
",",
"array",
"$",
"patches",
")",
"{",
"$",
"packages",
"=",
"$",
"this",
"->",
"packageCollector",
"->",
"collect",
"(",
"$",
"repository",
")",
";",
"$",
"packagesUpdated",
"=",
"false... | @SuppressWarnings(PHPMD.ExcessiveMethodLength)
@SuppressWarnings(PHPMD.NPathComplexity)
@SuppressWarnings(PHPMD.CyclomaticComplexity)
@param Repository $repository
@param array $patches
@return bool
@throws \Vaimo\ComposerPatches\Exceptions\PackageNotFound
@throws \Vaimo\ComposerPatches\Exceptions\PackageResetException | [
"@SuppressWarnings",
"(",
"PHPMD",
".",
"ExcessiveMethodLength",
")",
"@SuppressWarnings",
"(",
"PHPMD",
".",
"NPathComplexity",
")",
"@SuppressWarnings",
"(",
"PHPMD",
".",
"CyclomaticComplexity",
")"
] | train | https://github.com/vaimo/composer-patches/blob/ad127823452de89508070daee3f159225800f0da/src/Repository/PatchesApplier.php#L141-L278 |
vaimo/composer-patches | src/Factories/PatchesLoaderFactory.php | PatchesLoaderFactory.create | public function create(LoaderComponents $loaderComponentsPool, PluginConfig $pluginConfig, $devMode = false)
{
$composer = $this->composer;
$installationManager = $composer->getInstallationManager();
$rootPackage = $composer->getPackage();
$composerConfig = clone $composer->getConfig();
$patcherConfig = $pluginConfig->getPatcherConfig();
$composerConfig->merge(array(
'config' => array('secure-http' => $patcherConfig[PluginConfig::PATCHER_SECURE_HTTP])
));
$loaders = array(
PluginConfig::DEFINITIONS_LIST => new SourceLoaders\PatchList(),
PluginConfig::DEFINITIONS_FILE => new SourceLoaders\PatchesFile($installationManager),
PluginConfig::DEFINITIONS_SEARCH => new SourceLoaders\PatchesSearch(
$installationManager,
$devMode
)
);
if ($devMode) {
$loaders = array_replace($loaders, array(
PluginConfig::DEV_DEFINITIONS_LIST => $loaders[PluginConfig::DEFINITIONS_LIST],
PluginConfig::DEV_DEFINITIONS_FILE => $loaders[PluginConfig::DEFINITIONS_FILE]
));
}
$exploderComponents = array(
new ExploderComponents\LabelVersionConfigComponent(),
new ExploderComponents\VersionConfigComponent(),
new ExploderComponents\VersionRangesConfigComponent(),
new ExploderComponents\ComplexItemComponent(),
new ExploderComponents\SequenceVersionConfigComponent(),
new ExploderComponents\SequenceItemComponent(),
new ExploderComponents\GroupVersionConfigComponent()
);
$definitionExploder = new Patch\Definition\Exploder($exploderComponents);
$normalizerComponents = array(
new NormalizerComponents\DefaultValuesComponent(),
new NormalizerComponents\BaseComponent(),
new NormalizerComponents\DependencyComponent(),
new NormalizerComponents\PathComponent(),
new NormalizerComponents\BasePathComponent(),
new NormalizerComponents\UrlComponent(),
new NormalizerComponents\SkipComponent(),
new NormalizerComponents\SequenceComponent(),
new NormalizerComponents\PatcherConfigComponent()
);
$definitionNormalizer = new Patch\Definition\Normalizer($normalizerComponents);
$listNormalizer = new Patch\ListNormalizer(
$definitionExploder,
$definitionNormalizer
);
$configReaderFactory = new \Vaimo\ComposerPatches\Factories\PatcherConfigReaderFactory(
$this->composer
);
$configReader = $configReaderFactory->create($pluginConfig);
$patchesCollector = new Patch\Collector(
$listNormalizer,
$configReader,
$loaders
);
$loaderComponents = $loaderComponentsPool->getList($pluginConfig);
$srcResolverFactory = new \Vaimo\ComposerPatches\Factories\SourcesResolverFactory(
$this->composer
);
return new \Vaimo\ComposerPatches\Patch\DefinitionList\Loader(
new \Vaimo\ComposerPatches\Package\Collector(
array($rootPackage)
),
$patchesCollector,
$srcResolverFactory->create($pluginConfig),
$loaderComponents
);
} | php | public function create(LoaderComponents $loaderComponentsPool, PluginConfig $pluginConfig, $devMode = false)
{
$composer = $this->composer;
$installationManager = $composer->getInstallationManager();
$rootPackage = $composer->getPackage();
$composerConfig = clone $composer->getConfig();
$patcherConfig = $pluginConfig->getPatcherConfig();
$composerConfig->merge(array(
'config' => array('secure-http' => $patcherConfig[PluginConfig::PATCHER_SECURE_HTTP])
));
$loaders = array(
PluginConfig::DEFINITIONS_LIST => new SourceLoaders\PatchList(),
PluginConfig::DEFINITIONS_FILE => new SourceLoaders\PatchesFile($installationManager),
PluginConfig::DEFINITIONS_SEARCH => new SourceLoaders\PatchesSearch(
$installationManager,
$devMode
)
);
if ($devMode) {
$loaders = array_replace($loaders, array(
PluginConfig::DEV_DEFINITIONS_LIST => $loaders[PluginConfig::DEFINITIONS_LIST],
PluginConfig::DEV_DEFINITIONS_FILE => $loaders[PluginConfig::DEFINITIONS_FILE]
));
}
$exploderComponents = array(
new ExploderComponents\LabelVersionConfigComponent(),
new ExploderComponents\VersionConfigComponent(),
new ExploderComponents\VersionRangesConfigComponent(),
new ExploderComponents\ComplexItemComponent(),
new ExploderComponents\SequenceVersionConfigComponent(),
new ExploderComponents\SequenceItemComponent(),
new ExploderComponents\GroupVersionConfigComponent()
);
$definitionExploder = new Patch\Definition\Exploder($exploderComponents);
$normalizerComponents = array(
new NormalizerComponents\DefaultValuesComponent(),
new NormalizerComponents\BaseComponent(),
new NormalizerComponents\DependencyComponent(),
new NormalizerComponents\PathComponent(),
new NormalizerComponents\BasePathComponent(),
new NormalizerComponents\UrlComponent(),
new NormalizerComponents\SkipComponent(),
new NormalizerComponents\SequenceComponent(),
new NormalizerComponents\PatcherConfigComponent()
);
$definitionNormalizer = new Patch\Definition\Normalizer($normalizerComponents);
$listNormalizer = new Patch\ListNormalizer(
$definitionExploder,
$definitionNormalizer
);
$configReaderFactory = new \Vaimo\ComposerPatches\Factories\PatcherConfigReaderFactory(
$this->composer
);
$configReader = $configReaderFactory->create($pluginConfig);
$patchesCollector = new Patch\Collector(
$listNormalizer,
$configReader,
$loaders
);
$loaderComponents = $loaderComponentsPool->getList($pluginConfig);
$srcResolverFactory = new \Vaimo\ComposerPatches\Factories\SourcesResolverFactory(
$this->composer
);
return new \Vaimo\ComposerPatches\Patch\DefinitionList\Loader(
new \Vaimo\ComposerPatches\Package\Collector(
array($rootPackage)
),
$patchesCollector,
$srcResolverFactory->create($pluginConfig),
$loaderComponents
);
} | [
"public",
"function",
"create",
"(",
"LoaderComponents",
"$",
"loaderComponentsPool",
",",
"PluginConfig",
"$",
"pluginConfig",
",",
"$",
"devMode",
"=",
"false",
")",
"{",
"$",
"composer",
"=",
"$",
"this",
"->",
"composer",
";",
"$",
"installationManager",
"... | @SuppressWarnings(PHPMD.BooleanArgumentFlag)
@param LoaderComponents $loaderComponentsPool
@param PluginConfig $pluginConfig
@param bool $devMode
@return Patch\DefinitionList\Loader | [
"@SuppressWarnings",
"(",
"PHPMD",
".",
"BooleanArgumentFlag",
")"
] | train | https://github.com/vaimo/composer-patches/blob/ad127823452de89508070daee3f159225800f0da/src/Factories/PatchesLoaderFactory.php#L39-L127 |
ignited/laravel-omnipay | src/Ignited/LaravelOmnipay/BaseServiceProvider.php | BaseServiceProvider.registerManager | public function registerManager()
{
$this->app->singleton('omnipay', function ($app) {
$factory = new GatewayFactory;
$manager = new LaravelOmnipayManager($app, $factory);
return $manager;
});
} | php | public function registerManager()
{
$this->app->singleton('omnipay', function ($app) {
$factory = new GatewayFactory;
$manager = new LaravelOmnipayManager($app, $factory);
return $manager;
});
} | [
"public",
"function",
"registerManager",
"(",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"singleton",
"(",
"'omnipay'",
",",
"function",
"(",
"$",
"app",
")",
"{",
"$",
"factory",
"=",
"new",
"GatewayFactory",
";",
"$",
"manager",
"=",
"new",
"LaravelOmni... | Register the Omnipay manager | [
"Register",
"the",
"Omnipay",
"manager"
] | train | https://github.com/ignited/laravel-omnipay/blob/4c3a6a0787770e55f6b761f2f4c1cbf774d8175a/src/Ignited/LaravelOmnipay/BaseServiceProvider.php#L28-L36 |
ignited/laravel-omnipay | src/Ignited/LaravelOmnipay/LaravelOmnipayManager.php | LaravelOmnipayManager.gateway | public function gateway($name = null)
{
$name = $name ?: $this->getGateway();
if ( ! isset($this->gateways[$name]))
{
$this->gateways[$name] = $this->resolve($name);
}
return $this->gateways[$name];
} | php | public function gateway($name = null)
{
$name = $name ?: $this->getGateway();
if ( ! isset($this->gateways[$name]))
{
$this->gateways[$name] = $this->resolve($name);
}
return $this->gateways[$name];
} | [
"public",
"function",
"gateway",
"(",
"$",
"name",
"=",
"null",
")",
"{",
"$",
"name",
"=",
"$",
"name",
"?",
":",
"$",
"this",
"->",
"getGateway",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"gateways",
"[",
"$",
"name",
"]... | Get an instance of the specified gateway
@param index of config array to use
@return Omnipay\Common\AbstractGateway | [
"Get",
"an",
"instance",
"of",
"the",
"specified",
"gateway"
] | train | https://github.com/ignited/laravel-omnipay/blob/4c3a6a0787770e55f6b761f2f4c1cbf774d8175a/src/Ignited/LaravelOmnipay/LaravelOmnipayManager.php#L58-L68 |
dwightwatson/active | src/Active.php | Active.isActive | public function isActive($routes)
{
$routes = is_array($routes) ? $routes : func_get_args();
list($routes, $ignoredRoutes) = $this->parseIgnoredRoutes($routes);
if ($this->isPath($routes) || $this->isFullPath($routes) || $this->isRoute($routes)) {
if (count($ignoredRoutes) && ($this->isPath($ignoredRoutes) || $this->isFullPath($routes) || $this->isRoute($ignoredRoutes))) {
return false;
}
return true;
}
return false;
} | php | public function isActive($routes)
{
$routes = is_array($routes) ? $routes : func_get_args();
list($routes, $ignoredRoutes) = $this->parseIgnoredRoutes($routes);
if ($this->isPath($routes) || $this->isFullPath($routes) || $this->isRoute($routes)) {
if (count($ignoredRoutes) && ($this->isPath($ignoredRoutes) || $this->isFullPath($routes) || $this->isRoute($ignoredRoutes))) {
return false;
}
return true;
}
return false;
} | [
"public",
"function",
"isActive",
"(",
"$",
"routes",
")",
"{",
"$",
"routes",
"=",
"is_array",
"(",
"$",
"routes",
")",
"?",
"$",
"routes",
":",
"func_get_args",
"(",
")",
";",
"list",
"(",
"$",
"routes",
",",
"$",
"ignoredRoutes",
")",
"=",
"$",
... | Determine if any of the provided routes are active.
@param mixed $routes
@return bool | [
"Determine",
"if",
"any",
"of",
"the",
"provided",
"routes",
"are",
"active",
"."
] | train | https://github.com/dwightwatson/active/blob/4faa30a31d2bb870c852ea38330f3fa1c1350f34/src/Active.php#L54-L69 |
dwightwatson/active | src/Active.php | Active.active | public function active($routes, $class = null, $fallbackClass = null)
{
$routes = (array) $routes;
if ($this->isActive($routes)) {
return $this->getActiveClass($class);
}
if ($fallbackClass) {
return $fallbackClass;
}
} | php | public function active($routes, $class = null, $fallbackClass = null)
{
$routes = (array) $routes;
if ($this->isActive($routes)) {
return $this->getActiveClass($class);
}
if ($fallbackClass) {
return $fallbackClass;
}
} | [
"public",
"function",
"active",
"(",
"$",
"routes",
",",
"$",
"class",
"=",
"null",
",",
"$",
"fallbackClass",
"=",
"null",
")",
"{",
"$",
"routes",
"=",
"(",
"array",
")",
"$",
"routes",
";",
"if",
"(",
"$",
"this",
"->",
"isActive",
"(",
"$",
"... | Get the active class if the active path is provided.
@param mixed $routes
@param string $class
@param null $fallbackClass
@return string|null | [
"Get",
"the",
"active",
"class",
"if",
"the",
"active",
"path",
"is",
"provided",
"."
] | train | https://github.com/dwightwatson/active/blob/4faa30a31d2bb870c852ea38330f3fa1c1350f34/src/Active.php#L79-L90 |
dwightwatson/active | src/Active.php | Active.isPath | public function isPath($routes)
{
$routes = is_array($routes) ? $routes : func_get_args();
return call_user_func_array([$this->request, 'is'], $routes);
} | php | public function isPath($routes)
{
$routes = is_array($routes) ? $routes : func_get_args();
return call_user_func_array([$this->request, 'is'], $routes);
} | [
"public",
"function",
"isPath",
"(",
"$",
"routes",
")",
"{",
"$",
"routes",
"=",
"is_array",
"(",
"$",
"routes",
")",
"?",
"$",
"routes",
":",
"func_get_args",
"(",
")",
";",
"return",
"call_user_func_array",
"(",
"[",
"$",
"this",
"->",
"request",
",... | Determine if the current path is one of the provided paths.
@param mixed $routes
@return boolean | [
"Determine",
"if",
"the",
"current",
"path",
"is",
"one",
"of",
"the",
"provided",
"paths",
"."
] | train | https://github.com/dwightwatson/active/blob/4faa30a31d2bb870c852ea38330f3fa1c1350f34/src/Active.php#L98-L103 |
dwightwatson/active | src/Active.php | Active.isFullPath | public function isFullPath($routes)
{
$routes = is_array($routes) ? $routes : func_get_args();
return call_user_func_array([$this->request, 'fullUrlIs'], $routes);
} | php | public function isFullPath($routes)
{
$routes = is_array($routes) ? $routes : func_get_args();
return call_user_func_array([$this->request, 'fullUrlIs'], $routes);
} | [
"public",
"function",
"isFullPath",
"(",
"$",
"routes",
")",
"{",
"$",
"routes",
"=",
"is_array",
"(",
"$",
"routes",
")",
"?",
"$",
"routes",
":",
"func_get_args",
"(",
")",
";",
"return",
"call_user_func_array",
"(",
"[",
"$",
"this",
"->",
"request",
... | Determine if the current full path is one of the provided paths.
@param mixed $routes
@return boolean | [
"Determine",
"if",
"the",
"current",
"full",
"path",
"is",
"one",
"of",
"the",
"provided",
"paths",
"."
] | train | https://github.com/dwightwatson/active/blob/4faa30a31d2bb870c852ea38330f3fa1c1350f34/src/Active.php#L111-L116 |
dwightwatson/active | src/Active.php | Active.path | public function path($routes, $class = null)
{
$routes = (array) $routes;
if ($this->isPath($routes)) {
return $this->getActiveClass($class);
}
} | php | public function path($routes, $class = null)
{
$routes = (array) $routes;
if ($this->isPath($routes)) {
return $this->getActiveClass($class);
}
} | [
"public",
"function",
"path",
"(",
"$",
"routes",
",",
"$",
"class",
"=",
"null",
")",
"{",
"$",
"routes",
"=",
"(",
"array",
")",
"$",
"routes",
";",
"if",
"(",
"$",
"this",
"->",
"isPath",
"(",
"$",
"routes",
")",
")",
"{",
"return",
"$",
"th... | Get the active class if the active path is provided.
@param mixed $routes
@param string $class
@return string|null | [
"Get",
"the",
"active",
"class",
"if",
"the",
"active",
"path",
"is",
"provided",
"."
] | train | https://github.com/dwightwatson/active/blob/4faa30a31d2bb870c852ea38330f3fa1c1350f34/src/Active.php#L125-L132 |
dwightwatson/active | src/Active.php | Active.isRoute | public function isRoute($routes)
{
$routes = is_array($routes) ? $routes : func_get_args();
return call_user_func_array([$this->router, 'is'], $routes);
} | php | public function isRoute($routes)
{
$routes = is_array($routes) ? $routes : func_get_args();
return call_user_func_array([$this->router, 'is'], $routes);
} | [
"public",
"function",
"isRoute",
"(",
"$",
"routes",
")",
"{",
"$",
"routes",
"=",
"is_array",
"(",
"$",
"routes",
")",
"?",
"$",
"routes",
":",
"func_get_args",
"(",
")",
";",
"return",
"call_user_func_array",
"(",
"[",
"$",
"this",
"->",
"router",
",... | Determin if the current route is one of the provided routes.
@param mixed $routes
@return boolean | [
"Determin",
"if",
"the",
"current",
"route",
"is",
"one",
"of",
"the",
"provided",
"routes",
"."
] | train | https://github.com/dwightwatson/active/blob/4faa30a31d2bb870c852ea38330f3fa1c1350f34/src/Active.php#L140-L145 |
dwightwatson/active | src/Active.php | Active.route | public function route($routes, $class = null)
{
$routes = (array) $routes;
if ($this->isRoute($routes)) {
return $this->getActiveClass($class);
}
} | php | public function route($routes, $class = null)
{
$routes = (array) $routes;
if ($this->isRoute($routes)) {
return $this->getActiveClass($class);
}
} | [
"public",
"function",
"route",
"(",
"$",
"routes",
",",
"$",
"class",
"=",
"null",
")",
"{",
"$",
"routes",
"=",
"(",
"array",
")",
"$",
"routes",
";",
"if",
"(",
"$",
"this",
"->",
"isRoute",
"(",
"$",
"routes",
")",
")",
"{",
"return",
"$",
"... | Get the active class if the active route is provided.
@param mixed $routes
@param string $class
@return string|null | [
"Get",
"the",
"active",
"class",
"if",
"the",
"active",
"route",
"is",
"provided",
"."
] | train | https://github.com/dwightwatson/active/blob/4faa30a31d2bb870c852ea38330f3fa1c1350f34/src/Active.php#L154-L161 |
dwightwatson/active | src/Active.php | Active.parseIgnoredRoutes | private function parseIgnoredRoutes($routes)
{
$ignoredRoutes = [];
$routes = is_array($routes) ? $routes : func_get_args();
foreach ($routes as $index => $route) {
if (Str::startsWith($route, 'not:')) {
$ignoredRoute = substr($route, 4);
unset($routes[$index]);
$ignoredRoutes[] = $ignoredRoute;
}
}
return [$routes, $ignoredRoutes];
} | php | private function parseIgnoredRoutes($routes)
{
$ignoredRoutes = [];
$routes = is_array($routes) ? $routes : func_get_args();
foreach ($routes as $index => $route) {
if (Str::startsWith($route, 'not:')) {
$ignoredRoute = substr($route, 4);
unset($routes[$index]);
$ignoredRoutes[] = $ignoredRoute;
}
}
return [$routes, $ignoredRoutes];
} | [
"private",
"function",
"parseIgnoredRoutes",
"(",
"$",
"routes",
")",
"{",
"$",
"ignoredRoutes",
"=",
"[",
"]",
";",
"$",
"routes",
"=",
"is_array",
"(",
"$",
"routes",
")",
"?",
"$",
"routes",
":",
"func_get_args",
"(",
")",
";",
"foreach",
"(",
"$",
... | Separate ignored routes from the provided routes.
@param mixed $routes
@return array | [
"Separate",
"ignored",
"routes",
"from",
"the",
"provided",
"routes",
"."
] | train | https://github.com/dwightwatson/active/blob/4faa30a31d2bb870c852ea38330f3fa1c1350f34/src/Active.php#L181-L198 |
dwightwatson/active | src/Route.php | Route.controller | public function controller($separator = null, $includeNamespace = true, $trimNamespace = 'App\Http\Controllers\\')
{
if ($action = $this->router->currentRouteAction()) {
$separator = is_null($separator) ? ' ' : $separator;
$controller = head(Str::parseCallback($action, null));
// If the controller contains the given namespace, remove it.
if (substr($controller, 0, strlen($trimNamespace)) === $trimNamespace) {
$controller = substr($controller, strlen($trimNamespace));
}
// If the controller contains 'Controller' at the end, remove it.
if (substr($controller, - strlen('Controller')) === 'Controller') {
$controller = substr($controller, 0, - strlen('Controller'));
}
// Separate out nested controller resources.
$controller = str_replace('_', $separator, snake_case($controller));
// Either separate out the namespaces or remove them.
$controller = $includeNamespace ? str_replace('\\', null, $controller) : substr(strrchr($controller, '\\'), 1);
return trim($controller);
}
return null;
} | php | public function controller($separator = null, $includeNamespace = true, $trimNamespace = 'App\Http\Controllers\\')
{
if ($action = $this->router->currentRouteAction()) {
$separator = is_null($separator) ? ' ' : $separator;
$controller = head(Str::parseCallback($action, null));
// If the controller contains the given namespace, remove it.
if (substr($controller, 0, strlen($trimNamespace)) === $trimNamespace) {
$controller = substr($controller, strlen($trimNamespace));
}
// If the controller contains 'Controller' at the end, remove it.
if (substr($controller, - strlen('Controller')) === 'Controller') {
$controller = substr($controller, 0, - strlen('Controller'));
}
// Separate out nested controller resources.
$controller = str_replace('_', $separator, snake_case($controller));
// Either separate out the namespaces or remove them.
$controller = $includeNamespace ? str_replace('\\', null, $controller) : substr(strrchr($controller, '\\'), 1);
return trim($controller);
}
return null;
} | [
"public",
"function",
"controller",
"(",
"$",
"separator",
"=",
"null",
",",
"$",
"includeNamespace",
"=",
"true",
",",
"$",
"trimNamespace",
"=",
"'App\\Http\\Controllers\\\\'",
")",
"{",
"if",
"(",
"$",
"action",
"=",
"$",
"this",
"->",
"router",
"->",
"... | Get the controller name, separated as necessary and with or without namespaces.
@param string $separator
@param bool $includeNamespace
@param string $trimNamespace
@return string|null | [
"Get",
"the",
"controller",
"name",
"separated",
"as",
"necessary",
"and",
"with",
"or",
"without",
"namespaces",
"."
] | train | https://github.com/dwightwatson/active/blob/4faa30a31d2bb870c852ea38330f3fa1c1350f34/src/Route.php#L36-L63 |
dwightwatson/active | src/Route.php | Route.action | public function action($removeHttpMethod = true)
{
if ($action = $this->router->currentRouteAction()) {
$action = last(Str::parseCallback($action, null));
if ($removeHttpMethod) {
$action = str_replace(['get', 'post', 'patch', 'put', 'delete'], '', $action);
}
return Str::snake($action, '-');
}
return null;
} | php | public function action($removeHttpMethod = true)
{
if ($action = $this->router->currentRouteAction()) {
$action = last(Str::parseCallback($action, null));
if ($removeHttpMethod) {
$action = str_replace(['get', 'post', 'patch', 'put', 'delete'], '', $action);
}
return Str::snake($action, '-');
}
return null;
} | [
"public",
"function",
"action",
"(",
"$",
"removeHttpMethod",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"action",
"=",
"$",
"this",
"->",
"router",
"->",
"currentRouteAction",
"(",
")",
")",
"{",
"$",
"action",
"=",
"last",
"(",
"Str",
"::",
"parseCallbac... | Get the current controller action name.
@param bool $removeHttpMethod
@return string|null | [
"Get",
"the",
"current",
"controller",
"action",
"name",
"."
] | train | https://github.com/dwightwatson/active/blob/4faa30a31d2bb870c852ea38330f3fa1c1350f34/src/Route.php#L71-L84 |
povils/phpmnd | src/HintList.php | HintList.getHintsByValue | public function getHintsByValue($magicNumber): array
{
$hints = [];
foreach ($this->constants as $constant) {
if ($constant['value'] === $magicNumber) {
$hints[] = $constant['hint'];
}
}
return $hints;
} | php | public function getHintsByValue($magicNumber): array
{
$hints = [];
foreach ($this->constants as $constant) {
if ($constant['value'] === $magicNumber) {
$hints[] = $constant['hint'];
}
}
return $hints;
} | [
"public",
"function",
"getHintsByValue",
"(",
"$",
"magicNumber",
")",
":",
"array",
"{",
"$",
"hints",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"constants",
"as",
"$",
"constant",
")",
"{",
"if",
"(",
"$",
"constant",
"[",
"'value'",
"... | @param mixed $magicNumber
@return array | [
"@param",
"mixed",
"$magicNumber"
] | train | https://github.com/povils/phpmnd/blob/0471854ac2c3a77354be6eade27137cc05058363/src/HintList.php#L22-L32 |
povils/phpmnd | src/Printer/Xml.php | Xml.getSnippet | private function getSnippet(string $content, int $line, $text): array
{
$content = str_replace(array("\r\n", "\r"), "\n", $content);
$lines = explode("\n", $content);
$lineContent = array_slice($lines, $line-1, 1);
$lineContent = reset($lineContent);
$start = strpos($lineContent, $text.'');
return [
'snippet' => $lineContent,
'line' => $line,
'magic' => $text,
'col' => $start
];
} | php | private function getSnippet(string $content, int $line, $text): array
{
$content = str_replace(array("\r\n", "\r"), "\n", $content);
$lines = explode("\n", $content);
$lineContent = array_slice($lines, $line-1, 1);
$lineContent = reset($lineContent);
$start = strpos($lineContent, $text.'');
return [
'snippet' => $lineContent,
'line' => $line,
'magic' => $text,
'col' => $start
];
} | [
"private",
"function",
"getSnippet",
"(",
"string",
"$",
"content",
",",
"int",
"$",
"line",
",",
"$",
"text",
")",
":",
"array",
"{",
"$",
"content",
"=",
"str_replace",
"(",
"array",
"(",
"\"\\r\\n\"",
",",
"\"\\r\"",
")",
",",
"\"\\n\"",
",",
"$",
... | Get the snippet and information about it
@param string $content
@param int $line
@param int|string $text
@return array | [
"Get",
"the",
"snippet",
"and",
"information",
"about",
"it"
] | train | https://github.com/povils/phpmnd/blob/0471854ac2c3a77354be6eade27137cc05058363/src/Printer/Xml.php#L92-L107 |
jeremykenedy/laravel-exception-notifier | src/LaravelExceptionNotifier.php | LaravelExceptionNotifier.register | public function register()
{
$this->loadViewsFrom(__DIR__.'/resources/views/', $this->_packageTag);
$this->mergeConfigFrom(__DIR__.'/config/exceptions.php', $this->_packageTag);
$this->publishFiles();
} | php | public function register()
{
$this->loadViewsFrom(__DIR__.'/resources/views/', $this->_packageTag);
$this->mergeConfigFrom(__DIR__.'/config/exceptions.php', $this->_packageTag);
$this->publishFiles();
} | [
"public",
"function",
"register",
"(",
")",
"{",
"$",
"this",
"->",
"loadViewsFrom",
"(",
"__DIR__",
".",
"'/resources/views/'",
",",
"$",
"this",
"->",
"_packageTag",
")",
";",
"$",
"this",
"->",
"mergeConfigFrom",
"(",
"__DIR__",
".",
"'/config/exceptions.ph... | Register the application services.
@return void | [
"Register",
"the",
"application",
"services",
"."
] | train | https://github.com/jeremykenedy/laravel-exception-notifier/blob/06f2841b4530da665616fbae5862a1ac6a09739f/src/LaravelExceptionNotifier.php#L33-L38 |
jeremykenedy/laravel-exception-notifier | src/LaravelExceptionNotifier.php | LaravelExceptionNotifier.publishFiles | private function publishFiles()
{
$publishTag = $this->_packageTag;
// Publish Mailer
$this->publishes([
__DIR__.'/App/Mail/ExceptionOccured.php' => app_path('Mail/ExceptionOccured.php'),
], $publishTag);
// Publish email view
$this->publishes([
__DIR__.'/resources/views/emails/exception.blade.php' => resource_path('views/emails/exception.blade.php'),
], $publishTag);
// Publish config file
$this->publishes([
__DIR__.'/config/exceptions.php' => config_path('exceptions.php'),
], $publishTag);
} | php | private function publishFiles()
{
$publishTag = $this->_packageTag;
// Publish Mailer
$this->publishes([
__DIR__.'/App/Mail/ExceptionOccured.php' => app_path('Mail/ExceptionOccured.php'),
], $publishTag);
// Publish email view
$this->publishes([
__DIR__.'/resources/views/emails/exception.blade.php' => resource_path('views/emails/exception.blade.php'),
], $publishTag);
// Publish config file
$this->publishes([
__DIR__.'/config/exceptions.php' => config_path('exceptions.php'),
], $publishTag);
} | [
"private",
"function",
"publishFiles",
"(",
")",
"{",
"$",
"publishTag",
"=",
"$",
"this",
"->",
"_packageTag",
";",
"// Publish Mailer",
"$",
"this",
"->",
"publishes",
"(",
"[",
"__DIR__",
".",
"'/App/Mail/ExceptionOccured.php'",
"=>",
"app_path",
"(",
"'Mail/... | Publish files for package.
@return void | [
"Publish",
"files",
"for",
"package",
"."
] | train | https://github.com/jeremykenedy/laravel-exception-notifier/blob/06f2841b4530da665616fbae5862a1ac6a09739f/src/LaravelExceptionNotifier.php#L45-L63 |
jeremykenedy/laravel-exception-notifier | src/App/Traits/ExceptionNotificationHandlerTrait.php | ExceptionNotificationHandlerTrait.report | public function report(Exception $exception)
{
$enableEmailExceptions = config('exceptions.emailExceptionEnabled');
if ($enableEmailExceptions === '') {
$enableEmailExceptions = config('exceptions.emailExceptionEnabledDefault');
}
if ($enableEmailExceptions) {
if ($this->shouldReport($exception)) {
$this->sendEmail($exception);
}
}
parent::report($exception);
} | php | public function report(Exception $exception)
{
$enableEmailExceptions = config('exceptions.emailExceptionEnabled');
if ($enableEmailExceptions === '') {
$enableEmailExceptions = config('exceptions.emailExceptionEnabledDefault');
}
if ($enableEmailExceptions) {
if ($this->shouldReport($exception)) {
$this->sendEmail($exception);
}
}
parent::report($exception);
} | [
"public",
"function",
"report",
"(",
"Exception",
"$",
"exception",
")",
"{",
"$",
"enableEmailExceptions",
"=",
"config",
"(",
"'exceptions.emailExceptionEnabled'",
")",
";",
"if",
"(",
"$",
"enableEmailExceptions",
"===",
"''",
")",
"{",
"$",
"enableEmailExcepti... | Report or log an exception.
This is a great spot to send exceptions to Sentry, Bugsnag, etc.
@param \Exception $exception
@return void | [
"Report",
"or",
"log",
"an",
"exception",
"."
] | train | https://github.com/jeremykenedy/laravel-exception-notifier/blob/06f2841b4530da665616fbae5862a1ac6a09739f/src/App/Traits/ExceptionNotificationHandlerTrait.php#L36-L51 |
jeremykenedy/laravel-exception-notifier | src/App/Traits/ExceptionNotificationHandlerTrait.php | ExceptionNotificationHandlerTrait.sendEmail | public function sendEmail(Exception $exception)
{
try {
$e = FlattenException::create($exception);
$handler = new SymfonyExceptionHandler();
$html = $handler->getHtml($e);
Mail::send(new ExceptionOccured($html));
} catch (Exception $exception) {
Log::error($exception);
}
} | php | public function sendEmail(Exception $exception)
{
try {
$e = FlattenException::create($exception);
$handler = new SymfonyExceptionHandler();
$html = $handler->getHtml($e);
Mail::send(new ExceptionOccured($html));
} catch (Exception $exception) {
Log::error($exception);
}
} | [
"public",
"function",
"sendEmail",
"(",
"Exception",
"$",
"exception",
")",
"{",
"try",
"{",
"$",
"e",
"=",
"FlattenException",
"::",
"create",
"(",
"$",
"exception",
")",
";",
"$",
"handler",
"=",
"new",
"SymfonyExceptionHandler",
"(",
")",
";",
"$",
"h... | Sends an email upon exception.
@param \Exception $exception
@return void | [
"Sends",
"an",
"email",
"upon",
"exception",
"."
] | train | https://github.com/jeremykenedy/laravel-exception-notifier/blob/06f2841b4530da665616fbae5862a1ac6a09739f/src/App/Traits/ExceptionNotificationHandlerTrait.php#L60-L71 |
jeremykenedy/laravel-exception-notifier | src/App/Mail/ExceptionOccured.php | ExceptionOccured.build | public function build()
{
$emailsTo = str_getcsv(config('exceptions.emailExceptionsTo'), ',');
$ccEmails = str_getcsv(config('exceptions.emailExceptionCCto'), ',');
$bccEmails = str_getcsv(config('exceptions.emailExceptionBCCto'), ',');
$fromSender = config('exceptions.emailExceptionFrom');
$subject = config('exceptions.emailExceptionSubject');
if ($emailsTo[0] == null) {
$emailsTo = config('exceptions.emailExceptionsToDefault');
}
if ($ccEmails[0] == null) {
$ccEmails = config('exceptions.emailExceptionCCtoDefault');
}
if ($bccEmails[0] == null) {
$bccEmails = config('exceptions.emailExceptionBCCtoDefault');
}
if (!$fromSender) {
$fromSender = config('exceptions.emailExceptionFromDefault');
}
if (!$subject) {
$subject = config('exceptions.emailExceptionSubjectDefault');
}
return $this->from($fromSender)
->to($emailsTo)
->cc($ccEmails)
->bcc($bccEmails)
->subject($subject)
->view(config('exceptions.emailExceptionView'))
->with('content', $this->content);
} | php | public function build()
{
$emailsTo = str_getcsv(config('exceptions.emailExceptionsTo'), ',');
$ccEmails = str_getcsv(config('exceptions.emailExceptionCCto'), ',');
$bccEmails = str_getcsv(config('exceptions.emailExceptionBCCto'), ',');
$fromSender = config('exceptions.emailExceptionFrom');
$subject = config('exceptions.emailExceptionSubject');
if ($emailsTo[0] == null) {
$emailsTo = config('exceptions.emailExceptionsToDefault');
}
if ($ccEmails[0] == null) {
$ccEmails = config('exceptions.emailExceptionCCtoDefault');
}
if ($bccEmails[0] == null) {
$bccEmails = config('exceptions.emailExceptionBCCtoDefault');
}
if (!$fromSender) {
$fromSender = config('exceptions.emailExceptionFromDefault');
}
if (!$subject) {
$subject = config('exceptions.emailExceptionSubjectDefault');
}
return $this->from($fromSender)
->to($emailsTo)
->cc($ccEmails)
->bcc($bccEmails)
->subject($subject)
->view(config('exceptions.emailExceptionView'))
->with('content', $this->content);
} | [
"public",
"function",
"build",
"(",
")",
"{",
"$",
"emailsTo",
"=",
"str_getcsv",
"(",
"config",
"(",
"'exceptions.emailExceptionsTo'",
")",
",",
"','",
")",
";",
"$",
"ccEmails",
"=",
"str_getcsv",
"(",
"config",
"(",
"'exceptions.emailExceptionCCto'",
")",
"... | Build the message.
@return $this | [
"Build",
"the",
"message",
"."
] | train | https://github.com/jeremykenedy/laravel-exception-notifier/blob/06f2841b4530da665616fbae5862a1ac6a09739f/src/App/Mail/ExceptionOccured.php#L30-L65 |
spatie/laravel-translation-loader | src/TranslationLoaderManager.php | TranslationLoaderManager.load | public function load($locale, $group, $namespace = null): array
{
$fileTranslations = parent::load($locale, $group, $namespace);
if (! is_null($namespace) && $namespace !== '*') {
return $fileTranslations;
}
$loaderTranslations = $this->getTranslationsForTranslationLoaders($locale, $group, $namespace);
return array_replace_recursive($fileTranslations, $loaderTranslations);
} | php | public function load($locale, $group, $namespace = null): array
{
$fileTranslations = parent::load($locale, $group, $namespace);
if (! is_null($namespace) && $namespace !== '*') {
return $fileTranslations;
}
$loaderTranslations = $this->getTranslationsForTranslationLoaders($locale, $group, $namespace);
return array_replace_recursive($fileTranslations, $loaderTranslations);
} | [
"public",
"function",
"load",
"(",
"$",
"locale",
",",
"$",
"group",
",",
"$",
"namespace",
"=",
"null",
")",
":",
"array",
"{",
"$",
"fileTranslations",
"=",
"parent",
"::",
"load",
"(",
"$",
"locale",
",",
"$",
"group",
",",
"$",
"namespace",
")",
... | Load the messages for the given locale.
@param string $locale
@param string $group
@param string $namespace
@return array | [
"Load",
"the",
"messages",
"for",
"the",
"given",
"locale",
"."
] | train | https://github.com/spatie/laravel-translation-loader/blob/a730e5e8bedf3fda9ff5fc253a68179e3dbf5f14/src/TranslationLoaderManager.php#L19-L30 |
spatie/laravel-translation-loader | src/LanguageLine.php | LanguageLine.getTranslation | public function getTranslation(string $locale): ?string
{
if (! isset($this->text[$locale])) {
$fallback = config('app.fallback_locale');
return $this->text[$fallback] ?? null;
}
return $this->text[$locale];
} | php | public function getTranslation(string $locale): ?string
{
if (! isset($this->text[$locale])) {
$fallback = config('app.fallback_locale');
return $this->text[$fallback] ?? null;
}
return $this->text[$locale];
} | [
"public",
"function",
"getTranslation",
"(",
"string",
"$",
"locale",
")",
":",
"?",
"string",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"text",
"[",
"$",
"locale",
"]",
")",
")",
"{",
"$",
"fallback",
"=",
"config",
"(",
"'app.fallback_l... | @param string $locale
@return string | [
"@param",
"string",
"$locale"
] | train | https://github.com/spatie/laravel-translation-loader/blob/a730e5e8bedf3fda9ff5fc253a68179e3dbf5f14/src/LanguageLine.php#L58-L67 |
spatie/laravel-translation-loader | src/LanguageLine.php | LanguageLine.setTranslation | public function setTranslation(string $locale, string $value)
{
$this->text = array_merge($this->text ?? [], [$locale => $value]);
return $this;
} | php | public function setTranslation(string $locale, string $value)
{
$this->text = array_merge($this->text ?? [], [$locale => $value]);
return $this;
} | [
"public",
"function",
"setTranslation",
"(",
"string",
"$",
"locale",
",",
"string",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"text",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"text",
"??",
"[",
"]",
",",
"[",
"$",
"locale",
"=>",
"$",
"value",
... | @param string $locale
@param string $value
@return $this | [
"@param",
"string",
"$locale",
"@param",
"string",
"$value"
] | train | https://github.com/spatie/laravel-translation-loader/blob/a730e5e8bedf3fda9ff5fc253a68179e3dbf5f14/src/LanguageLine.php#L75-L80 |
aaemnnosttv/wp-cli-dotenv-command | src/Salts/Salts.php | Salts.fetch | protected function fetch()
{
return Collection::make(file($this->source, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES))
->map(function ($line) {
// capture everything between single quotes
preg_match_all(self::PATTERN_CAPTURE, $line, $matches);
// matches[x]
// 0 - complete match
// 1 - captures
return $matches[ 1 ];
})->filter();
} | php | protected function fetch()
{
return Collection::make(file($this->source, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES))
->map(function ($line) {
// capture everything between single quotes
preg_match_all(self::PATTERN_CAPTURE, $line, $matches);
// matches[x]
// 0 - complete match
// 1 - captures
return $matches[ 1 ];
})->filter();
} | [
"protected",
"function",
"fetch",
"(",
")",
"{",
"return",
"Collection",
"::",
"make",
"(",
"file",
"(",
"$",
"this",
"->",
"source",
",",
"FILE_SKIP_EMPTY_LINES",
"|",
"FILE_IGNORE_NEW_LINES",
")",
")",
"->",
"map",
"(",
"function",
"(",
"$",
"line",
")",... | Fetch the salts from the generator and return the parsed response.
@throws Exception
@return Collection | [
"Fetch",
"the",
"salts",
"from",
"the",
"generator",
"and",
"return",
"the",
"parsed",
"response",
"."
] | train | https://github.com/aaemnnosttv/wp-cli-dotenv-command/blob/1a779dd3645ed49bf1e48b3b35d3b9c8af90fc2c/src/Salts/Salts.php#L56-L67 |
aaemnnosttv/wp-cli-dotenv-command | src/WP_CLI/Command.php | Command.get_flag | protected function get_flag($key, $default = null)
{
return \WP_CLI\Utils\get_flag_value($this->args->original(), $key, $default);
} | php | protected function get_flag($key, $default = null)
{
return \WP_CLI\Utils\get_flag_value($this->args->original(), $key, $default);
} | [
"protected",
"function",
"get_flag",
"(",
"$",
"key",
",",
"$",
"default",
"=",
"null",
")",
"{",
"return",
"\\",
"WP_CLI",
"\\",
"Utils",
"\\",
"get_flag_value",
"(",
"$",
"this",
"->",
"args",
"->",
"original",
"(",
")",
",",
"$",
"key",
",",
"$",
... | Get flag value for command line option.
@param $key
@param null $default
@return mixed | [
"Get",
"flag",
"value",
"for",
"command",
"line",
"option",
"."
] | train | https://github.com/aaemnnosttv/wp-cli-dotenv-command/blob/1a779dd3645ed49bf1e48b3b35d3b9c8af90fc2c/src/WP_CLI/Command.php#L32-L35 |
aaemnnosttv/wp-cli-dotenv-command | src/WP_CLI/Command.php | Command.get_env_for_read_or_fail | protected function get_env_for_read_or_fail()
{
try {
return File::at($this->resolve_file_path())->load();
} catch (\Exception $e) {
WP_CLI::error($e->getMessage());
}
} | php | protected function get_env_for_read_or_fail()
{
try {
return File::at($this->resolve_file_path())->load();
} catch (\Exception $e) {
WP_CLI::error($e->getMessage());
}
} | [
"protected",
"function",
"get_env_for_read_or_fail",
"(",
")",
"{",
"try",
"{",
"return",
"File",
"::",
"at",
"(",
"$",
"this",
"->",
"resolve_file_path",
"(",
")",
")",
"->",
"load",
"(",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
... | Load the environment file, while ensuring read permissions or die trying!
@return File | [
"Load",
"the",
"environment",
"file",
"while",
"ensuring",
"read",
"permissions",
"or",
"die",
"trying!"
] | train | https://github.com/aaemnnosttv/wp-cli-dotenv-command/blob/1a779dd3645ed49bf1e48b3b35d3b9c8af90fc2c/src/WP_CLI/Command.php#L42-L49 |
aaemnnosttv/wp-cli-dotenv-command | src/WP_CLI/Command.php | Command.get_env_for_write_or_fail | protected function get_env_for_write_or_fail()
{
try {
return File::writable($this->resolve_file_path())->load();
} catch (\Exception $e) {
WP_CLI::error($e->getMessage());
}
} | php | protected function get_env_for_write_or_fail()
{
try {
return File::writable($this->resolve_file_path())->load();
} catch (\Exception $e) {
WP_CLI::error($e->getMessage());
}
} | [
"protected",
"function",
"get_env_for_write_or_fail",
"(",
")",
"{",
"try",
"{",
"return",
"File",
"::",
"writable",
"(",
"$",
"this",
"->",
"resolve_file_path",
"(",
")",
")",
"->",
"load",
"(",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
... | Load the environment file, while ensuring read permissions or die trying!
@return File | [
"Load",
"the",
"environment",
"file",
"while",
"ensuring",
"read",
"permissions",
"or",
"die",
"trying!"
] | train | https://github.com/aaemnnosttv/wp-cli-dotenv-command/blob/1a779dd3645ed49bf1e48b3b35d3b9c8af90fc2c/src/WP_CLI/Command.php#L56-L63 |
aaemnnosttv/wp-cli-dotenv-command | src/WP_CLI/Command.php | Command.resolve_file_path | protected function resolve_file_path($file = null)
{
if (is_null($file)) {
$file = $this->args->file;
}
if (file_exists($file)) {
return $file;
}
$dirname = dirname($file);
$filename = basename($file);
$relpath = $dirname ? "/$dirname" : '';
$path = getcwd() . "$relpath/$filename";
/**
* realpath will return false if path does not exist
*/
return realpath($path) ?: str_replace('/./', '/', $path);
} | php | protected function resolve_file_path($file = null)
{
if (is_null($file)) {
$file = $this->args->file;
}
if (file_exists($file)) {
return $file;
}
$dirname = dirname($file);
$filename = basename($file);
$relpath = $dirname ? "/$dirname" : '';
$path = getcwd() . "$relpath/$filename";
/**
* realpath will return false if path does not exist
*/
return realpath($path) ?: str_replace('/./', '/', $path);
} | [
"protected",
"function",
"resolve_file_path",
"(",
"$",
"file",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"file",
")",
")",
"{",
"$",
"file",
"=",
"$",
"this",
"->",
"args",
"->",
"file",
";",
"}",
"if",
"(",
"file_exists",
"(",
"$",
... | Get the absolute path to the file.
@param null $file The path to resolve, defaults to argument passed value.
@return string | [
"Get",
"the",
"absolute",
"path",
"to",
"the",
"file",
"."
] | train | https://github.com/aaemnnosttv/wp-cli-dotenv-command/blob/1a779dd3645ed49bf1e48b3b35d3b9c8af90fc2c/src/WP_CLI/Command.php#L72-L91 |
aaemnnosttv/wp-cli-dotenv-command | src/WP_CLI/Command.php | Command.prompt | protected function prompt($question, $default)
{
try {
return \cli\prompt($question, $default);
} catch (\Exception $e) {
WP_CLI::error($e->getMessage());
die;
}
} | php | protected function prompt($question, $default)
{
try {
return \cli\prompt($question, $default);
} catch (\Exception $e) {
WP_CLI::error($e->getMessage());
die;
}
} | [
"protected",
"function",
"prompt",
"(",
"$",
"question",
",",
"$",
"default",
")",
"{",
"try",
"{",
"return",
"\\",
"cli",
"\\",
"prompt",
"(",
"$",
"question",
",",
"$",
"default",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{"... | Prompt the user for input at the command line or use a default.
@param $question
@param $default
@return bool | [
"Prompt",
"the",
"user",
"for",
"input",
"at",
"the",
"command",
"line",
"or",
"use",
"a",
"default",
"."
] | train | https://github.com/aaemnnosttv/wp-cli-dotenv-command/blob/1a779dd3645ed49bf1e48b3b35d3b9c8af90fc2c/src/WP_CLI/Command.php#L102-L110 |
aaemnnosttv/wp-cli-dotenv-command | src/Dotenv/File.php | File.at | public static function at($path)
{
$file = new static($path);
if (! $file->exists()) {
throw new NonExistentFileException("File does not exist at $path");
}
if (! $file->isReadable()) {
throw new FilePermissionsException("File not readable at $path");
}
return $file;
} | php | public static function at($path)
{
$file = new static($path);
if (! $file->exists()) {
throw new NonExistentFileException("File does not exist at $path");
}
if (! $file->isReadable()) {
throw new FilePermissionsException("File not readable at $path");
}
return $file;
} | [
"public",
"static",
"function",
"at",
"(",
"$",
"path",
")",
"{",
"$",
"file",
"=",
"new",
"static",
"(",
"$",
"path",
")",
";",
"if",
"(",
"!",
"$",
"file",
"->",
"exists",
"(",
")",
")",
"{",
"throw",
"new",
"NonExistentFileException",
"(",
"\"Fi... | Get a new instance, and ensure the file is readable.
@param $path
@throws NonExistentFileException
@throws FilePermissionsException
@return static | [
"Get",
"a",
"new",
"instance",
"and",
"ensure",
"the",
"file",
"is",
"readable",
"."
] | train | https://github.com/aaemnnosttv/wp-cli-dotenv-command/blob/1a779dd3645ed49bf1e48b3b35d3b9c8af90fc2c/src/Dotenv/File.php#L46-L59 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.