message: [Intl] Add polyfill for Locale::canonicalize()

diff:
@@ -16,8 +16,8 @@ use Symfony\Component\Intl\Exception\MethodNotImplementedException;
/**
* Replacement for PHP's native {@link \Locale} class.
*
- * The only method supported in this class is {@link getDefault}. This method
- * will always return "en". All other methods will throw an exception when used.
+ * The only methods supported in this class are `getDefault` and `canonicalize`.
+ * All other methods will throw an exception when used.
*
* @author Eriksen Costa <eriksen.costa@infranology.com.br>
* @author Bernhard Schussek <bschussek@gmail.com>
@@ -57,6 +57,39 @@ class Locale
throw new MethodNotImplementedException(__METHOD__);
}
+ /**
+ * Returns a canonicalized locale string.
+ *
+ * This polyfill doesn't implement the full-spec algorithm. It only
+ * canonicalizes locale strings handled by the `LocaleBundle` class.
+ *
+ * @param string $locale
+ *
+ * @return string
+ */
+ public static function canonicalize($locale)
+ {
+ $locale = (string) $locale;
+
+ if ('' === $locale || '.' === $locale[0]) {
+ return self::getDefault();
+ }
+
+ if (!preg_match('/^([a-z]{2})[-_]([a-z]{2})(?:([a-z]{2})(?:[-_]([a-z]{2}))?)?(?:\..*)?$/i', $locale, $m)) {
+ return $locale;
+ }
+
+ if (!empty($m[4])) {
+ return strtolower($m[1]).'_'.ucfirst(strtolower($m[2].$m[3])).'_'.strtoupper($m[4]);
+ }
+
+ if (!empty($m[3])) {
+ return strtolower($m[1]).'_'.ucfirst(strtolower($m[2].$m[3]));
+ }
+
+ return strtolower($m[1]).'_'.strtoupper($m[2]);
+ }
+
/**
* Not supported. Returns a correctly ordered and delimited locale code.
*

diff:
@@ -21,6 +21,17 @@ class LocaleTest extends AbstractLocaleTest
$this->call('acceptFromHttp', 'pt-br,en-us;q=0.7,en;q=0.5');
}
+ public function testCanonicalize()
+ {
+ $this->assertSame('en', $this->call('canonicalize', ''));
+ $this->assertSame('en', $this->call('canonicalize', '.utf8'));
+ $this->assertSame('fr_FR', $this->call('canonicalize', 'FR-fr'));
+ $this->assertSame('fr_FR', $this->call('canonicalize', 'FR-fr.utf8'));
+ $this->assertSame('uz_Latn', $this->call('canonicalize', 'UZ-lATN'));
+ $this->assertSame('uz_Cyrl_UZ', $this->call('canonicalize', 'UZ-cYRL-uz'));
+ $this->assertSame('123', $this->call('canonicalize', 123));
+ }
+
/**
* @expectedException \Symfony\Component\Intl\Exception\MethodNotImplementedException
*/

repo: symfony/intl


message: Consistently throw exceptions on a single line

change_type: MODIFY

diff:
@@ -37,10 +37,7 @@ class GenrbCompiler implements BundleCompilerInterface
exec('which '.$genrb, $output, $status);
if (0 !== $status) {
- throw new RuntimeException(sprintf(
- 'The command "%s" is not installed',
- $genrb
- ));
+ throw new RuntimeException(sprintf('The command "%s" is not installed', $genrb));
}
$this->genrb = ($envVars ? $envVars.' ' : '').$genrb;
@@ -58,12 +55,7 @@ class GenrbCompiler implements BundleCompilerInterface
exec($this->genrb.' --quiet -e UTF-8 -d '.$targetDir.' '.$sourcePath, $output, $status);
if (0 !== $status) {
- throw new RuntimeException(sprintf(
- 'genrb failed with status %d while compiling %s to %s.',
- $status,
- $sourcePath,
- $targetDir
- ));
+ throw new RuntimeException(sprintf('genrb failed with status %d while compiling %s to %s.', $status, $sourcePath, $targetDir));
}
}
}

diff:
@@ -41,11 +41,7 @@ class IntlBundleReader implements BundleReaderInterface
// The bundle is NULL if the path does not look like a resource bundle
// (i.e. contain a bunch of *.res files)
if (null === $bundle) {
- throw new ResourceBundleNotFoundException(sprintf(
- 'The resource bundle "%s/%s.res" could not be found.',
- $path,
- $locale
- ));
+ throw new ResourceBundleNotFoundException(sprintf('The resource bundle "%s/%s.res" could not be found.', $path, $locale));
}
// Other possible errors are U_USING_FALLBACK_WARNING and U_ZERO_ERROR,

diff:
@@ -36,27 +36,17 @@ class JsonBundleReader implements BundleReaderInterface
}
if (!file_exists($fileName)) {
- throw new ResourceBundleNotFoundException(sprintf(
- 'The resource bundle "%s" does not exist.',
- $fileName
- ));
+ throw new ResourceBundleNotFoundException(sprintf('The resource bundle "%s" does not exist.', $fileName));
}
if (!is_file($fileName)) {
- throw new RuntimeException(sprintf(
- 'The resource bundle "%s" is not a file.',
- $fileName
- ));
+ throw new RuntimeException(sprintf('The resource bundle "%s" is not a file.', $fileName));
}
$data = json_decode(file_get_contents($fileName), true);
if (null === $data) {
- throw new RuntimeException(sprintf(
- 'The resource bundle "%s" contains invalid JSON: %s',
- $fileName,
- json_last_error_msg()
- ));
+ throw new RuntimeException(sprintf('The resource bundle "%s" contains invalid JSON: %s', $fileName, json_last_error_msg()));
}
return $data;

diff:
@@ -36,19 +36,11 @@ class PhpBundleReader implements BundleReaderInterface
}
if (!file_exists($fileName)) {
- throw new ResourceBundleNotFoundException(sprintf(
- 'The resource bundle "%s/%s.php" does not exist.',
- $path,
- $locale
- ));
+ throw new ResourceBundleNotFoundException(sprintf('The resource bundle "%s/%s.php" does not exist.', $path, $locale));
}
if (!is_file($fileName)) {
- throw new RuntimeException(sprintf(
- 'The resource bundle "%s/%s.php" is not a file.',
- $path,
- $locale
- ));
+ throw new RuntimeException(sprintf('The resource bundle "%s/%s.php" is not a file.', $path, $locale));
}
return include $fileName;

diff:
@@ -175,32 +175,19 @@ class LanguageDataGenerator extends AbstractDataGenerator
if (isset(self::$preferredAlpha2ToAlpha3Mapping[$language])) {
// Validate to prevent typos
if (!isset($aliases[self::$preferredAlpha2ToAlpha3Mapping[$language]])) {
- throw new RuntimeException(
- 'The statically set three-letter mapping '.
- self::$preferredAlpha2ToAlpha3Mapping[$language].' '.
- 'for the language code '.$language.' seems to be '.
- 'invalid. Typo?'
- );
+ throw new RuntimeException('The statically set three-letter mapping '.self::$preferredAlpha2ToAlpha3Mapping[$language].' for the language code '.$language.' seems to be invalid. Typo?');
}
$alpha3 = self::$preferredAlpha2ToAlpha3Mapping[$language];
$alpha2 = $aliases[$alpha3]['replacement'];
if ($language !== $alpha2) {
- throw new RuntimeException(
- 'The statically set three-letter mapping '.$alpha3.' '.
- 'for the language code '.$language.' seems to be '.
- 'an alias for '.$alpha2.'. Wrong mapping?'
- );
+ throw new RuntimeException('The statically set three-letter mapping '.$alpha3.' for the language code '.$language.' seems to be an alias for '.$alpha2.'. Wrong mapping?');
}
$alpha2ToAlpha3[$language] = $alpha3;
} elseif (isset($alpha2ToAlpha3[$language])) {
- throw new RuntimeException(
- 'Multiple three-letter mappings exist for the language '.
- 'code '.$language.'. Please add one of them to the '.
- 'property $preferredAlpha2ToAlpha3Mapping.'
- );
+ throw new RuntimeException('Multiple three-letter mappings exist for the language code '.$language.'. Please add one of them to the property $preferredAlpha2ToAlpha3Mapping.');
} else {
$alpha2ToAlpha3[$language] = $alias;
}

diff:
@@ -36,10 +36,7 @@ class RecursiveArrayAccess
}
}
- throw new OutOfBoundsException(sprintf(
- 'The index %s does not exist.',
- $index
- ));
+ throw new OutOfBoundsException(sprintf('The index %s does not exist.', $index));
}
return $array;

diff:
@@ -53,10 +53,7 @@ class RingBuffer implements \ArrayAccess
public function offsetGet($key)
{
if (!isset($this->indices[$key])) {
- throw new OutOfBoundsException(sprintf(
- 'The index "%s" does not exist.',
- $key
- ));
+ throw new OutOfBoundsException(sprintf('The index "%s" does not exist.', $key));
}
return $this->values[$this->indices[$key]];

diff:
@@ -106,10 +106,7 @@ class TimeZoneTransformer extends Transformer
$signal = '-' == $matches['signal'] ? '+' : '-';
if (0 < $minutes) {
- throw new NotImplementedException(sprintf(
- 'It is not possible to use a GMT time zone with minutes offset different than zero (0). GMT time zone tried: %s.',
- $formattedTimeZone
- ));
+ throw new NotImplementedException(sprintf('It is not possible to use a GMT time zone with minutes offset different than zero (0). GMT time zone tried: %s.', $formattedTimeZone));
}
return 'Etc/GMT'.(0 !== $hours ? $signal.$hours : '');

diff:
@@ -360,10 +360,7 @@ class NumberFormatter
}
if (self::CURRENCY == $this->style) {
- throw new NotImplementedException(sprintf(
- '%s() method does not support the formatting of currencies (instance with CURRENCY style). %s',
- __METHOD__, NotImplementedException::INTL_INSTALL_MESSAGE
- ));
+ throw new NotImplementedException(sprintf('%s() method does not support the formatting of currencies (instance with CURRENCY style). %s', __METHOD__, NotImplementedException::INTL_INSTALL_MESSAGE));
}
// Only the default type is supported.

license: MIT License


message: Fix return statements

diff:
@@ -72,7 +72,7 @@ class LocaleDataGenerator extends AbstractDataGenerator
// Don't generate aliases, as they are resolved during runtime
// Unless an alias is needed as fallback for de-duplication purposes
if (isset($this->localeAliases[$displayLocale]) && !$this->generatingFallback) {
- return;
+ return null;
}
// Generate locale names for all locales that have translations in
@@ -117,7 +117,7 @@ class LocaleDataGenerator extends AbstractDataGenerator
$data['Names'] = array_diff($data['Names'], $fallbackData['Names']);
}
if (!$data['Names']) {
- return;
+ return null;
}
return $data;

diff:
@@ -49,7 +49,7 @@ class CurrencyBundle extends CurrencyDataProvider implements CurrencyBundleInter
try {
return $this->getSymbol($currency, $displayLocale);
} catch (MissingResourceException $e) {
- return;
+ return null;
}
}
@@ -61,7 +61,7 @@ class CurrencyBundle extends CurrencyDataProvider implements CurrencyBundleInter
try {
return $this->getName($currency, $displayLocale);
} catch (MissingResourceException $e) {
- return;
+ return null;
}
}

diff:
@@ -62,7 +62,7 @@ class LanguageBundle extends LanguageDataProvider implements LanguageBundleInter
try {
return $this->getName($language, $displayLocale);
} catch (MissingResourceException $e) {
- return;
+ return null;
}
}
@@ -86,7 +86,7 @@ class LanguageBundle extends LanguageDataProvider implements LanguageBundleInter
try {
return $this->scriptProvider->getName($script, $displayLocale);
} catch (MissingResourceException $e) {
- return;
+ return null;
}
}

diff:
@@ -43,7 +43,7 @@ class LocaleBundle extends LocaleDataProvider implements LocaleBundleInterface
try {
return $this->getName($locale, $displayLocale);
} catch (MissingResourceException $e) {
- return;
+ return null;
}
}

diff:
@@ -49,7 +49,7 @@ class RegionBundle extends RegionDataProvider implements RegionBundleInterface
try {
return $this->getName($country, $displayLocale);
} catch (MissingResourceException $e) {
- return;
+ return null;
}
}

diff:
@@ -83,7 +83,7 @@ class Version
}
if (!preg_match('/^'.$pattern.'/', $version, $matches)) {
- return;
+ return null;
}
return $matches[0];

original_message: Fix return statements


message: Import return annotations from vendors

diff:
@@ -84,13 +84,13 @@ class TimezoneDataGenerator extends AbstractDataGenerator
// Don't generate aliases, as they are resolved during runtime
// Unless an alias is needed as fallback for de-duplication purposes
if (isset($this->localeAliases[$displayLocale]) && !$this->generatingFallback) {
- return;
+ return null;
}
$localeBundle = $reader->read($tempDir, $displayLocale);
if (!isset($localeBundle['zoneStrings']) || null === $localeBundle['zoneStrings']) {
- return;
+ return null;
}
$data = [
@@ -115,7 +115,7 @@ class TimezoneDataGenerator extends AbstractDataGenerator
$data['Meta'] = array_diff($data['Meta'], $fallback['Meta']);
}
if (!$data['Names'] && !$data['Meta']) {
- return;
+ return null;
}
$this->zoneIds = array_merge($this->zoneIds, array_keys($data['Names']));

original_message: Import return annotations from vendors


message: some backports from master

diff:
@@ -51,7 +51,7 @@ class CurrencyDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function scanLocales(LocaleScanner $scanner, $sourceDir): array
+ protected function scanLocales(LocaleScanner $scanner, string $sourceDir): array
{
return $scanner->scanLocales($sourceDir.'/curr');
}
@@ -59,7 +59,7 @@ class CurrencyDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function compileTemporaryBundles(BundleCompilerInterface $compiler, $sourceDir, $tempDir)
+ protected function compileTemporaryBundles(BundleCompilerInterface $compiler, string $sourceDir, string $tempDir)
{
$compiler->compile($sourceDir.'/curr', $tempDir);
$compiler->compile($sourceDir.'/misc/currencyNumericCodes.txt', $tempDir);
@@ -76,7 +76,7 @@ class CurrencyDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function generateDataForLocale(BundleEntryReaderInterface $reader, $tempDir, $displayLocale): ?array
+ protected function generateDataForLocale(BundleEntryReaderInterface $reader, string $tempDir, string $displayLocale): ?array
{
$localeBundle = $reader->read($tempDir, $displayLocale);
@@ -97,7 +97,7 @@ class CurrencyDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function generateDataForRoot(BundleEntryReaderInterface $reader, $tempDir): ?array
+ protected function generateDataForRoot(BundleEntryReaderInterface $reader, string $tempDir): ?array
{
$rootBundle = $reader->read($tempDir, 'root');
@@ -110,7 +110,7 @@ class CurrencyDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function generateDataForMeta(BundleEntryReaderInterface $reader, $tempDir): ?array
+ protected function generateDataForMeta(BundleEntryReaderInterface $reader, string $tempDir): ?array
{
$rootBundle = $reader->read($tempDir, 'root');
$supplementalDataBundle = $reader->read($tempDir, 'supplementalData');

diff:
@@ -101,7 +101,7 @@ class LanguageDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function scanLocales(LocaleScanner $scanner, $sourceDir): array
+ protected function scanLocales(LocaleScanner $scanner, string $sourceDir): array
{
return $scanner->scanLocales($sourceDir.'/lang');
}
@@ -109,7 +109,7 @@ class LanguageDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function compileTemporaryBundles(BundleCompilerInterface $compiler, $sourceDir, $tempDir)
+ protected function compileTemporaryBundles(BundleCompilerInterface $compiler, string $sourceDir, string $tempDir)
{
$compiler->compile($sourceDir.'/lang', $tempDir);
$compiler->compile($sourceDir.'/misc/metadata.txt', $tempDir);
@@ -126,7 +126,7 @@ class LanguageDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function generateDataForLocale(BundleEntryReaderInterface $reader, $tempDir, $displayLocale): ?array
+ protected function generateDataForLocale(BundleEntryReaderInterface $reader, string $tempDir, string $displayLocale): ?array
{
$localeBundle = $reader->read($tempDir, $displayLocale);
@@ -148,14 +148,14 @@ class LanguageDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function generateDataForRoot(BundleEntryReaderInterface $reader, $tempDir): ?array
+ protected function generateDataForRoot(BundleEntryReaderInterface $reader, string $tempDir): ?array
{
}
/**
* {@inheritdoc}
*/
- protected function generateDataForMeta(BundleEntryReaderInterface $reader, $tempDir): ?array
+ protected function generateDataForMeta(BundleEntryReaderInterface $reader, string $tempDir): ?array
{
$rootBundle = $reader->read($tempDir, 'root');
$metadataBundle = $reader->read($tempDir, 'metadata');

diff:
@@ -36,7 +36,7 @@ class LocaleDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function scanLocales(LocaleScanner $scanner, $sourceDir): array
+ protected function scanLocales(LocaleScanner $scanner, string $sourceDir): array
{
$this->locales = $scanner->scanLocales($sourceDir.'/locales');
$this->localeAliases = $scanner->scanAliases($sourceDir.'/locales');
@@ -48,7 +48,7 @@ class LocaleDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function compileTemporaryBundles(BundleCompilerInterface $compiler, $sourceDir, $tempDir)
+ protected function compileTemporaryBundles(BundleCompilerInterface $compiler, string $sourceDir, string $tempDir)
{
$filesystem = new Filesystem();
$filesystem->mkdir([
@@ -74,7 +74,7 @@ class LocaleDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function generateDataForLocale(BundleEntryReaderInterface $reader, $tempDir, $displayLocale): ?array
+ protected function generateDataForLocale(BundleEntryReaderInterface $reader, string $tempDir, string $displayLocale): ?array
{
// Don't generate aliases, as they are resolved during runtime
// Unless an alias is needed as fallback for de-duplication purposes
@@ -133,14 +133,14 @@ class LocaleDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function generateDataForRoot(BundleEntryReaderInterface $reader, $tempDir): ?array
+ protected function generateDataForRoot(BundleEntryReaderInterface $reader, string $tempDir): ?array
{
}
/**
* {@inheritdoc}
*/
- protected function generateDataForMeta(BundleEntryReaderInterface $reader, $tempDir): ?array
+ protected function generateDataForMeta(BundleEntryReaderInterface $reader, string $tempDir): ?array
{
return [
'Locales' => $this->locales,

diff:
@@ -84,7 +84,7 @@ class RegionDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function scanLocales(LocaleScanner $scanner, $sourceDir): array
+ protected function scanLocales(LocaleScanner $scanner, string $sourceDir): array
{
return $scanner->scanLocales($sourceDir.'/region');
}
@@ -92,7 +92,7 @@ class RegionDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function compileTemporaryBundles(BundleCompilerInterface $compiler, $sourceDir, $tempDir)
+ protected function compileTemporaryBundles(BundleCompilerInterface $compiler, string $sourceDir, string $tempDir)
{
$compiler->compile($sourceDir.'/region', $tempDir);
$compiler->compile($sourceDir.'/misc/metadata.txt', $tempDir);
@@ -109,7 +109,7 @@ class RegionDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function generateDataForLocale(BundleEntryReaderInterface $reader, $tempDir, $displayLocale): ?array
+ protected function generateDataForLocale(BundleEntryReaderInterface $reader, string $tempDir, string $displayLocale): ?array
{
$localeBundle = $reader->read($tempDir, $displayLocale);
@@ -131,14 +131,14 @@ class RegionDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function generateDataForRoot(BundleEntryReaderInterface $reader, $tempDir): ?array
+ protected function generateDataForRoot(BundleEntryReaderInterface $reader, string $tempDir): ?array
{
}
/**
* {@inheritdoc}
*/
- protected function generateDataForMeta(BundleEntryReaderInterface $reader, $tempDir): ?array
+ protected function generateDataForMeta(BundleEntryReaderInterface $reader, string $tempDir): ?array
{
$rootBundle = $reader->read($tempDir, 'root');
$metadataBundle = $reader->read($tempDir, 'metadata');

diff:
@@ -38,7 +38,7 @@ class ScriptDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function scanLocales(LocaleScanner $scanner, $sourceDir): array
+ protected function scanLocales(LocaleScanner $scanner, string $sourceDir): array
{
return $scanner->scanLocales($sourceDir.'/lang');
}
@@ -46,7 +46,7 @@ class ScriptDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function compileTemporaryBundles(BundleCompilerInterface $compiler, $sourceDir, $tempDir)
+ protected function compileTemporaryBundles(BundleCompilerInterface $compiler, string $sourceDir, string $tempDir)
{
$compiler->compile($sourceDir.'/lang', $tempDir);
}
@@ -62,7 +62,7 @@ class ScriptDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function generateDataForLocale(BundleEntryReaderInterface $reader, $tempDir, $displayLocale): ?array
+ protected function generateDataForLocale(BundleEntryReaderInterface $reader, string $tempDir, string $displayLocale): ?array
{
$localeBundle = $reader->read($tempDir, $displayLocale);
@@ -84,14 +84,14 @@ class ScriptDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function generateDataForRoot(BundleEntryReaderInterface $reader, $tempDir): ?array
+ protected function generateDataForRoot(BundleEntryReaderInterface $reader, string $tempDir): ?array
{
}
/**
* {@inheritdoc}
*/
- protected function generateDataForMeta(BundleEntryReaderInterface $reader, $tempDir): ?array
+ protected function generateDataForMeta(BundleEntryReaderInterface $reader, string $tempDir): ?array
{
$rootBundle = $reader->read($tempDir, 'root');

diff:
@@ -42,7 +42,7 @@ class TimezoneDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function scanLocales(LocaleScanner $scanner, $sourceDir): array
+ protected function scanLocales(LocaleScanner $scanner, string $sourceDir): array
{
$this->localeAliases = $scanner->scanAliases($sourceDir.'/locales');
@@ -52,7 +52,7 @@ class TimezoneDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function compileTemporaryBundles(BundleCompilerInterface $compiler, $sourceDir, $tempDir)
+ protected function compileTemporaryBundles(BundleCompilerInterface $compiler, string $sourceDir, string $tempDir)
{
$filesystem = new Filesystem();
$filesystem->mkdir($tempDir.'/region');
@@ -75,7 +75,7 @@ class TimezoneDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function generateDataForLocale(BundleEntryReaderInterface $reader, $tempDir, $displayLocale): ?array
+ protected function generateDataForLocale(BundleEntryReaderInterface $reader, string $tempDir, string $displayLocale): ?array
{
if (!$this->zoneToCountryMapping) {
$this->zoneToCountryMapping = self::generateZoneToCountryMapping($reader->read($tempDir, 'windowsZones'));
@@ -126,7 +126,7 @@ class TimezoneDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function generateDataForRoot(BundleEntryReaderInterface $reader, $tempDir): ?array
+ protected function generateDataForRoot(BundleEntryReaderInterface $reader, string $tempDir): ?array
{
$rootBundle = $reader->read($tempDir, 'root');
@@ -139,7 +139,7 @@ class TimezoneDataGenerator extends AbstractDataGenerator
/**
* {@inheritdoc}
*/
- protected function generateDataForMeta(BundleEntryReaderInterface $reader, $tempDir): ?array
+ protected function generateDataForMeta(BundleEntryReaderInterface $reader, string $tempDir): ?array
{
$rootBundle = $reader->read($tempDir, 'root');

original_message: some backports from master


message: [Intl] make polyfill classes abstract, fix edge case

diff:
@@ -33,7 +33,7 @@ use Symfony\Component\Intl\Locale\Locale;
*
* @internal
*/
-class Collator
+abstract class Collator
{
/* Attribute constants */
const FRENCH_COLLATION = 0;
@@ -86,13 +86,13 @@ class Collator
*
* @param string|null $locale The locale code. The only currently supported locale is "en" (or null using the default locale, i.e. "en")
*
- * @return self
+ * @return static
*
* @throws MethodArgumentValueNotImplementedException When $locale different than "en" or null is passed
*/
public static function create($locale)
{
- return new self($locale);
+ return new static($locale);
}
/**

diff:
@@ -46,7 +46,7 @@ use Symfony\Component\Intl\Locale\Locale;
*
* @internal
*/
-class IntlDateFormatter
+abstract class IntlDateFormatter
{
/**
* The error code from the last operation.
@@ -78,9 +78,9 @@ class IntlDateFormatter
*/
private $defaultDateFormats = [
self::NONE => '',
- self::FULL => 'EEEE, LLLL d, y',
- self::LONG => 'LLLL d, y',
- self::MEDIUM => 'LLL d, y',
+ self::FULL => 'EEEE, MMMM d, y',
+ self::LONG => 'MMMM d, y',
+ self::MEDIUM => 'MMM d, y',
self::SHORT => 'M/d/yy',
];
@@ -160,7 +160,7 @@ class IntlDateFormatter
* One of the calendar constants
* @param string|null $pattern Optional pattern to use when formatting
*
- * @return self
+ * @return static
*
* @see https://php.net/intldateformatter.create
* @see http://userguide.icu-project.org/formatparse/datetime
@@ -170,7 +170,7 @@ class IntlDateFormatter
*/
public static function create($locale, $datetype, $timetype, $timezone = null, $calendar = self::GREGORIAN, $pattern = null)
{
- return new self($locale, $datetype, $timetype, $timezone, $calendar, $pattern);
+ return new static($locale, $datetype, $timetype, $timezone, $calendar, $pattern);
}
/**
@@ -600,14 +600,19 @@ class IntlDateFormatter
*/
protected function getDefaultPattern()
{
- $patternParts = [];
+ $pattern = '';
if (self::NONE !== $this->datetype) {
- $patternParts[] = $this->defaultDateFormats[$this->datetype];
+ $pattern = $this->defaultDateFormats[$this->datetype];
}
if (self::NONE !== $this->timetype) {
- $patternParts[] = $this->defaultTimeFormats[$this->timetype];
+ if (self::FULL === $this->datetype || self::LONG === $this->datetype) {
+ $pattern .= ' \'at\' ';
+ } elseif (self::NONE !== $this->datetype) {
+ $pattern .= ', ';
+ }
+ $pattern .= $this->defaultTimeFormats[$this->timetype];
}
- return implode(', ', $patternParts);
+ return $pattern;
}
}

diff:
@@ -24,7 +24,7 @@ use Symfony\Component\Intl\Exception\MethodNotImplementedException;
*
* @internal
*/
-class Locale
+abstract class Locale
{
const DEFAULT_LOCALE = null;

diff:
@@ -40,7 +40,7 @@ use Symfony\Component\Intl\Locale\Locale;
*
* @internal
*/
-class NumberFormatter
+abstract class NumberFormatter
{
/* Format style constants */
const PATTERN_DECIMAL = 0;
@@ -286,7 +286,7 @@ class NumberFormatter
* NumberFormat::PATTERN_RULEBASED. It must conform to the syntax
* described in the ICU DecimalFormat or ICU RuleBasedNumberFormat documentation
*
- * @return self
+ * @return static
*
* @see https://php.net/numberformatter.create
* @see http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#_details
@@ -298,7 +298,7 @@ class NumberFormatter
*/
public static function create($locale = 'en', $style = null, $pattern = null)
{
- return new self($locale, $style, $pattern);
+ return new static($locale, $style, $pattern);
}
/**

diff:
@@ -19,7 +19,7 @@ class CollatorTest extends AbstractCollatorTest
public function testConstructorWithUnsupportedLocale()
{
$this->expectException('Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException');
- new Collator('pt_BR');
+ $this->getCollator('pt_BR');
}
public function testCompare()
@@ -90,12 +90,14 @@ class CollatorTest extends AbstractCollatorTest
public function testStaticCreate()
{
- $collator = Collator::create('en');
+ $collator = $this->getCollator('en');
+ $collator = $collator::create('en');
$this->assertInstanceOf('\Symfony\Component\Intl\Collator\Collator', $collator);
}
protected function getCollator($locale)
{
- return new Collator($locale);
+ return new class($locale) extends Collator {
+ };
}
}

diff:
@@ -43,8 +43,6 @@ abstract class AbstractIntlDateFormatterTest extends TestCase
/**
* When a time zone is not specified, it uses the system default however it returns null in the getter method.
- *
- * @see StubIntlDateFormatterTest::testDefaultTimeZoneIntl()
*/
public function testConstructorDefaultTimeZone()
{
@@ -60,14 +58,14 @@ abstract class AbstractIntlDateFormatterTest extends TestCase
public function testConstructorWithoutDateType()
{
- $formatter = new IntlDateFormatter('en', null, IntlDateFormatter::SHORT, 'UTC', IntlDateFormatter::GREGORIAN);
+ $formatter = $this->getDateFormatter('en', null, IntlDateFormatter::SHORT, 'UTC', IntlDateFormatter::GREGORIAN);
- $this->assertSame('EEEE, LLLL d, y, h:mm a', $formatter->getPattern());
+ $this->assertSame('EEEE, MMMM d, y \'at\' h:mm a', $formatter->getPattern());
}
public function testConstructorWithoutTimeType()
{
- $formatter = new IntlDateFormatter('en', IntlDateFormatter::SHORT, null, 'UTC', IntlDateFormatter::GREGORIAN);
+ $formatter = $this->getDateFormatter('en', IntlDateFormatter::SHORT, null, 'UTC', IntlDateFormatter::GREGORIAN);
$this->assertSame('M/d/yy, h:mm:ss a zzzz', $formatter->getPattern());
}
@@ -963,14 +961,7 @@ abstract class AbstractIntlDateFormatterTest extends TestCase
}
/**
- * @param $locale
- * @param $datetype
- * @param $timetype
- * @param null $timezone
- * @param int $calendar
- * @param null $pattern
- *
- * @return mixed
+ * @return IntlDateFormatter|\IntlDateFormatter
*/
abstract protected function getDateFormatter($locale, $datetype, $timetype, $timezone = null, $calendar = IntlDateFormatter::GREGORIAN, $pattern = null);

diff:
@@ -18,31 +18,32 @@ class IntlDateFormatterTest extends AbstractIntlDateFormatterTest
{
public function testConstructor()
{
- $formatter = new IntlDateFormatter('en', IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT, 'UTC', IntlDateFormatter::GREGORIAN, 'y-M-d');
+ $formatter = $this->getDateFormatter('en', IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT, 'UTC', IntlDateFormatter::GREGORIAN, 'y-M-d');
$this->assertEquals('y-M-d', $formatter->getPattern());
}
public function testConstructorWithoutLocale()
{
- $formatter = new IntlDateFormatter(null, IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT, 'UTC', IntlDateFormatter::GREGORIAN, 'y-M-d');
+ $formatter = $this->getDateFormatter(null, IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT, 'UTC', IntlDateFormatter::GREGORIAN, 'y-M-d');
$this->assertEquals('y-M-d', $formatter->getPattern());
}
public function testConstructorWithoutCalendar()
{
- $formatter = new IntlDateFormatter('en', IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT, 'UTC', null, 'y-M-d');
+ $formatter = $this->getDateFormatter('en', IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT, 'UTC', null, 'y-M-d');
$this->assertEquals('y-M-d', $formatter->getPattern());
}
public function testConstructorWithUnsupportedLocale()
{
$this->expectException('Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException');
- new IntlDateFormatter('pt_BR', IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT);
+ $this->getDateFormatter('pt_BR', IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT);
}
public function testStaticCreate()
{
- $formatter = IntlDateFormatter::create('en', IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT);
+ $formatter = $this->getDateFormatter('en', IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT);
+ $formatter = $formatter::create('en', IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT);
$this->assertInstanceOf('\Symfony\Component\Intl\DateFormatter\IntlDateFormatter', $formatter);
}
@@ -75,7 +76,7 @@ class IntlDateFormatterTest extends AbstractIntlDateFormatterTest
{
$this->expectException('Symfony\Component\Intl\Exception\NotImplementedException');
$pattern = 'Y';
- $formatter = new IntlDateFormatter('en', IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT, 'UTC', IntlDateFormatter::GREGORIAN, $pattern);
+ $formatter = $this->getDateFormatter('en', IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT, 'UTC', IntlDateFormatter::GREGORIAN, $pattern);
$formatter->format(0);
}
@@ -178,7 +179,8 @@ class IntlDateFormatterTest extends AbstractIntlDateFormatterTest
protected function getDateFormatter($locale, $datetype, $timetype, $timezone = null, $calendar = IntlDateFormatter::GREGORIAN, $pattern = null)
{
- return new IntlDateFormatter($locale, $datetype, $timetype, $timezone, $calendar, $pattern);
+ return new class($locale, $datetype, $timetype, $timezone, $calendar, $pattern) extends IntlDateFormatter {
+ };
}
protected function getIntlErrorMessage()

diff:
@@ -23,19 +23,19 @@ class NumberFormatterTest extends AbstractNumberFormatterTest
public function testConstructorWithUnsupportedLocale()
{
$this->expectException('Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException');
- new NumberFormatter('pt_BR');
+ $this->getNumberFormatter('pt_BR');
}
public function testConstructorWithUnsupportedStyle()
{
$this->expectException('Symfony\Component\Intl\Exception\MethodArgumentValueNotImplementedException');
- new NumberFormatter('en', NumberFormatter::PATTERN_DECIMAL);
+ $this->getNumberFormatter('en', NumberFormatter::PATTERN_DECIMAL);
}
public function testConstructorWithPatternDifferentThanNull()
{
$this->expectException('Symfony\Component\Intl\Exception\MethodArgumentNotImplementedException');
- new NumberFormatter('en', NumberFormatter::DECIMAL, '');
+ $this->getNumberFormatter('en', NumberFormatter::DECIMAL, '');
}
public function testSetAttributeWithUnsupportedAttribute()
@@ -62,10 +62,8 @@ class NumberFormatterTest extends AbstractNumberFormatterTest
public function testCreate()
{
- $this->assertInstanceOf(
- '\Symfony\Component\Intl\NumberFormatter\NumberFormatter',
- NumberFormatter::create('en', NumberFormatter::DECIMAL)
- );
+ $formatter = $this->getNumberFormatter('en', NumberFormatter::DECIMAL);
+ $this->assertInstanceOf(NumberFormatter::class, $formatter::create('en', NumberFormatter::DECIMAL));
}
public function testFormatWithCurrencyStyle()
@@ -171,7 +169,8 @@ class NumberFormatterTest extends AbstractNumberFormatterTest
protected function getNumberFormatter($locale = 'en', $style = null, $pattern = null)
{
- return new NumberFormatter($locale, $style, $pattern);
+ return new class($locale, $style, $pattern) extends NumberFormatter {
+ };
}
protected function getIntlErrorMessage()


message: [Intl] fix return type declarations

diff:
@@ -415,7 +415,7 @@ class IntlDateFormatter
* contain -1 otherwise it will contain the position at which parsing
* ended. If $parse_pos > strlen($value), the parse fails immediately.
*
- * @return int Parsed value as a timestamp
+ * @return int|false Parsed value as a timestamp
*
* @see https://php.net/intldateformatter.parse
*

original_message: [Intl] fix return type declarations


message: [PhpUnitBridge] fix replaying skipped tests

diff:
@@ -30,6 +30,18 @@ class IntlDateFormatterTest extends AbstractIntlDateFormatterTest
parent::setUp();
}
+ /**
+ * @dataProvider formatProvider
+ */
+ public function testFormat($pattern, $timestamp, $expected)
+ {
+ if (\PHP_VERSION_ID < 70105 && $timestamp instanceof \DateTimeImmutable) {
+ $this->markTestSkipped('PHP >= 7.1.5 required for DateTimeImmutable.');
+ }
+
+ parent::testFormat($pattern, $timestamp, $expected);
+ }
+
/**
* @dataProvider formatTimezoneProvider
*/


message: [Form] fix passing null $pattern to IntlDateFormatter

diff:
@@ -145,6 +145,10 @@ abstract class IntlDateFormatter
$this->datetype = null !== $datetype ? $datetype : self::FULL;
$this->timetype = null !== $timetype ? $timetype : self::FULL;
+ if ('' === ($pattern ?? '')) {
+ $pattern = $this->getDefaultPattern();
+ }
+
$this->setPattern($pattern);
$this->setTimeZone($timezone);
}
@@ -485,7 +489,7 @@ abstract class IntlDateFormatter
/**
* Set the formatter's pattern.
*
- * @param string|null $pattern A pattern string in conformance with the ICU IntlDateFormatter documentation
+ * @param string $pattern A pattern string in conformance with the ICU IntlDateFormatter documentation
*
* @return bool true on success or false on failure
*
@@ -494,11 +498,7 @@ abstract class IntlDateFormatter
*/
public function setPattern($pattern)
{
- if (null === $pattern) {
- $pattern = $this->getDefaultPattern();
- }
-
- $this->pattern = $pattern;
+ $this->pattern = (string) $pattern;
return true;
}


message: [Intl] Add `Currencies::getCashFractionDigits()` and `Currencies::getCashRoundingIncrement()`

diff:
CHANGELOG
=========
+5.3
+---
+
+ * Add `Currencies::getCashFractionDigits()` and `Currencies::getCashRoundingIncrement()`
+
5.0.0
-----

diff:
@@ -25,6 +25,8 @@ final class Currencies extends ResourceBundle
private const INDEX_NAME = 1;
private const INDEX_FRACTION_DIGITS = 0;
private const INDEX_ROUNDING_INCREMENT = 1;
+ private const INDEX_CASH_FRACTION_DIGITS = 2;
+ private const INDEX_CASH_ROUNDING_INCREMENT = 3;
/**
* @return string[]
@@ -94,10 +96,7 @@ final class Currencies extends ResourceBundle
}
}
- /**
- * @return float|int
- */
- public static function getRoundingIncrement(string $currency)
+ public static function getRoundingIncrement(string $currency): int
{
try {
return self::readEntry(['Meta', $currency, self::INDEX_ROUNDING_INCREMENT], 'meta');
@@ -106,6 +105,24 @@ final class Currencies extends ResourceBundle
}
}
+ public static function getCashFractionDigits(string $currency): int
+ {
+ try {
+ return self::readEntry(['Meta', $currency, self::INDEX_CASH_FRACTION_DIGITS], 'meta');
+ } catch (MissingResourceException $e) {
+ return self::readEntry(['Meta', 'DEFAULT', self::INDEX_CASH_FRACTION_DIGITS], 'meta');
+ }
+ }
+
+ public static function getCashRoundingIncrement(string $currency): int
+ {
+ try {
+ return self::readEntry(['Meta', $currency, self::INDEX_CASH_ROUNDING_INCREMENT], 'meta');
+ } catch (MissingResourceException $e) {
+ return self::readEntry(['Meta', 'DEFAULT', self::INDEX_CASH_ROUNDING_INCREMENT], 'meta');
+ }
+ }
+
/**
* @throws MissingResourceException if the currency code has no numeric code
*/


message: [Form] fix support for years outside of the 32b range on x86 arch

diff:
@@ -180,7 +180,7 @@ abstract class IntlDateFormatter
/**
* Format the date/time value (timestamp) as a string.
*
- * @param int|\DateTimeInterface $timestamp The timestamp to format
+ * @param int|string|\DateTimeInterface $timestamp The timestamp to format
*
* @return string|bool The formatted value or false if formatting failed
*
@@ -192,11 +192,15 @@ abstract class IntlDateFormatter
{
// intl allows timestamps to be passed as arrays - we don't
if (\is_array($timestamp)) {
- $message = 'Only integer Unix timestamps and DateTime objects are supported';
+ $message = 'Only Unix timestamps and DateTime objects are supported';
throw new MethodArgumentValueNotImplementedException(__METHOD__, 'timestamp', $timestamp, $message);
}
+ if (\is_string($timestamp) && $dt = \DateTime::createFromFormat('U', $timestamp)) {
+ $timestamp = $dt;
+ }
+
// behave like the intl extension
$argumentError = null;
if (!\is_int($timestamp) && !$timestamp instanceof \DateTimeInterface) {
@@ -212,7 +216,7 @@ abstract class IntlDateFormatter
}
if ($timestamp instanceof \DateTimeInterface) {
- $timestamp = $timestamp->getTimestamp();
+ $timestamp = $timestamp->format('U');
}
$transformer = new FullTransformer($this->getPattern(), $this->getTimeZoneId());
@@ -586,8 +590,7 @@ abstract class IntlDateFormatter
*/
protected function createDateTime($timestamp)
{
- $dateTime = new \DateTime();
- $dateTime->setTimestamp($timestamp);
+ $dateTime = \DateTime::createFromFormat('U', $timestamp);
$dateTime->setTimezone($this->dateTimeZone);
return $dateTime;

diff:
@@ -72,7 +72,7 @@ class IntlDateFormatterTest extends AbstractIntlDateFormatterTest
} catch (\Exception $e) {
$this->assertInstanceOf(MethodArgumentValueNotImplementedException::class, $e);
- $this->assertStringEndsWith('Only integer Unix timestamps and DateTime objects are supported. Please install the "intl" extension for full localization capabilities.', $e->getMessage());
+ $this->assertStringEndsWith('Only Unix timestamps and DateTime objects are supported. Please install the "intl" extension for full localization capabilities.', $e->getMessage());
}
}


message: [Intl] fix bad merge

diff:
@@ -585,7 +585,7 @@ abstract class IntlDateFormatter
*
* @return \DateTime
*/
- protected function createDateTime(int $timestamp)
+ protected function createDateTime(string $timestamp)
{
$dateTime = \DateTime::createFromFormat('U', $timestamp);
$dateTime->setTimezone($this->dateTimeZone);

original_message: [Intl] fix bad merge


message: [Intl] Fix composer.json file

original_message: [Intl] Fix composer.json file


message: [GHA] Test on PHP 8.2 as experimental and 8.1 as a regular version

diff:
@@ -56,6 +56,9 @@ abstract class AbstractIntlDateFormatterTest extends TestCase
);
}
+ /**
+ * @group legacy
+ */
public function testConstructorWithoutDateType()
{
$formatter = $this->getDateFormatter('en', null, IntlDateFormatter::SHORT, 'UTC', IntlDateFormatter::GREGORIAN);
@@ -63,6 +66,9 @@ abstract class AbstractIntlDateFormatterTest extends TestCase
$this->assertSame('EEEE, MMMM d, y \'at\' h:mm a', $formatter->getPattern());
}
+ /**
+ * @group legacy
+ */
public function testConstructorWithoutTimeType()
{
$formatter = $this->getDateFormatter('en', IntlDateFormatter::SHORT, null, 'UTC', IntlDateFormatter::GREGORIAN);


message: Fix tests on PHP 8.1

diff:
@@ -73,7 +73,7 @@ class IntlDateFormatterTest extends AbstractIntlDateFormatterTest
{
IntlTestHelper::requireFullIntl($this, '55.1');
- if (!$formatter = new \IntlDateFormatter($locale, $datetype, $timetype, $timezone, $calendar, $pattern)) {
+ if (!$formatter = new \IntlDateFormatter($locale, $datetype ?? IntlDateFormatter::FULL, $timetype ?? IntlDateFormatter::FULL, $timezone, $calendar, $pattern)) {
throw new \InvalidArgumentException(intl_get_error_message());
}

original_message: Fix tests on PHP 8.1


message: [5.4] cs fixes

diff:
@@ -57,8 +57,6 @@ class GeneratorConfig
/**
* Returns the directory where the source versions of the resource bundles
* are stored.
- *
- * @return string
*/
public function getSourceDir(): string
{
@@ -67,8 +65,6 @@ class GeneratorConfig
/**
* Returns the ICU version of the bundles being converted.
- *
- * @return string
*/
public function getIcuVersion(): string
{

diff:
@@ -66,8 +66,6 @@ final class Intl
/**
* Returns whether the intl extension is installed.
- *
- * @return bool
*/
public static function isExtensionLoaded(): bool
{
@@ -76,8 +74,6 @@ final class Intl
/**
* Returns the version of the installed ICU library.
- *
- * @return string|null
*/
public static function getIcuVersion(): ?string
{
@@ -106,8 +102,6 @@ final class Intl
/**
* Returns the version of the installed ICU data.
- *
- * @return string
*/
public static function getIcuDataVersion(): string
{
@@ -120,8 +114,6 @@ final class Intl
/**
* Returns the ICU version that the stub classes mimic.
- *
- * @return string
*/
public static function getIcuStubVersion(): string
{
@@ -130,8 +122,6 @@ final class Intl
/**
* Returns the absolute path to the data directory.
- *
- * @return string
*/
public static function getDataDirectory(): string
{

diff:
@@ -43,8 +43,6 @@ final class Locale extends \Locale
/**
* Returns the default fallback locale.
*
- * @return string|null
- *
* @see setDefaultFallback()
* @see getFallback()
*/

original_message: [5.4] cs fixes


message: [Intl] Fix EmojiTransliterator on PHP 8.2

diff:
@@ -18,8 +18,15 @@ use Symfony\Component\Intl\Transliterator\EmojiTransliterator;
/**
* @requires extension intl
*/
-final class EmojiTransliteratorTest extends TestCase
+class EmojiTransliteratorTest extends TestCase
{
+ protected function setUp(): void
+ {
+ if (\PHP_VERSION_ID >= 80200 && !(new \ReflectionProperty(\Transliterator::class, 'id'))->isReadOnly()) {
+ $this->markTestSkipped('Waiting for https://github.com/php/php-src/pull/9167 to be merged');
+ }
+ }
+
public function provideTransliterateTests(): iterable
{
yield [

diff:
namespace Symfony\Component\Intl\Transliterator;
+if (\PHP_VERSION_ID >= 80200) {
final class EmojiTransliterator extends \Transliterator
{
+ use EmojiTransliteratorTrait;
+
+ private const QUICK_CHECK = "\xE2\xE3\xF0";
+
+ public readonly string $id;
+ }
+} else {
+ final class EmojiTransliterator extends \Transliterator
+ {
+ use EmojiTransliteratorTrait;
+
private const QUICK_CHECK = "\xE2\xE3\xF0";
+ }
+}
+/**
+ * @internal
+ */
+trait EmojiTransliteratorTrait
+{
private array $map;
private \Transliterator $transliterator;
@@ -37,7 +56,14 @@ final class EmojiTransliterator extends \Transliterator
static $maps;
// Create an instance of \Transliterator with a custom id; that's the only way
+ if (\PHP_VERSION_ID >= 80200) {
+ static $newInstance;
+ $instance = ($newInstance ??= (new \ReflectionClass(self::class))->newInstanceWithoutConstructor(...))();
+ $instance->id = $id;
+ } else {
$instance = unserialize(sprintf('O:%d:"%s":1:{s:2:"id";s:%d:"%s";}', \strlen(self::class), self::class, \strlen($id), $id));
+ }
+
$instance->map = $maps[$id] ??= require \dirname(__DIR__)."/Resources/data/transliterator/emoji/{$id}.php";
return $instance;
@@ -95,10 +121,6 @@ final class EmojiTransliterator extends \Transliterator
return false;
}
- if ($cookie === $result) {
- return \strlen($string) === strcspn($string, self::QUICK_CHECK) ? $string : strtr($string, $this->map);
- }
-
$parts = explode($cookie, $result);
$start = \strlen($parts[0]);
$length = -\strlen($parts[1]) ?: null;


message: [Intl] Remove dead code in tests

diff:
@@ -20,13 +20,6 @@ use Symfony\Component\Intl\Transliterator\EmojiTransliterator;
*/
class EmojiTransliteratorTest extends TestCase
{
- protected function setUp(): void
- {
- if (\PHP_VERSION_ID >= 80200 && !(new \ReflectionProperty(\Transliterator::class, 'id'))->isReadOnly()) {
- $this->markTestSkipped('Waiting for https://github.com/php/php-src/pull/9167 to be merged');
- }
- }
-
public function provideTransliterateTests(): iterable
{
yield [

original_message: [Intl] Remove dead code in tests


message: [Intl] Get emoji-test.txt from unicode.org

old_path: Resources/emoji/Makefile

new_path: Resources/emoji/Makefile

diff:
@@ -5,6 +5,7 @@ update: ## Update sources
@composer update
@curl https://api.github.com/emojis > vendor/github-emojis.json
@curl https://raw.githubusercontent.com/iamcal/emoji-data/master/emoji.json > vendor/slack-emojis.json
+ @curl https://unicode.org/Public/emoji/latest/emoji-test.txt > vendor/emoji-test.txt
build: ## Build rules
@./build.php

diff:
@@ -6,11 +6,17 @@ This folder contains the tool to build all transliterator rules.
* composer
* PHP
+* curl
+* make
## Update the rules
To update the rules, you need to update the version of `unicode-org/cldr` in the
-`composer.json` file, then run `make update`.
+`composer.json` file, then run:
+
+```bash
+make update
+```
Finally, run the following command:

diff:
@@ -28,7 +28,7 @@ final class Builder
public static function getEmojisCodePoints(): array
{
- $lines = file(__DIR__.'/vendor/unicode-org/cldr/tools/cldr-code/src/main/resources/org/unicode/cldr/util/data/emoji/emoji-test.txt');
+ $lines = file(__DIR__.'/vendor/emoji-test.txt');
$emojisCodePoints = [];
foreach ($lines as $line) {


message: [Intl] Fix tests

diff:
@@ -35,10 +35,18 @@ class QuarterTransformer extends Transformer
return $this->padLeft($quarter, $length);
case 3:
return 'Q'.$quarter;
+ case 4:
+ $map = [1 => '1st quarter', 2 => '2nd quarter', 3 => '3rd quarter', 4 => '4th quarter'];
+
+ return $map[$quarter];
default:
+ if (\defined('INTL_ICU_VERSION') && version_compare(\INTL_ICU_VERSION, '70.1', '<')) {
$map = [1 => '1st quarter', 2 => '2nd quarter', 3 => '3rd quarter', 4 => '4th quarter'];
return $map[$quarter];
+ } else {
+ return $quarter;
+ }
}
}

diff:
@@ -96,6 +96,12 @@ abstract class AbstractIntlDateFormatterTest extends TestCase
$dateTime = new \DateTime('@0');
$dateTimeImmutable = new \DateTimeImmutable('@0');
+ /* https://unicode-org.atlassian.net/browse/ICU-21647 */
+ $expectedQuarterX5 = '1';
+ if (\defined('INTL_ICU_VERSION') && version_compare(\INTL_ICU_VERSION, '70.1', '<')) {
+ $expectedQuarterX5 = '1st quarter';
+ }
+
$formatData = [
/* general */
['y-M-d', 0, '1970-1-1'],
@@ -144,13 +150,13 @@ abstract class AbstractIntlDateFormatterTest extends TestCase
['QQ', 0, '01'],
['QQQ', 0, 'Q1'],
['QQQQ', 0, '1st quarter'],
- ['QQQQQ', 0, '1st quarter'],
+ ['QQQQQ', 0, $expectedQuarterX5],
['q', 0, '1'],
['qq', 0, '01'],
['qqq', 0, 'Q1'],
['qqqq', 0, '1st quarter'],
- ['qqqqq', 0, '1st quarter'],
+ ['qqqqq', 0, $expectedQuarterX5],
// 4 months
['Q', 7776000, '2'],
@@ -363,6 +369,10 @@ abstract class AbstractIntlDateFormatterTest extends TestCase
*/
public function testFormatTimezone($pattern, $timezone, $expected)
{
+ if ((80114 === \PHP_VERSION_ID || 80201 === \PHP_VERSION_ID) && str_contains($timezone, 'GMT')) {
+ $this->markTestSkipped('Broken version of PHP');
+ }
+
$formatter = $this->getDefaultDateFormatter($pattern);
$formatter->setTimeZone(new \DateTimeZone($timezone));
@@ -421,6 +431,10 @@ abstract class AbstractIntlDateFormatterTest extends TestCase
public function testFormatWithGmtTimezone()
{
+ if (80114 === \PHP_VERSION_ID || 80201 === \PHP_VERSION_ID) {
+ $this->markTestSkipped('Broken version of PHP');
+ }
+
$formatter = $this->getDefaultDateFormatter('zzzz');
$formatter->setTimeZone('GMT+03:00');
@@ -430,6 +444,10 @@ abstract class AbstractIntlDateFormatterTest extends TestCase
public function testFormatWithGmtTimeZoneAndMinutesOffset()
{
+ if (80114 === \PHP_VERSION_ID || 80201 === \PHP_VERSION_ID) {
+ $this->markTestSkipped('Broken version of PHP');
+ }
+
$formatter = $this->getDefaultDateFormatter('zzzz');
$formatter->setTimeZone('GMT+00:30');
@@ -794,6 +812,10 @@ abstract class AbstractIntlDateFormatterTest extends TestCase
public function parseTimezoneProvider()
{
+ if (80114 === \PHP_VERSION_ID || 80201 === \PHP_VERSION_ID) {
+ return [['y-M-d HH:mm:ss', '1970-1-1 00:00:00', 0]];
+ }
+
return [
['y-M-d HH:mm:ss zzzz', '1970-1-1 00:00:00 GMT-03:00', 10800],
['y-M-d HH:mm:ss zzzz', '1970-1-1 00:00:00 GMT-04:00', 14400],
@@ -912,6 +934,10 @@ abstract class AbstractIntlDateFormatterTest extends TestCase
*/
public function testSetTimeZoneId($timeZoneId, $expectedTimeZoneId)
{
+ if ((80114 === \PHP_VERSION_ID || 80201 === \PHP_VERSION_ID) && str_contains($timeZoneId ?? '', 'GMT')) {
+ $this->markTestSkipped('Broken version of PHP');
+ }
+
$formatter = $this->getDefaultDateFormatter();
$formatter->setTimeZone($timeZoneId);

diff:
@@ -186,6 +186,10 @@ class IntlDateFormatterTest extends AbstractIntlDateFormatterTest
protected function getDateFormatter($locale, $datetype, $timetype, $timezone = null, $calendar = IntlDateFormatter::GREGORIAN, $pattern = null)
{
+ if ((80114 === \PHP_VERSION_ID || 80201 === \PHP_VERSION_ID) && \is_string($timezone) && str_contains($timezone, 'GMT')) {
+ $this->markTestSkipped('Broken version of PHP');
+ }
+
return new class($locale, $datetype, $timetype, $timezone, $calendar, $pattern) extends IntlDateFormatter {
};
}

diff:
@@ -35,6 +35,10 @@ class IntlDateFormatterTest extends AbstractIntlDateFormatterTest
*/
public function testFormatTimezone($pattern, $timezone, $expected)
{
+ if ((80114 === \PHP_VERSION_ID || 80201 === \PHP_VERSION_ID) && str_contains($timezone, 'GMT')) {
+ $this->markTestSkipped('Broken version of PHP');
+ }
+
IntlTestHelper::requireFullIntl($this, '59.1');
parent::testFormatTimezone($pattern, $timezone, $expected);
@@ -59,6 +63,10 @@ class IntlDateFormatterTest extends AbstractIntlDateFormatterTest
protected function getDateFormatter($locale, $datetype, $timetype, $timezone = null, $calendar = IntlDateFormatter::GREGORIAN, $pattern = null)
{
+ if ((80114 === \PHP_VERSION_ID || 80201 === \PHP_VERSION_ID) && \is_string($timezone) && str_contains($timezone, 'GMT')) {
+ $this->markTestSkipped('Broken version of PHP');
+ }
+
IntlTestHelper::requireFullIntl($this, '55.1');
if (!$formatter = new \IntlDateFormatter($locale, $datetype ?? IntlDateFormatter::FULL, $timetype ?? IntlDateFormatter::FULL, $timezone, $calendar, $pattern)) {

original_message: [Intl] Fix tests


message: database: Add 5.x version schema.

diff:
@@ -28,9 +28,9 @@ class zabbix::database::mysql (
assert_private()
#
- # Adjustments for version 3.0/4.0 - structure of package with sqls differs from previous versions
+ # Adjustments for version 3.x/4.x/5.x - structure of package with sqls differs from previous versions
case $zabbix_version {
- /^(3|4).\d+$/: {
+ /^(3|4|5).\d+$/: {
if ($database_schema_path == false) or ($database_schema_path == '') {
$schema_path = '/usr/share/doc/zabbix-*-mysql*'
}

diff:
@@ -28,9 +28,9 @@ class zabbix::database::postgresql (
assert_private()
#
- # Adjustments for version 3.0/4.0 - structure of package with sqls differs from previous versions
+ # Adjustments for version 3.x/4.x/5.x - structure of package with sqls differs from previous versions
case $zabbix_version {
- /^(3|4).\d+$/: {
+ /^(3|4|5).\d+$/: {
if ($database_schema_path == false) or ($database_schema_path == '') {
case $facts['os']['name'] {
'CentOS', 'RedHat', 'OracleLinux', 'VirtuozzoLinux': {

diff:
@@ -355,9 +355,7 @@ class zabbix::web (
require => Class['zabbix::repo'],
tag => 'zabbix',
}
-
} else {
-
package { "zabbix-web-${db}":
ensure => $zabbix_package_state,
before => Package[$zabbix_web_package],

diff:
@@ -6,7 +6,7 @@ def agent_supported(version)
true
end
-['2.4', '3.2', '3.4', '4.0', '4.2', '4.4'].each do |version|
+['2.4', '3.2', '3.4', '4.0', '4.2', '4.4', '5.0', '5.2'].each do |version|
describe "zabbix::agent class with zabbix_version #{version}", if: agent_supported(version) do
it 'works idempotently with no errors' do
pp = <<-EOS

diff:
@@ -26,7 +26,7 @@ describe 'zabbix_application type', unless: default[:platform] =~ %r{debian-10-a
-> class { 'postgresql::server': }
class { 'zabbix':
- zabbix_version => '4.4',
+ zabbix_version => '5.0',
zabbix_url => 'localhost',
zabbix_api_user => 'Admin',
zabbix_api_pass => 'zabbix',

license: Apache License 2.0

repo: voxpupuli/puppet-zabbix

original_message: database: Add 5.x version schema.


message: repo: Fix 5.0 frontend for RHEL7

diff:
@@ -166,6 +166,7 @@ class zabbix::params {
$manage_apt = true
$repo_location = undef
$unsupported_repo_location = undef
+ $frontend_repo_location = undef
$manage_resources = false
$manage_vhost = true
$database_path = '/usr/sbin'

diff:
@@ -35,6 +35,7 @@ class zabbix::repo (
Boolean $manage_repo = $zabbix::params::manage_repo,
Boolean $manage_apt = $zabbix::params::manage_apt,
Optional[Stdlib::HTTPUrl] $repo_location = $zabbix::params::repo_location,
+ Optional[Stdlib::HTTPUrl] $frontend_repo_location = $zabbix::params::frontend_repo_location,
Optional[Stdlib::HTTPUrl] $unsupported_repo_location = $zabbix::params::unsupported_repo_location,
String[1] $zabbix_version = $zabbix::params::zabbix_version,
) inherits zabbix::params {
@@ -93,7 +94,8 @@ class zabbix::repo (
priority => '1',
}
- if ($facts['os']['name'] == 'CentOS' and $majorrelease == '7') {
+ # Zabbix 5.0 frontend on CentOS 7 has different location.
+ if ($facts['os']['name'] == 'CentOS' and $majorrelease == '7' and $zabbix_version == '5.0') {
$_frontend_repo_location = $frontend_repo_location ? {
undef => "https://repo.zabbix.com/zabbix/${zabbix_version}/rhel/${majorrelease}/\$basearch/frontend",
default => $frontend_repo_location,

diff:
@@ -340,13 +340,12 @@ class zabbix::web (
],
}
}
- 'CentOS': {
+ 'CentOS', 'RedHat': {
$zabbix_web_package = 'zabbix-web'
- if ($facts['os']['release']['major'] == '7'){
-
+ if ($facts['os']['release']['major'] == '7' and $zabbix_version == '5.0') {
package { 'zabbix-required-scl-repo':
+ ensure => 'latest',
name => 'centos-release-scl',
- ensure => 'latest'
}
package { "zabbix-web-${db}-scl":
@@ -362,7 +361,6 @@ class zabbix::web (
require => Class['zabbix::repo'],
tag => 'zabbix',
}
-
}
}
default: {
@@ -409,11 +407,19 @@ class zabbix::web (
include apache::mod::proxy
include apache::mod::proxy_fcgi
$apache_vhost_custom_fragment = ''
- #php parameters are moved to /etc/opt/rh/rh-php72/php-fpm.d/zabbix.conf per package zabbix-web-deps-scl
+
+ service { 'rh-php72-php-fpm':
+ ensure => 'running',
+ enable => true,
+ }
+
+ # PHP parameters are moved to /etc/opt/rh/rh-php72/php-fpm.d/zabbix.conf per package zabbix-web-deps-scl
file { '/etc/opt/rh/rh-php72/php-fpm.d/zabbix.conf':
ensure => file,
+ notify => Service['rh-php72-php-fpm'],
content => epp('zabbix/web/php-fpm.d.zabbix.conf.epp'),
}
+
$fcgi_filematch = {
path => '/usr/share/zabbix',
provider => 'directory',

diff:
@@ -53,9 +53,13 @@ describe 'zabbix::web' do
it { is_expected.not_to contain_selboolean('httpd_can_connect_zabbix') }
end
- describe 'with database_type as postgresql' do
+ %w[4.4 5.0].each do |zabbix_version|
+ describe "with database_type as postgresql and zabbix_version #{zabbix_version}" do
+ next if zabbix_version == '5.0' and %w[Debian Ubuntu].include?(facts[:osfamily]) and
+ %w[16.04 9].include?(facts[:operatingsystemmajrelease])
let :params do
super().merge(database_type: 'postgresql')
+ super().merge(zabbix_version: zabbix_version)
end
pgsqlpackage = case facts[:operatingsystem]
@@ -75,13 +79,26 @@ describe 'zabbix::web' do
'php5-pgsql'
end
- packages = facts[:osfamily] == 'RedHat' ? ['zabbix-web-pgsql', 'zabbix-web'] : ['zabbix-frontend-php', pgsqlpackage]
+ if facts[:osfamily] == 'RedHat'
+ if facts[:operatingsystemmajrelease].to_i == 7 and
+ !['VirtuozzoLinux', 'OracleLinux', 'Scientific'].include?(facts[:os]['name']) and
+ zabbix_version == '5.0'
+ packages = ['zabbix-web-pgsql-scl', 'zabbix-web']
+ else
+ packages = ['zabbix-web-pgsql', 'zabbix-web']
+ end
+ else
+ packages = ['zabbix-frontend-php', pgsqlpackage]
+ end
+
packages.each do |package|
it { is_expected.to contain_package(package) }
end
it { is_expected.to contain_file('/etc/zabbix/web/zabbix.conf.php').with_content(%r{^\$DB\['TYPE'\] = 'POSTGRESQL'}) }
end
+ end
+ %w[4.4 5.0].each do |zabbix_version|
describe 'with database_type as mysql' do
let :params do
super().merge(database_type: 'mysql')
@@ -110,6 +127,7 @@ describe 'zabbix::web' do
end
it { is_expected.to contain_file('/etc/zabbix/web/zabbix.conf.php').with_content(%r{^\$DB\['TYPE'\] = 'MYSQL'}) }
end
+ end
it { is_expected.to contain_file('/etc/zabbix/web/zabbix.conf.php') }

diff:
@@ -10,6 +10,9 @@ def prepare_host
cleanup_script = <<-SHELL
/opt/puppetlabs/bin/puppet resource service zabbix-server ensure=stopped
/opt/puppetlabs/bin/puppet resource package zabbix-server-pgsql ensure=purged
+ /opt/puppetlabs/bin/puppet resource package zabbix-server-pgsql-scl ensure=purged
+ /opt/puppetlabs/bin/puppet resource package zabbix-web ensure=purged
+ /opt/puppetlabs/bin/puppet resource package zabbix-frontend-php ensure=purged
rm -f /etc/zabbix/.*done
if id postgres > /dev/null 2>&1; then
su - postgres -c "psql -c 'drop database if exists zabbix_server;'"

diff:
-# THIS FILE IS MANAGED BY PUPPET
+;THIS FILE IS MANAGED BY PUPPET
[zabbix]
user = apache
group = apache
@@ -16,12 +16,12 @@ pm.max_spare_servers = 35
php_value[session.save_handler] = files
php_value[session.save_path] = /var/opt/rh/rh-php72/lib/php/session/
-php_value max_execution_time <%= $zabbix::web::apache_php_max_execution_time %>
-php_value memory_limit <%= $zabbix::web::apache_php_memory_limit %>
-php_value post_max_size <%= $zabbix::web::apache_php_post_max_size %>
-php_value upload_max_filesize <%= $zabbix::web::apache_php_upload_max_filesize %>
-php_value max_input_time <%= $zabbix::web::apache_php_max_input_time %>
-php_value always_populate_raw_post_data <%= $zabbix::web::apache_php_always_populate_raw_post_data %>
-php_value max_input_vars <%= $zabbix::web::apache_php_max_input_vars %>
-# Set correct timezone
-php_value date.timezone <%= $zabbix::web::zabbix_timezone %>
+php_value[max_execution_time] = <%= $zabbix::web::apache_php_max_execution_time %>
+php_value[memory_limit] = <%= $zabbix::web::apache_php_memory_limit %>
+php_value[post_max_size] = <%= $zabbix::web::apache_php_post_max_size %>
+php_value[upload_max_filesize] = <%= $zabbix::web::apache_php_upload_max_filesize %>
+php_value[max_input_time] = <%= $zabbix::web::apache_php_max_input_time %>
+php_value[always_populate_raw_post_data] = <%= $zabbix::web::apache_php_always_populate_raw_post_data %>
+php_value[max_input_vars] = <%= $zabbix::web::apache_php_max_input_vars %>
+;Set correct timezone
+php_value[date.timezone] = <%= $zabbix::web::zabbix_timezone %>

original_message:
repo: Fix 5.0 frontend for RHEL7

Signed-off-by: Christos Papageorgiou <root.expert.xda@gmail.com>


diff:
@@ -67,7 +67,9 @@ describe 'zabbix::database::mysql' do
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_exec('zabbix_proxy_create.sql').with_command("cd #{path2} && if [ -f schema.sql.gz ]; then gunzip -f schema.sql.gz ; fi && mysql -h 'rspec.puppet.com' -u 'zabbix-proxy' -p'zabbix-proxy' -D 'zabbix-proxy' < schema.sql && touch /etc/zabbix/.schema.done") }
end
- context 'when zabbix_type is server and zabbix version is 3.0' do
+
+ %w[3.0 3.2 3.4 4.0 4.2 4.4 5.0 5.2].each do |zabbix_version|
+ context "when zabbix_type is server and zabbix version is #{zabbix_version}" do
let :params do
{
database_name: 'zabbix-server',
@@ -75,7 +77,7 @@ describe 'zabbix::database::mysql' do
database_password: 'zabbix-server',
database_host: 'rspec.puppet.com',
zabbix_type: 'server',
- zabbix_version: '3.0'
+ zabbix_version: zabbix_version
}
end
@@ -84,9 +86,8 @@ describe 'zabbix::database::mysql' do
it { is_expected.to contain_exec('zabbix_server_create.sql').with_command("cd #{path3} && if [ -f create.sql.gz ]; then gunzip -f create.sql.gz ; fi && mysql -h 'rspec.puppet.com' -u 'zabbix-server' -p'zabbix-server' -D 'zabbix-server' < create.sql && touch /etc/zabbix/.schema.done") }
it { is_expected.to contain_exec('zabbix_server_images.sql').with_command('touch /etc/zabbix/.images.done') }
it { is_expected.to contain_exec('zabbix_server_data.sql').with_command('touch /etc/zabbix/.data.done') }
- end
- describe 'when zabbix_type is proxy and zabbix version is 3.0' do
+ describe "when zabbix_type is proxy and zabbix version is #{zabbix_version}" do
let :params do
{
database_name: 'zabbix-proxy',
@@ -94,7 +95,7 @@ describe 'zabbix::database::mysql' do
database_password: 'zabbix-proxy',
database_host: 'rspec.puppet.com',
zabbix_type: 'proxy',
- zabbix_version: '3.0'
+ zabbix_version: zabbix_version
}
end
@@ -102,40 +103,7 @@ describe 'zabbix::database::mysql' do
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_exec('zabbix_proxy_create.sql').with_command("cd #{path3} && if [ -f schema.sql.gz ]; then gunzip -f schema.sql.gz ; fi && mysql -h 'rspec.puppet.com' -u 'zabbix-proxy' -p'zabbix-proxy' -D 'zabbix-proxy' < schema.sql && touch /etc/zabbix/.schema.done") }
end
- context 'when zabbix_type is server and zabbix version is 3.2' do
- let :params do
- {
- database_name: 'zabbix-server',
- database_user: 'zabbix-server',
- database_password: 'zabbix-server',
- database_host: 'rspec.puppet.com',
- zabbix_type: 'server',
- zabbix_version: '3.2'
- }
end
-
- it { is_expected.to contain_class('zabbix::database::mysql') }
- it { is_expected.to compile.with_all_deps }
- it { is_expected.to contain_exec('zabbix_server_create.sql').with_command("cd #{path3} && if [ -f create.sql.gz ]; then gunzip -f create.sql.gz ; fi && mysql -h 'rspec.puppet.com' -u 'zabbix-server' -p'zabbix-server' -D 'zabbix-server' < create.sql && touch /etc/zabbix/.schema.done") }
- it { is_expected.to contain_exec('zabbix_server_images.sql').with_command('touch /etc/zabbix/.images.done') }
- it { is_expected.to contain_exec('zabbix_server_data.sql').with_command('touch /etc/zabbix/.data.done') }
- end
-
- describe 'when zabbix_type is proxy and zabbix version is 3.2' do
- let :params do
- {
- database_name: 'zabbix-proxy',
- database_user: 'zabbix-proxy',
- database_password: 'zabbix-proxy',
- database_host: 'rspec.puppet.com',
- zabbix_type: 'proxy',
- zabbix_version: '3.2'
- }
- end
-
- it { is_expected.to contain_class('zabbix::database::mysql') }
- it { is_expected.to compile.with_all_deps }
- it { is_expected.to contain_exec('zabbix_proxy_create.sql').with_command("cd #{path3} && if [ -f schema.sql.gz ]; then gunzip -f schema.sql.gz ; fi && mysql -h 'rspec.puppet.com' -u 'zabbix-proxy' -p'zabbix-proxy' -D 'zabbix-proxy' < schema.sql && touch /etc/zabbix/.schema.done") }
end
end
end

diff:
@@ -17,8 +17,26 @@ describe 'zabbix::database::postgresql' do
end
case facts[:os]['name']
- when 'CentOS', 'RedHat'
- describe 'when zabbix_type is server' do
+ when 'CentOS', 'RedHat', 'OracleLinux', 'VirtuozzoLinux'
+ # Path for version 2.4 on RedHat
+ path_for2 = "/usr/share/doc/zabbix-*-pgsql-2.4*/create"
+ else
+ # Path for version 2.4 on Debian
+ path_for2 = "/usr/share/zabbix-*-pgsql"
+ end
+
+ %w[2.4 3.2 3.4 4.0 4.2 4.4 5.0 5.2].each do |zabbix_version|
+
+ case facts[:os]['name']
+ when 'CentOS', 'RedHat', 'OracleLinux', 'VirtuozzoLinux'
+ # Path for versions >= 3.x on RedHat
+ path_for3_and_up = "/usr/share/doc/zabbix-*-pgsql-#{zabbix_version}*/"
+ else
+ # Path for versions >= 3.x on Debian
+ path_for3_and_up = "/usr/share/doc/zabbix-*-pgsql"
+ end
+
+ describe "when zabbix_type is server and version is #{zabbix_version}" do
let :params do
{
database_name: 'zabbix-server',
@@ -26,20 +44,26 @@ describe 'zabbix::database::postgresql' do
database_password: 'zabbix-server',
database_host: 'node01.example.com',
zabbix_type: 'server',
- zabbix_version: '2.4'
+ zabbix_version: zabbix_version
}
end
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_exec('update_pgpass').with_command('echo node01.example.com:5432:zabbix-server:zabbix-server:zabbix-server >> /root/.pgpass') }
- it { is_expected.to contain_exec('zabbix_server_create.sql').with_command("cd /usr/share/doc/zabbix-*-pgsql-2.4*/create && if [ -f schema.sql.gz ]; then gunzip -f schema.sql.gz ; fi && psql -h 'node01.example.com' -U 'zabbix-server' -d 'zabbix-server' -f schema.sql && touch /etc/zabbix/.schema.done") }
- it { is_expected.to contain_exec('zabbix_server_images.sql').with_command("cd /usr/share/doc/zabbix-*-pgsql-2.4*/create && if [ -f images.sql.gz ]; then gunzip -f images.sql.gz ; fi && psql -h 'node01.example.com' -U 'zabbix-server' -d 'zabbix-server' -f images.sql && touch /etc/zabbix/.images.done") }
- it { is_expected.to contain_exec('zabbix_server_data.sql').with_command("cd /usr/share/doc/zabbix-*-pgsql-2.4*/create && if [ -f data.sql.gz ]; then gunzip -f data.sql.gz ; fi && psql -h 'node01.example.com' -U 'zabbix-server' -d 'zabbix-server' -f data.sql && touch /etc/zabbix/.data.done") }
+ if zabbix_version != '2.4'
+ it { is_expected.to contain_exec('zabbix_server_create.sql').with_command("cd #{path_for3_and_up} && if [ -f create.sql.gz ]; then gunzip -f create.sql.gz ; fi && psql -h 'node01.example.com' -U 'zabbix-server' -d 'zabbix-server' -f create.sql && touch /etc/zabbix/.schema.done") }
+ it { is_expected.to contain_exec('zabbix_server_images.sql').with_command("touch /etc/zabbix/.images.done") }
+ it { is_expected.to contain_exec('zabbix_server_data.sql').with_command("touch /etc/zabbix/.data.done") }
+ else
+ it { is_expected.to contain_exec('zabbix_server_create.sql').with_command("cd #{path_for2} && if [ -f schema.sql.gz ]; then gunzip -f schema.sql.gz ; fi && psql -h 'node01.example.com' -U 'zabbix-server' -d 'zabbix-server' -f schema.sql && touch /etc/zabbix/.schema.done") }
+ it { is_expected.to contain_exec('zabbix_server_images.sql').with_command("cd #{path_for2} && if [ -f images.sql.gz ]; then gunzip -f images.sql.gz ; fi && psql -h 'node01.example.com' -U 'zabbix-server' -d 'zabbix-server' -f images.sql && touch /etc/zabbix/.images.done") }
+ it { is_expected.to contain_exec('zabbix_server_data.sql').with_command("cd #{path_for2} && if [ -f data.sql.gz ]; then gunzip -f data.sql.gz ; fi && psql -h 'node01.example.com' -U 'zabbix-server' -d 'zabbix-server' -f data.sql && touch /etc/zabbix/.data.done") }
+ end
it { is_expected.to contain_file('/root/.pgpass') }
it { is_expected.to contain_class('zabbix::params') }
end
- describe 'when zabbix_type is proxy' do
+ describe "when zabbix_type is proxy and version is #{zabbix_version}" do
let :params do
{
database_name: 'zabbix-proxy',
@@ -47,13 +71,17 @@ describe 'zabbix::database::postgresql' do
database_password: 'zabbix-proxy',
database_host: 'node01.example.com',
zabbix_type: 'proxy',
- zabbix_version: '2.4'
+ zabbix_version: zabbix_version
}
end
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_exec('update_pgpass').with_command('echo node01.example.com:5432:zabbix-proxy:zabbix-proxy:zabbix-proxy >> /root/.pgpass') }
- it { is_expected.to contain_exec('zabbix_proxy_create.sql').with_command("cd /usr/share/doc/zabbix-*-pgsql-2.4*/create && if [ -f schema.sql.gz ]; then gunzip -f schema.sql.gz ; fi && psql -h 'node01.example.com' -U 'zabbix-proxy' -d 'zabbix-proxy' -f schema.sql && touch /etc/zabbix/.schema.done") }
+ if zabbix_version != '2.4'
+ it { is_expected.to contain_exec('zabbix_proxy_create.sql').with_command("cd #{path_for3_and_up} && if [ -f schema.sql.gz ]; then gunzip -f schema.sql.gz ; fi && psql -h 'node01.example.com' -U 'zabbix-proxy' -d 'zabbix-proxy' -f schema.sql && touch /etc/zabbix/.schema.done") }
+ else
+ it { is_expected.to contain_exec('zabbix_proxy_create.sql').with_command("cd #{path_for2} && if [ -f schema.sql.gz ]; then gunzip -f schema.sql.gz ; fi && psql -h 'node01.example.com' -U 'zabbix-proxy' -d 'zabbix-proxy' -f schema.sql && touch /etc/zabbix/.schema.done") }
+ end
it { is_expected.to contain_class('zabbix::params') }
end
end

original_message:
spec: Add all versions of server/proxy for databases

Signed-off-by: Christos Papageorgiou <root.expert.xda@gmail.com>


message: spec: Fix some rubocop offences

diff:
@@ -19,21 +19,20 @@ describe 'zabbix::database::postgresql' do
case facts[:os]['name']
when 'CentOS', 'RedHat', 'OracleLinux', 'VirtuozzoLinux'
# Path for version 2.4 on RedHat
- path_for2 = "/usr/share/doc/zabbix-*-pgsql-2.4*/create"
+ path_for2 = '/usr/share/doc/zabbix-*-pgsql-2.4*/create'
else
# Path for version 2.4 on Debian
- path_for2 = "/usr/share/zabbix-*-pgsql"
+ path_for2 = '/usr/share/zabbix-*-pgsql'
end
%w[2.4 3.2 3.4 4.0 4.2 4.4 5.0 5.2].each do |zabbix_version|
-
case facts[:os]['name']
when 'CentOS', 'RedHat', 'OracleLinux', 'VirtuozzoLinux'
# Path for versions >= 3.x on RedHat
path_for3_and_up = "/usr/share/doc/zabbix-*-pgsql-#{zabbix_version}*/"
else
# Path for versions >= 3.x on Debian
- path_for3_and_up = "/usr/share/doc/zabbix-*-pgsql"
+ path_for3_and_up = '/usr/share/doc/zabbix-*-pgsql'
end
describe "when zabbix_type is server and version is #{zabbix_version}" do
@@ -52,8 +51,8 @@ describe 'zabbix::database::postgresql' do
it { is_expected.to contain_exec('update_pgpass').with_command('echo node01.example.com:5432:zabbix-server:zabbix-server:zabbix-server >> /root/.pgpass') }
if zabbix_version != '2.4'
it { is_expected.to contain_exec('zabbix_server_create.sql').with_command("cd #{path_for3_and_up} && if [ -f create.sql.gz ]; then gunzip -f create.sql.gz ; fi && psql -h 'node01.example.com' -U 'zabbix-server' -d 'zabbix-server' -f create.sql && touch /etc/zabbix/.schema.done") }
- it { is_expected.to contain_exec('zabbix_server_images.sql').with_command("touch /etc/zabbix/.images.done") }
- it { is_expected.to contain_exec('zabbix_server_data.sql').with_command("touch /etc/zabbix/.data.done") }
+ it { is_expected.to contain_exec('zabbix_server_images.sql').with_command('touch /etc/zabbix/.images.done') }
+ it { is_expected.to contain_exec('zabbix_server_data.sql').with_command('touch /etc/zabbix/.data.done') }
else
it { is_expected.to contain_exec('zabbix_server_create.sql').with_command("cd #{path_for2} && if [ -f schema.sql.gz ]; then gunzip -f schema.sql.gz ; fi && psql -h 'node01.example.com' -U 'zabbix-server' -d 'zabbix-server' -f schema.sql && touch /etc/zabbix/.schema.done") }
it { is_expected.to contain_exec('zabbix_server_images.sql').with_command("cd #{path_for2} && if [ -f images.sql.gz ]; then gunzip -f images.sql.gz ; fi && psql -h 'node01.example.com' -U 'zabbix-server' -d 'zabbix-server' -f images.sql && touch /etc/zabbix/.images.done") }

diff:
@@ -79,16 +79,16 @@ describe 'zabbix::web' do
'php5-pgsql'
end
- if facts[:osfamily] == 'RedHat'
- if facts[:operatingsystemmajrelease].to_i == 7 and
- !['VirtuozzoLinux', 'OracleLinux', 'Scientific'].include?(facts[:os]['name']) and
+ packages = if facts[:osfamily] == 'RedHat'
+ if facts[:operatingsystemmajrelease].to_i == 7 &&
+ !%w[VirtuozzoLinux OracleLinux Scientific].include?(facts[:os]['name']) &&
zabbix_version == '5.0'
- packages = ['zabbix-web-pgsql-scl', 'zabbix-web']
+ ['zabbix-web-pgsql-scl', 'zabbix-web']
else
- packages = ['zabbix-web-pgsql', 'zabbix-web']
+ ['zabbix-web-pgsql', 'zabbix-web']
end
else
- packages = ['zabbix-frontend-php', pgsqlpackage]
+ ['zabbix-frontend-php', pgsqlpackage]
end
packages.each do |package|
@@ -98,7 +98,6 @@ describe 'zabbix::web' do
end
end
- %w[4.4 5.0].each do |zabbix_version|
describe 'with database_type as mysql' do
let :params do
super().merge(database_type: 'mysql')
@@ -127,7 +126,6 @@ describe 'zabbix::web' do
end
it { is_expected.to contain_file('/etc/zabbix/web/zabbix.conf.php').with_content(%r{^\$DB\['TYPE'\] = 'MYSQL'}) }
end
- end
it { is_expected.to contain_file('/etc/zabbix/web/zabbix.conf.php') }

original_message:
spec: Fix some rubocop offences

Signed-off-by: Christos Papageorgiou <root.expert.xda@gmail.com>


message: web: Add API for 5.x versions

diff:
@@ -279,9 +279,12 @@ class zabbix::web (
'3.4' : {
$zabbixapi_version = '4.0.0'
}
- default : {
+ /^4\.\d{1}$/: {
$zabbixapi_version = '4.2.0'
}
+ default : {
+ $zabbixapi_version = '5.0.0-alpha1'
+ }
}
# Installing the zabbixapi gem package. We need this gem for

original_message:
web: Add API for 5.x versions

Signed-off-by: Christos Papageorgiou <root.expert.xda@gmail.com>


diff:
@@ -30,7 +30,7 @@ class zabbix::database::mysql (
#
# Adjustments for version 3.x/4.x/5.x - structure of package with sqls differs from previous versions
case $zabbix_version {
- /^(3|4|5).\d+$/: {
+ /^[345].\d+$/: {
if ($database_schema_path == false) or ($database_schema_path == '') {
$schema_path = '/usr/share/doc/zabbix-*-mysql*'
}

diff:
@@ -30,7 +30,7 @@ class zabbix::database::postgresql (
#
# Adjustments for version 3.x/4.x/5.x - structure of package with sqls differs from previous versions
case $zabbix_version {
- /^(3|4|5).\d+$/: {
+ /^[345].\d+$/: {
if ($database_schema_path == false) or ($database_schema_path == '') {
case $facts['os']['name'] {
'CentOS', 'RedHat', 'OracleLinux', 'VirtuozzoLinux': {

diff:
@@ -237,6 +237,14 @@ class zabbix::web (
fail("${facts['os']['family']} is currently not supported for zabbix::web")
}
+ # zabbix frontend 5.x is not supported, among others, on stretch and xenial.
+ # https://www.zabbix.com/documentation/current/manual/installation/frontend/frontend_on_debian
+ if $facts['os']['name'] in ['ubuntu', 'debian'] and versioncmp($zabbix_version, '5') >= 0 {
+ if versioncmp($facts['os']['release']['major'], '16.04') == 0 or versioncmp($facts['os']['release']['major'], '9') == 0 {
+ fail("${facts['os']['family']} ${$facts['os']['release']['major']} is not supported for zabbix::web")
+ }
+ }
+
# Only include the repo class if it has not yet been included
unless defined(Class['Zabbix::Repo']) {
class { 'zabbix::repo':
@@ -279,7 +287,10 @@ class zabbix::web (
'3.4' : {
$zabbixapi_version = '4.0.0'
}
- /^4\.\d{1}$/: {
+ /^4\.[02]$/: {
+ $zabbixapi_version = '4.1.2'
+ }
+ '4.4': {
$zabbixapi_version = '4.2.0'
}
default : {
@@ -345,7 +356,7 @@ class zabbix::web (
}
'CentOS', 'RedHat': {
$zabbix_web_package = 'zabbix-web'
- if ($facts['os']['release']['major'] == '7' and $zabbix_version == '5.0') {
+ if ($facts['os']['release']['major'] == '7' and versioncmp($zabbix_version, '5') >= 0) {
package { 'zabbix-required-scl-repo':
ensure => 'latest',
name => 'centos-release-scl',
@@ -403,6 +414,17 @@ class zabbix::web (
content => template('zabbix/web/zabbix.conf.php.erb'),
}
+ # For API to work on Zabbix 5.x zabbix.conf.php needs to be in the root folder.
+ if versioncmp($zabbix_version, '5') >= 0 {
+ file { '/etc/zabbix/zabbix.conf.php':
+ ensure => link,
+ target => '/etc/zabbix/web/zabbix.conf.php',
+ owner => $web_config_owner,
+ group => $web_config_group,
+ mode => '0640',
+ }
+ }
+
# Is set to true, it will create the apache vhost.
if $manage_vhost {
include apache

diff:
@@ -2,7 +2,7 @@ require 'spec_helper_acceptance'
require 'serverspec_type_zabbixapi'
# rubocop:disable RSpec/LetBeforeExamples
-describe 'zabbix_application type', unless: default[:platform] =~ %r{debian-10-amd64} do
+describe 'zabbix_application type', unless: default[:platform] =~ %r{(ubuntu-16.04|debian-9|debian-10)-amd64} do
context 'create zabbix_application resources' do
# This will deploy a running Zabbix setup (server, web, db) which we can
# use for custom type tests

diff:
@@ -2,7 +2,7 @@ require 'spec_helper_acceptance'
require 'serverspec_type_zabbixapi'
# rubocop:disable RSpec/LetBeforeExamples
-describe 'zabbix_host type', unless: default[:platform] =~ %r{debian-10-amd64} do
+describe 'zabbix_host type', unless: default[:platform] =~ %r{(ubuntu-16.04|debian-9|debian-10)-amd64} do
context 'create zabbix_host resources' do
# This will deploy a running Zabbix setup (server, web, db) which we can
# use for custom type tests
@@ -20,7 +20,7 @@ class { 'postgresql::globals':
-> class { 'postgresql::server': }
class { 'zabbix':
- zabbix_version => '4.4',
+ zabbix_version => '5.0',
zabbix_url => 'localhost',
zabbix_api_user => 'Admin',
zabbix_api_pass => 'zabbix',

diff:
@@ -2,7 +2,7 @@ require 'spec_helper_acceptance'
require 'serverspec_type_zabbixapi'
# rubocop:disable RSpec/LetBeforeExamples
-describe 'zabbix_hostgroup type', unless: default[:platform] =~ %r{debian-10-amd64} do
+describe 'zabbix_hostgroup type', unless: default[:platform] =~ %r{(ubuntu-16.04|debian-9|debian-10)-amd64} do
context 'create zabbix_hostgroup resources' do
it 'runs successfully' do
# This will deploy a running Zabbix setup (server, web, db) which we can
@@ -21,7 +21,7 @@ describe 'zabbix_hostgroup type', unless: default[:platform] =~ %r{debian-10-amd
-> class { 'postgresql::server': }
class { 'zabbix':
- zabbix_version => '4.4',
+ zabbix_version => '5.0',
zabbix_url => 'localhost',
zabbix_api_user => 'Admin',
zabbix_api_pass => 'zabbix',

diff:
@@ -2,7 +2,7 @@ require 'spec_helper_acceptance'
require 'serverspec_type_zabbixapi'
# rubocop:disable RSpec/LetBeforeExamples
-describe 'zabbix_proxy type', unless: default[:platform] =~ %r{debian-10-amd64} do
+describe 'zabbix_proxy type', unless: default[:platform] =~ %r{(ubuntu-16.04|debian-9|debian-10)-amd64} do
context 'create zabbix_proxy resources' do
# This will deploy a running Zabbix setup (server, web, db) which we can
# use for custom type tests
@@ -20,7 +20,7 @@ describe 'zabbix_proxy type', unless: default[:platform] =~ %r{debian-10-amd64}
-> class { 'postgresql::server': }
class { 'zabbix':
- zabbix_version => '4.4',
+ zabbix_version => '5.0',
zabbix_url => 'localhost',
zabbix_api_user => 'Admin',
zabbix_api_pass => 'zabbix',

diff:
@@ -2,7 +2,7 @@ require 'spec_helper_acceptance'
require 'serverspec_type_zabbixapi'
# rubocop:disable RSpec/LetBeforeExamples
-describe 'zabbix_template_host type', unless: default[:platform] =~ %r{debian-10-amd64} do
+describe 'zabbix_template_host type', unless: default[:platform] =~ %r{(ubuntu-16.04|debian-9|debian-10)-amd64} do
context 'create zabbix_template_host resources' do
it 'runs successfully' do
# This will deploy a running Zabbix setup (server, web, db) which we can
@@ -21,7 +21,7 @@ describe 'zabbix_template_host type', unless: default[:platform] =~ %r{debian-10
-> class { 'postgresql::server': }
class { 'zabbix':
- zabbix_version => '4.4',
+ zabbix_version => '5.0',
zabbix_url => 'localhost',
zabbix_api_user => 'Admin',
zabbix_api_pass => 'zabbix',

diff:
@@ -2,7 +2,7 @@ require 'spec_helper_acceptance'
require 'serverspec_type_zabbixapi'
# rubocop:disable RSpec/LetBeforeExamples
-describe 'zabbix_template type', unless: default[:platform] =~ %r{debian-10-amd64} do
+describe 'zabbix_template type', unless: default[:platform] =~ %r{(ubuntu-16.04|debian-9|debian-10)-amd64} do
context 'create zabbix_template resources' do
it 'runs successfully' do
# This will deploy a running Zabbix setup (server, web, db) which we can
@@ -21,7 +21,7 @@ describe 'zabbix_template type', unless: default[:platform] =~ %r{debian-10-amd6
-> class { 'postgresql::server': }
class { 'zabbix':
- zabbix_version => '4.4',
+ zabbix_version => '5.0',
zabbix_url => 'localhost',
zabbix_api_user => 'Admin',
zabbix_api_pass => 'zabbix',

diff:
@@ -11,7 +11,13 @@ def prepare_host
/opt/puppetlabs/bin/puppet resource service zabbix-server ensure=stopped
/opt/puppetlabs/bin/puppet resource package zabbix-server-pgsql ensure=purged
/opt/puppetlabs/bin/puppet resource package zabbix-server-pgsql-scl ensure=purged
+ /opt/puppetlabs/bin/puppet resource package zabbix-server-mysql ensure=purged
+ /opt/puppetlabs/bin/puppet resource package zabbix-server-mysql-scl ensure=purged
/opt/puppetlabs/bin/puppet resource package zabbix-web ensure=purged
+ /opt/puppetlabs/bin/puppet resource package zabbix-web-pgsql ensure=purged
+ /opt/puppetlabs/bin/puppet resource package zabbix-web-mysql ensure=purged
+ /opt/puppetlabs/bin/puppet resource package zabbix-web-pgsql-scl ensure=purged
+ /opt/puppetlabs/bin/puppet resource package zabbix-web-mysql-scl ensure=purged
/opt/puppetlabs/bin/puppet resource package zabbix-frontend-php ensure=purged
rm -f /etc/zabbix/.*done
if id postgres > /dev/null 2>&1; then

original_message:
Bump the rest of the of the acceptance tests to 5.0

Signed-off-by: Christos Papageorgiou <root.expert.xda@gmail.com>


diff:
@@ -389,6 +389,14 @@ class zabbix::server (
Boolean $manage_startup_script = $zabbix::params::manage_startup_script,
Optional[Stdlib::Absolutepath] $socketdir = $zabbix::params::server_socketdir,
) inherits zabbix::params {
+ # zabbix server 5.2 is not supported on RHEL 7.
+ # https://www.zabbix.com/documentation/current/manual/installation/install_from_packages/rhel_centos
+ if $facts['os']['family'] == 'RedHat' and versioncmp($zabbix_version, '5.2') == 0 {
+ if versioncmp($facts['os']['release']['major'], '7') == 0 {
+ fail("${facts['os']['family']} ${$facts['os']['release']['major']} is not supported for zabbix::server (yet)")
+ }
+ }
+
# the following codeblock is a bit blargh. The correct default value for
# $real_additional_service_params changes based on the value of $zabbix_version
# We handle this in the params.pp, but that doesn't work if somebody provides a specific

diff:
@@ -3,7 +3,18 @@ require 'serverspec_type_zabbixapi'
# rubocop:disable RSpec/LetBeforeExamples
describe 'zabbix_application type', unless: default[:platform] =~ %r{(ubuntu-16.04|debian-9|debian-10)-amd64} do
- context 'create zabbix_application resources' do
+ %w[4.0 5.0 5.2].each do |zabbix_version|
+ # 5.2 server packages are not available for RHEL 7
+ next if zabbix_version == '5.2' and default[:platform] == 'el-7-x86_64'
+
+ template = case zabbix_version
+ when '4.0'
+ 'Template OS Linux'
+ else
+ 'Template OS Linux by Zabbix agent'
+ end
+
+ context "create zabbix_application resources with zabbix version #{zabbix_version}" do
# This will deploy a running Zabbix setup (server, web, db) which we can
# use for custom type tests
pp1 = <<-EOS
@@ -18,7 +29,6 @@ describe 'zabbix_application type', unless: default[:platform] =~ %r{(ubuntu-16.
}
include apache::mod::php
class { 'postgresql::globals':
- encoding => 'UTF-8',
locale => 'en_US.UTF-8',
manage_package_repo => true,
version => '12',
@@ -26,7 +36,7 @@ describe 'zabbix_application type', unless: default[:platform] =~ %r{(ubuntu-16.
-> class { 'postgresql::server': }
class { 'zabbix':
- zabbix_version => '5.0',
+ zabbix_version => "#{zabbix_version}",
zabbix_url => 'localhost',
zabbix_api_user => 'Admin',
zabbix_api_pass => 'zabbix',
@@ -39,7 +49,7 @@ describe 'zabbix_application type', unless: default[:platform] =~ %r{(ubuntu-16.
pp2 = <<-EOS
zabbix_application { 'TestApplication1':
- template => 'Template OS Linux by Zabbix agent',
+ template => "#{template}",
}
EOS
# setup zabbix. Apache module isn't idempotent and requires a second run
@@ -68,10 +78,11 @@ describe 'zabbix_application type', unless: default[:platform] =~ %r{(ubuntu-16.
end
context 'TestApplication1' do
- let(:template1) { result_templates.select { |t| t['host'] == 'Template OS Linux by Zabbix agent' }.first }
+ let(:template1) { result_templates.select { |t| t['host'] == template }.first }
- it 'is attached to Template OS Linux by Zabbix agent' do
+ it "is attached to #{template}" do
expect(template1['applications'].map { |a| a['name'] }).to include('TestApplication1')
end
end
end
+end

diff:
@@ -3,16 +3,32 @@ require 'serverspec_type_zabbixapi'
# rubocop:disable RSpec/LetBeforeExamples
describe 'zabbix_host type', unless: default[:platform] =~ %r{(ubuntu-16.04|debian-9|debian-10)-amd64} do
- context 'create zabbix_host resources' do
+ %w[4.0 5.0 5.2].each do |zabbix_version|
+ # 5.2 server packages are not available for RHEL 7
+ next if zabbix_version == '5.2' and default[:platform] == 'el-7-x86_64'
+ context "create zabbix_host resources with zabbix version #{zabbix_version}" do
# This will deploy a running Zabbix setup (server, web, db) which we can
# use for custom type tests
+
+ template = case zabbix_version
+ when '4.0'
+ 'Template OS Linux'
+ else
+ 'Template OS Linux by Zabbix agent'
+ end
+
pp1 = <<-EOS
+ $compile_packages = $facts['os']['family'] ? {
+ 'RedHat' => [ 'make', 'gcc-c++', 'rubygems', 'ruby'],
+ 'Debian' => [ 'make', 'g++', 'ruby-dev', 'ruby', 'pkg-config',],
+ default => [],
+ }
+ ensure_packages($compile_packages, { before => Package['zabbixapi'], })
class { 'apache':
mpm_module => 'prefork',
}
include apache::mod::php
class { 'postgresql::globals':
- encoding => 'UTF-8',
locale => 'en_US.UTF-8',
manage_package_repo => true,
version => '12',
@@ -20,7 +36,7 @@ class { 'postgresql::globals':
-> class { 'postgresql::server': }
class { 'zabbix':
- zabbix_version => '5.0',
+ zabbix_version => "#{zabbix_version}",
zabbix_url => 'localhost',
zabbix_api_user => 'Admin',
zabbix_api_pass => 'zabbix',
@@ -29,6 +45,7 @@ class { 'zabbix':
require => [ Class['postgresql::server'], Class['apache'], ],
}
EOS
+
# setup zabbix. Apache module isn't idempotent and requires a second run
it 'works with no error on the first apply' do
# Cleanup old database
@@ -48,15 +65,16 @@ zabbix_host { 'test1.example.com':
port => 10050,
groups => ['TestgroupOne'],
group_create => true,
- templates => [ 'Template OS Linux by Zabbix agent', ],
+ templates => [ "#{template}", ],
macros => [],
}
+
zabbix_host { 'test2.example.com':
ipaddress => '127.0.0.2',
use_ip => false,
port => 1050,
groups => ['Virtual machines'],
- templates => [ 'Template OS Linux by Zabbix agent', 'Template Module ICMP Ping', ],
+ templates => [ "#{template}", 'Template Module ICMP Ping', ],
macros => [],
}
EOS
@@ -102,7 +120,7 @@ zabbix_host { 'test2.example.com':
expect(test1['interfaces'][0]['useip']).to eq('1')
end
it 'has templates attached' do
- expect(test1['parentTemplates'].map { |t| t['host'] }.sort).to eq(['Template OS Linux by Zabbix agent'])
+ expect(test1['parentTemplates'].map { |t| t['host'] }.sort).to eq([template])
end
end
@@ -134,7 +152,8 @@ zabbix_host { 'test2.example.com':
expect(test2['interfaces'][0]['useip']).to eq('0')
end
it 'has templates attached' do
- expect(test2['parentTemplates'].map { |t| t['host'] }.sort).to eq(['Template Module ICMP Ping', 'Template OS Linux by Zabbix agent'])
+ expect(test2['parentTemplates'].map { |t| t['host'] }.sort).to eq(['Template Module ICMP Ping', template])
+ end
end
end
end

diff:
@@ -3,17 +3,18 @@ require 'serverspec_type_zabbixapi'
# rubocop:disable RSpec/LetBeforeExamples
describe 'zabbix_hostgroup type', unless: default[:platform] =~ %r{(ubuntu-16.04|debian-9|debian-10)-amd64} do
- context 'create zabbix_hostgroup resources' do
- it 'runs successfully' do
+ %w[4.0 5.0 5.2].each do |zabbix_version|
+ # 5.2 server packages are not available for RHEL 7
+ next if zabbix_version == '5.2' and default[:platform] == 'el-7-x86_64'
+ context "create zabbix_hostgroup resources with zabbix version #{zabbix_version}" do
# This will deploy a running Zabbix setup (server, web, db) which we can
# use for custom type tests
- pp = <<-EOS
+ pp1 = <<-EOS
class { 'apache':
mpm_module => 'prefork',
}
include apache::mod::php
class { 'postgresql::globals':
- encoding => 'UTF-8',
locale => 'en_US.UTF-8',
manage_package_repo => true,
version => '12',
@@ -21,7 +22,7 @@ describe 'zabbix_hostgroup type', unless: default[:platform] =~ %r{(ubuntu-16.04
-> class { 'postgresql::server': }
class { 'zabbix':
- zabbix_version => '5.0',
+ zabbix_version => "#{zabbix_version}",
zabbix_url => 'localhost',
zabbix_api_user => 'Admin',
zabbix_api_pass => 'zabbix',
@@ -29,10 +30,10 @@ describe 'zabbix_hostgroup type', unless: default[:platform] =~ %r{(ubuntu-16.04
manage_resources => true,
require => [ Class['postgresql::server'], Class['apache'], ],
}
+ EOS
- Zabbix_hostgroup {
- require => [ Service['zabbix-server'], Package['zabbixapi'], ],
- }
+ pp2 = <<-EOS
+ Zabbix_hostgroup { }
zabbix_hostgroup { 'Testgroup2': }
zabbix_hostgroup { 'Linux servers':
@@ -40,10 +41,21 @@ describe 'zabbix_hostgroup type', unless: default[:platform] =~ %r{(ubuntu-16.04
}
EOS
+ # setup zabbix. Apache module isn't idempotent and requires a second run
+ it 'works with no error on the first apply' do
# Cleanup old database
prepare_host
- apply_manifest(pp, catch_failures: true)
+ apply_manifest(pp1, catch_failures: true)
+ end
+
+ it 'works with no error on the second apply' do
+ apply_manifest(pp1, catch_failures: true)
+ end
+
+ it 'works with no error on the third apply' do
+ apply_manifest(pp2, catch_failures: true)
+ end
end
let(:result_hostgroups) do

diff:
@@ -3,7 +3,10 @@ require 'serverspec_type_zabbixapi'
# rubocop:disable RSpec/LetBeforeExamples
describe 'zabbix_proxy type', unless: default[:platform] =~ %r{(ubuntu-16.04|debian-9|debian-10)-amd64} do
- context 'create zabbix_proxy resources' do
+ %w[4.0 5.0 5.2].each do |zabbix_version|
+ # 5.2 server packages are not available for RHEL 7
+ next if zabbix_version == '5.2' and default[:platform] == 'el-7-x86_64'
+ context "create zabbix_proxy resources with zabbix version #{zabbix_version}" do
# This will deploy a running Zabbix setup (server, web, db) which we can
# use for custom type tests
pp1 = <<-EOS
@@ -12,7 +15,6 @@ describe 'zabbix_proxy type', unless: default[:platform] =~ %r{(ubuntu-16.04|deb
}
include apache::mod::php
class { 'postgresql::globals':
- encoding => 'UTF-8',
locale => 'en_US.UTF-8',
manage_package_repo => true,
version => '12',
@@ -20,7 +22,7 @@ describe 'zabbix_proxy type', unless: default[:platform] =~ %r{(ubuntu-16.04|deb
-> class { 'postgresql::server': }
class { 'zabbix':
- zabbix_version => '5.0',
+ zabbix_version => "#{zabbix_version}",
zabbix_url => 'localhost',
zabbix_api_user => 'Admin',
zabbix_api_pass => 'zabbix',
@@ -30,13 +32,15 @@ describe 'zabbix_proxy type', unless: default[:platform] =~ %r{(ubuntu-16.04|deb
}
EOS
+ # setup zabbix. Apache module isn't idempotent and requires a second run
+ it 'works with no error on first apply' do
# Cleanup old database
prepare_host
- it 'works idempotently with no errors' do
- # Run it twice and test for idempotency
apply_manifest(pp1, catch_failures: true)
- apply_manifest(pp1, catch_changes: true)
+ end
+ it 'works with no error on second apply' do
+ apply_manifest(pp1, catch_failures: true)
end
# setup proxies within zabbix
@@ -197,3 +201,4 @@ describe 'zabbix_proxy type', unless: default[:platform] =~ %r{(ubuntu-16.04|deb
end
end
end
+end

diff:
@@ -3,17 +3,26 @@ require 'serverspec_type_zabbixapi'
# rubocop:disable RSpec/LetBeforeExamples
describe 'zabbix_template_host type', unless: default[:platform] =~ %r{(ubuntu-16.04|debian-9|debian-10)-amd64} do
- context 'create zabbix_template_host resources' do
- it 'runs successfully' do
+ %w[4.0 5.0 5.2].each do |zabbix_version|
+ # 5.2 server packages are not available for RHEL 7
+ next if zabbix_version == '5.2' and default[:platform] == 'el-7-x86_64'
+ context "create zabbix_template_host resources with zabbix version #{zabbix_version}" do
+ template = case zabbix_version
+ when '4.0'
+ 'Template OS Linux'
+ else
+ 'Template OS Linux by Zabbix agent'
+ end
+
+
# This will deploy a running Zabbix setup (server, web, db) which we can
# use for custom type tests
- pp = <<-EOS
+ pp1 = <<-EOS
class { 'apache':
mpm_module => 'prefork',
}
include apache::mod::php
class { 'postgresql::globals':
- encoding => 'UTF-8',
locale => 'en_US.UTF-8',
manage_package_repo => true,
version => '12',
@@ -21,7 +30,7 @@ describe 'zabbix_template_host type', unless: default[:platform] =~ %r{(ubuntu-1
-> class { 'postgresql::server': }
class { 'zabbix':
- zabbix_version => '5.0',
+ zabbix_version => "#{zabbix_version}",
zabbix_url => 'localhost',
zabbix_api_user => 'Admin',
zabbix_api_pass => 'zabbix',
@@ -29,33 +38,42 @@ describe 'zabbix_template_host type', unless: default[:platform] =~ %r{(ubuntu-1
manage_resources => true,
require => [ Class['postgresql::server'], Class['apache'], ],
}
+ EOS
+ pp2 = <<-EOS
zabbix_host { 'test1.example.com':
ipaddress => '127.0.0.1',
use_ip => true,
port => 10050,
group => 'TestgroupOne',
group_create => true,
- templates => [ 'Template OS Linux by Zabbix agent', ],
- require => [ Service['zabbix-server'], Package['zabbixapi'], ],
+ templates => [ "#{template}", ],
}
zabbix_template { 'TestTemplate1':
template_source => '/root/TestTemplate1.xml',
- require => [ Service['zabbix-server'], Package['zabbixapi'], ],
}
- zabbix_template_host{"TestTemplate1@test1.example.com":
- require => [ Service['zabbix-server'], Package['zabbixapi'], ],
- }
+ zabbix_template_host{ "TestTemplate1@test1.example.com": }
EOS
shell("echo '<?xml version=\"1.0\" encoding=\"UTF-8\"?><zabbix_export><version>4.0</version><date>2018-12-13T15:00:46Z</date><groups><group><name>Templates/Applications</name></group></groups><templates><template><template>TestTemplate1</template><name>TestTemplate1</name><description/><groups><group><name>Templates/Applications</name></group></groups><applications/><items/><discovery_rules/><macros/><templates/><screens/></template></templates></zabbix_export>' > /root/TestTemplate1.xml")
+ # setup zabbix. Apache module isn't idempotent and requires a second run
+ it 'works with no error on the first apply' do
# Cleanup old database
prepare_host
- apply_manifest(pp, catch_failures: true)
+ apply_manifest(pp1, catch_failures: true)
+ end
+
+ it 'works with no error on the second apply' do
+ apply_manifest(pp1, catch_failures: true)
+ end
+
+ it 'works with no error on the third apply' do
+ apply_manifest(pp2, catch_failures: true)
+ end
end
let(:result_hosts) do

diff:
@@ -3,17 +3,18 @@ require 'serverspec_type_zabbixapi'
# rubocop:disable RSpec/LetBeforeExamples
describe 'zabbix_template type', unless: default[:platform] =~ %r{(ubuntu-16.04|debian-9|debian-10)-amd64} do
- context 'create zabbix_template resources' do
- it 'runs successfully' do
+ %w[4.0 5.0 5.2].each do |zabbix_version|
+ # 5.2 server packages are not available for RHEL 7
+ next if zabbix_version == '5.2' and default[:platform] == 'el-7-x86_64'
+ context "create zabbix_template resources with zabbix version #{zabbix_version}" do
# This will deploy a running Zabbix setup (server, web, db) which we can
# use for custom type tests
- pp = <<-EOS
+ pp1 = <<-EOS
class { 'apache':
mpm_module => 'prefork',
}
include apache::mod::php
class { 'postgresql::globals':
- encoding => 'UTF-8',
locale => 'en_US.UTF-8',
manage_package_repo => true,
version => '12',
@@ -21,7 +22,7 @@ describe 'zabbix_template type', unless: default[:platform] =~ %r{(ubuntu-16.04|
-> class { 'postgresql::server': }
class { 'zabbix':
- zabbix_version => '5.0',
+ zabbix_version => "#{zabbix_version}",
zabbix_url => 'localhost',
zabbix_api_user => 'Admin',
zabbix_api_pass => 'zabbix',
@@ -29,19 +30,31 @@ describe 'zabbix_template type', unless: default[:platform] =~ %r{(ubuntu-16.04|
manage_resources => true,
require => [ Class['postgresql::server'], Class['apache'], ],
}
+ EOS
+ pp2 = <<-EOS
zabbix_template { 'TestTemplate1':
template_source => '/root/TestTemplate1.xml',
- require => [ Service['zabbix-server'], Package['zabbixapi'], ],
}
EOS
shell("echo '<?xml version=\"1.0\" encoding=\"UTF-8\"?><zabbix_export><version>4.0</version><date>2018-12-13T15:00:46Z</date><groups><group><name>Templates/Applications</name></group></groups><templates><template><template>TestTemplate1</template><name>TestTemplate1</name><description/><groups><group><name>Templates/Applications</name></group></groups><applications/><items/><discovery_rules/><macros/><templates/><screens/></template></templates></zabbix_export>' > /root/TestTemplate1.xml")
+ # setup zabbix. Apache module isn't idempotent and requires a second run
+ it 'works with no error on the first apply' do
# Cleanup old database
prepare_host
- apply_manifest(pp, catch_failures: true)
+ apply_manifest(pp1, catch_failures: true)
+ end
+
+ it 'works with no error on the second apply' do
+ apply_manifest(pp1, catch_failures: true)
+ end
+
+ it 'works with no error on the third apply' do
+ apply_manifest(pp2, catch_failures: true)
+ end
end
let(:result_templates) do

diff:
@@ -19,6 +19,7 @@ def prepare_host
/opt/puppetlabs/bin/puppet resource package zabbix-web-pgsql-scl ensure=purged
/opt/puppetlabs/bin/puppet resource package zabbix-web-mysql-scl ensure=purged
/opt/puppetlabs/bin/puppet resource package zabbix-frontend-php ensure=purged
+ /opt/puppetlabs/bin/puppet/gem uninstall zabbixapi -a
rm -f /etc/zabbix/.*done
if id postgres > /dev/null 2>&1; then
su - postgres -c "psql -c 'drop database if exists zabbix_server;'"

original_message:
Run acceptance tests for all supported versions

Signed-off-by: Christos Papageorgiou <root.expert.xda@gmail.com>


message: Fix zabbixapi versions

diff:
@@ -293,9 +293,12 @@ class zabbix::web (
'4.4': {
$zabbixapi_version = '4.2.0'
}
- default : {
+ /^5\.[02]/: {
$zabbixapi_version = '5.0.0-alpha1'
}
+ default: {
+ fail("Zabbix ${zabbix_version} is not supported!")
+ }
}
# Installing the zabbixapi gem package. We need this gem for

diff:
@@ -19,7 +19,7 @@ def prepare_host
/opt/puppetlabs/bin/puppet resource package zabbix-web-pgsql-scl ensure=purged
/opt/puppetlabs/bin/puppet resource package zabbix-web-mysql-scl ensure=purged
/opt/puppetlabs/bin/puppet resource package zabbix-frontend-php ensure=purged
- /opt/puppetlabs/bin/puppet/gem uninstall zabbixapi -a
+ /opt/puppetlabs/puppet/bin/gem uninstall zabbixapi -a
rm -f /etc/zabbix/.*done
if id postgres > /dev/null 2>&1; then
su - postgres -c "psql -c 'drop database if exists zabbix_server;'"

original_message:
Fix zabbixapi versions

Signed-off-by: Christos Papageorgiou <root.expert.xda@gmail.com>