diff --git a/composer.json b/composer.json index dc2fd54..7207b82 100644 --- a/composer.json +++ b/composer.json @@ -31,13 +31,9 @@ "slevomat/coding-standard": "8.14.1", "squizlabs/php_codesniffer": "3.8.1" }, - "autoload": { - "psr-4": { - "Elastic\\OTel\\": "./prod/php/ElasticOTel/" - } - }, "autoload-dev": { "psr-4": { + "Elastic\\OTel\\": "./prod/php/ElasticOTel/", "ElasticOTelTests\\": "./tests/ElasticOTelTests/" } }, diff --git a/elastic-otel-php.properties b/elastic-otel-php.properties index f2567f1..b3b5df3 100644 --- a/elastic-otel-php.properties +++ b/elastic-otel-php.properties @@ -1,4 +1,4 @@ version=0.2.0 supported_php_versions=(80 81 82 83) php_headers_version=2.0 -logger_features_enum_values=ALL=0,MODULE=1,REQUEST=2,TRANSPORT=3,BOOTSTRAP=4,HOOKS=5,INSTRUMENTATION=6 +logger_features_enum_values=ALL=0,MODULE=1,REQUEST=2,TRANSPORT=3,BOOTSTRAP=4,HOOKS=5,INSTRUMENTATION=6,OTEL=7 diff --git a/prod/php/ElasticOTel/Autoloader.php b/prod/php/ElasticOTel/Autoloader.php new file mode 100644 index 0000000..8a72dbf --- /dev/null +++ b/prod/php/ElasticOTel/Autoloader.php @@ -0,0 +1,108 @@ +> - */ - private static $vaLue = null; - - private static function buildDurationMetadataInMillisecondsWithMin(int $min, int $default): DurationOptionMetadata - { - return new DurationOptionMetadata(floatval($min), /* max */ null, DurationUnits::MILLISECONDS, floatval($default)); - } - - private static function buildDurationMetadataInMillisecondsNoMin(int $default): DurationOptionMetadata - { - return new DurationOptionMetadata(/* min */ null, /* max */ null, DurationUnits::MILLISECONDS, floatval($default)); - } - - private static function buildDurationMetadataInMilliseconds(int $default): DurationOptionMetadata - { - return self::buildDurationMetadataInMillisecondsWithMin(/* min */ 0, $default); - } - - private static function buildDurationMetadataInSeconds(int $defaultInSeconds): DurationOptionMetadata - { - return new DurationOptionMetadata(/* min */ 0.0, /* max */ null, DurationUnits::SECONDS, floatval($defaultInSeconds * TimeUtil::NUMBER_OF_MILLISECONDS_IN_SECOND)); - } - - private static function buildPositiveOrZeroIntMetadata(int $default): IntOptionMetadata - { - return new IntOptionMetadata(/* min */ 0, /* max */ null, $default); - } - - /** - * @return array> Option name to metadata - */ - public static function get(): array - { - if (self::$vaLue !== null) { - return self::$vaLue; - } - - /** @var array> $value */ - $value = [ - OptionNames::API_KEY => new NullableStringOptionMetadata(), - OptionNames::ASYNC_BACKEND_COMM => new BoolOptionMetadata(/* default */ true), - OptionNames::BREAKDOWN_METRICS => new BoolOptionMetadata(/* default */ true), - OptionNames::CAPTURE_ERRORS => new BoolOptionMetadata(/* default */ true), - OptionNames::DEV_INTERNAL => new NullableWildcardListOptionMetadata(), - OptionNames::DISABLE_INSTRUMENTATIONS => new NullableWildcardListOptionMetadata(), - OptionNames::DISABLE_SEND => new BoolOptionMetadata(/* default */ false), - OptionNames::ENABLED => new BoolOptionMetadata(/* default */ true), - OptionNames::ENVIRONMENT => new NullableStringOptionMetadata(), - OptionNames::GLOBAL_LABELS => new NullableLabelsOptionMetadata(), - OptionNames::HOSTNAME => new NullableStringOptionMetadata(), - OptionNames::LOG_LEVEL => new NullableLogLevelOptionMetadata(), - OptionNames::LOG_LEVEL_STDERR => new NullableLogLevelOptionMetadata(), - OptionNames::LOG_LEVEL_SYSLOG => new NullableLogLevelOptionMetadata(), - OptionNames::NON_KEYWORD_STRING_MAX_LENGTH => self::buildPositiveOrZeroIntMetadata(/* default */ 10 * 1024), - OptionNames::SANITIZE_FIELD_NAMES => new WildcardListOptionMetadata(WildcardListOptionParser::staticParse(self::SANITIZE_FIELD_NAMES_DEFAULT)), - OptionNames::SECRET_TOKEN => new NullableStringOptionMetadata(), - OptionNames::SERVER_TIMEOUT => self::buildDurationMetadataInSeconds(/* default */ 30), - OptionNames::SERVICE_NAME => new NullableStringOptionMetadata(), - OptionNames::SERVICE_NODE_NAME => new NullableStringOptionMetadata(), - OptionNames::SERVICE_VERSION => new NullableStringOptionMetadata(), - OptionNames::SPAN_COMPRESSION_ENABLED => new BoolOptionMetadata(/* default */ true), - OptionNames::SPAN_COMPRESSION_EXACT_MATCH_MAX_DURATION => self::buildDurationMetadataInMilliseconds(/* default */ 50), - OptionNames::SPAN_COMPRESSION_SAME_KIND_MAX_DURATION => self::buildDurationMetadataInMilliseconds(/* default */ 0), - OptionNames::SPAN_STACK_TRACE_MIN_DURATION => self::buildDurationMetadataInMillisecondsNoMin(/* default */ OptionDefaultValues::SPAN_STACK_TRACE_MIN_DURATION), - OptionNames::STACK_TRACE_LIMIT => new IntOptionMetadata(/* min */ null, /* max */ null, /* default */ OptionDefaultValues::STACK_TRACE_LIMIT), - OptionNames::TRANSACTION_IGNORE_URLS => new NullableWildcardListOptionMetadata(), - OptionNames::TRANSACTION_MAX_SPANS => self::buildPositiveOrZeroIntMetadata(OptionDefaultValues::TRANSACTION_MAX_SPANS), - OptionNames::TRANSACTION_SAMPLE_RATE => new FloatOptionMetadata(/* min */ 0.0, /* max */ 1.0, /* default */ 1.0), - OptionNames::URL_GROUPS => new NullableWildcardListOptionMetadata(), - OptionNames::VERIFY_SERVER_CERT => new BoolOptionMetadata(/* default */ true), - ]; - - self::$vaLue = $value; - return self::$vaLue; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/BoolOptionMetadata.php b/prod/php/ElasticOTel/Config/BoolOptionMetadata.php deleted file mode 100644 index fa411fc..0000000 --- a/prod/php/ElasticOTel/Config/BoolOptionMetadata.php +++ /dev/null @@ -1,39 +0,0 @@ - - */ -final class BoolOptionMetadata extends OptionWithDefaultValueMetadata -{ - public function __construct(bool $defaultValue) - { - parent::__construct(new BoolOptionParser(), $defaultValue); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/BoolOptionParser.php b/prod/php/ElasticOTel/Config/BoolOptionParser.php deleted file mode 100644 index e013d9c..0000000 --- a/prod/php/ElasticOTel/Config/BoolOptionParser.php +++ /dev/null @@ -1,71 +0,0 @@ - - */ -final class BoolOptionParser extends EnumOptionParser -{ - /** @var array */ - public static $trueRawValues = ['true', 'yes', 'on', '1']; - - /** @var array */ - public static $falseRawValues = ['false', 'no', 'off', '0']; - - /** @var ?array */ - private static $boolNameToValue = null; - - public function __construct() - { - if (self::$boolNameToValue === null) { - self::$boolNameToValue = []; - foreach (self::$trueRawValues as $trueRawValue) { - self::$boolNameToValue[] = [$trueRawValue, true]; - } - foreach (self::$falseRawValues as $falseRawValue) { - self::$boolNameToValue[] = [$falseRawValue, false]; - } - } - - parent::__construct( - 'bool' /* <- dbgEnumDesc */, - self::$boolNameToValue /* <- nameToValue */, - false /* <- isCaseSensitive */, - false /* <- isUnambiguousPrefixAllowed */ - ); - } - - /** @inheritDoc */ - public function parse(string $rawValue) - { - return TextUtil::isEmptyString($rawValue) ? false : parent::parse($rawValue); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/CompositeRawSnapshot.php b/prod/php/ElasticOTel/Config/CompositeRawSnapshot.php deleted file mode 100644 index 9c0b9fb..0000000 --- a/prod/php/ElasticOTel/Config/CompositeRawSnapshot.php +++ /dev/null @@ -1,53 +0,0 @@ - */ - private $subSnapshots; - - /** - * @param array $subSnapshots - */ - public function __construct(array $subSnapshots) - { - $this->subSnapshots = $subSnapshots; - } - - public function valueFor(string $optionName): ?string - { - foreach ($this->subSnapshots as $subSnapshot) { - if (($value = $subSnapshot->valueFor($optionName)) !== null) { - return $value; - } - } - return null; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/CompositeRawSnapshotSource.php b/prod/php/ElasticOTel/Config/CompositeRawSnapshotSource.php deleted file mode 100644 index f326da9..0000000 --- a/prod/php/ElasticOTel/Config/CompositeRawSnapshotSource.php +++ /dev/null @@ -1,53 +0,0 @@ - */ - private $subSources; - - /** - * @param array $subSources - */ - public function __construct(array $subSources) - { - $this->subSources = $subSources; - } - - public function currentSnapshot(array $optionNameToMeta): RawSnapshotInterface - { - /** @var array */ - $subSnapshots = []; - foreach ($this->subSources as $subSource) { - $subSnapshots[] = $subSource->currentSnapshot($optionNameToMeta); - } - return new CompositeRawSnapshot($subSnapshots); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/DevInternalSubOptionNames.php b/prod/php/ElasticOTel/Config/DevInternalSubOptionNames.php deleted file mode 100644 index 0e296b7..0000000 --- a/prod/php/ElasticOTel/Config/DevInternalSubOptionNames.php +++ /dev/null @@ -1,41 +0,0 @@ - - */ -final class DurationOptionMetadata extends OptionWithDefaultValueMetadata -{ - public function __construct( - ?float $minValidValueInMilliseconds, - ?float $maxValidValueInMilliseconds, - int $defaultUnits, - float $defaultValueInMilliseconds - ) { - parent::__construct( - new DurationOptionParser($minValidValueInMilliseconds, $maxValidValueInMilliseconds, $defaultUnits), - $defaultValueInMilliseconds - ); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/DurationOptionParser.php b/prod/php/ElasticOTel/Config/DurationOptionParser.php deleted file mode 100644 index fc0fae4..0000000 --- a/prod/php/ElasticOTel/Config/DurationOptionParser.php +++ /dev/null @@ -1,144 +0,0 @@ - - */ -final class DurationOptionParser extends OptionParser -{ - /** @var ?float */ - private $minValidValueInMilliseconds; - - /** @var ?float */ - private $maxValidValueInMilliseconds; - - /** @var int */ - private $defaultUnits; - - public function __construct( - ?float $minValidValueInMilliseconds, - ?float $maxValidValueInMilliseconds, - int $defaultUnits - ) { - $this->minValidValueInMilliseconds = $minValidValueInMilliseconds; - $this->maxValidValueInMilliseconds = $maxValidValueInMilliseconds; - $this->defaultUnits = $defaultUnits; - } - - /** @inheritDoc */ - public function parse(string $rawValue): float - { - $partWithoutSuffix = ''; - $units = $this->defaultUnits; - self::splitToValueAndUnits($rawValue, /* ref */ $partWithoutSuffix, /* ref */ $units); - - $auxFloatOptionParser = new FloatOptionParser(null /* minValidValue */, null /* maxValidValue */); - $parsedValueInMilliseconds - = self::convertToMilliseconds($auxFloatOptionParser->parse($partWithoutSuffix), $units); - - if ( - ( - ($this->minValidValueInMilliseconds !== null) - && ($parsedValueInMilliseconds < $this->minValidValueInMilliseconds) - ) - || ( - ($this->maxValidValueInMilliseconds !== null) - && ($parsedValueInMilliseconds > $this->maxValidValueInMilliseconds) - ) - ) { - throw new ParseException( - 'Value is not in range between the valid minimum and maximum values.' - . ' Raw option value: `' . $rawValue . "'." - . ' Parsed option value (in milliseconds): ' . $parsedValueInMilliseconds . '.' - . ' The valid minimum value (in milliseconds): ' . $this->minValidValueInMilliseconds . '.' - . ' The valid maximum value (in milliseconds): ' . $this->maxValidValueInMilliseconds . '.' - ); - } - - return $parsedValueInMilliseconds; - } - - public function defaultUnits(): int - { - return $this->defaultUnits; - } - - public function minValidValueInMilliseconds(): ?float - { - return $this->minValidValueInMilliseconds; - } - - public function maxValidValueInMilliseconds(): ?float - { - return $this->maxValidValueInMilliseconds; - } - - private static function splitToValueAndUnits(string $rawValue, string &$partWithoutSuffix, int &$units): void - { - foreach (DurationUnits::$suffixAndIdPairs as $suffixAndIdPair) { - $suffix = $suffixAndIdPair[0]; - if (TextUtil::isSuffixOf($suffix, $rawValue, /* isCaseSensitive */ false)) { - $partWithoutSuffix = trim(substr($rawValue, 0, -strlen($suffix))); - $units = $suffixAndIdPair[1]; - return; - } - } - $partWithoutSuffix = $rawValue; - } - - public static function convertToMilliseconds(float $srcValue, int $srcValueUnits): float - { - switch ($srcValueUnits) { - case DurationUnits::MILLISECONDS: - return $srcValue; - - case DurationUnits::SECONDS: - return $srcValue * 1000; - - case DurationUnits::MINUTES: - return $srcValue * 60 * 1000; - - default: - throw new ParseException( - ExceptionUtil::buildMessage( - 'Not a valid time duration units ID', - /* context */ - [ - 'srcValueUnits' => $srcValueUnits, - 'srcValue' => $srcValue, - 'valid time duration units' => DurationUnits::$suffixAndIdPairs, - ] - ) - ); - } - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/DurationUnits.php b/prod/php/ElasticOTel/Config/DurationUnits.php deleted file mode 100644 index c003baa..0000000 --- a/prod/php/ElasticOTel/Config/DurationUnits.php +++ /dev/null @@ -1,57 +0,0 @@ - Array should be in descending order of suffix length - * - * @see TimeDurationUnitsTest::testSuffixAndIdIsInDescendingOrderOfSuffixLength - */ - public static $suffixAndIdPairs - = [ - [self::MILLISECONDS_SUFFIX, self::MILLISECONDS], - [self::SECONDS_SUFFIX, self::SECONDS], - [self::MINUTES_SUFFIX, self::MINUTES], - ]; -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/EnumOptionParser.php b/prod/php/ElasticOTel/Config/EnumOptionParser.php deleted file mode 100644 index 08e01c3..0000000 --- a/prod/php/ElasticOTel/Config/EnumOptionParser.php +++ /dev/null @@ -1,130 +0,0 @@ - - */ -class EnumOptionParser extends OptionParser -{ - /** @var string */ - private $dbgEnumDesc; - - /** - * We are forced to use list-array of pairs instead of regular associative array - * because in an associative array if the key is numeric string it's automatically converted to int - * (see https://www.php.net/manual/en/language.types.array.php) - * - * @var array> - * @phpstan-var array - */ - private $nameValuePairs; - - /** @var bool */ - private $isCaseSensitive; - - /** @var bool */ - private $isUnambiguousPrefixAllowed; - - /** - * @param string $dbgEnumDesc - * @param array $nameValuePairs - * @param bool $isCaseSensitive - * @param bool $isUnambiguousPrefixAllowed - */ - public function __construct( - string $dbgEnumDesc, - array $nameValuePairs, - bool $isCaseSensitive, - bool $isUnambiguousPrefixAllowed - ) { - $this->dbgEnumDesc = $dbgEnumDesc; - $this->nameValuePairs = $nameValuePairs; - $this->isCaseSensitive = $isCaseSensitive; - $this->isUnambiguousPrefixAllowed = $isUnambiguousPrefixAllowed; - } - - /** - * @return array> - * @phpstan-return array - */ - public function nameValuePairs(): array - { - return $this->nameValuePairs; - } - - public function isCaseSensitive(): bool - { - return $this->isCaseSensitive; - } - - public function isUnambiguousPrefixAllowed(): bool - { - return $this->isUnambiguousPrefixAllowed; - } - - /** - * @param string $rawValue - * - * @return mixed - * - * @phpstan-return T - */ - public function parse(string $rawValue) - { - foreach ($this->nameValuePairs as $enumEntryNameValuePair) { - if (TextUtil::isPrefixOf($rawValue, $enumEntryNameValuePair[0], $this->isCaseSensitive)) { - if (strlen($enumEntryNameValuePair[0]) === strlen($rawValue)) { - return $enumEntryNameValuePair[1]; - } - - if (!$this->isUnambiguousPrefixAllowed) { - continue; - } - - if (isset($foundMatchingEntry)) { - throw new ParseException( - "Not a valid $this->dbgEnumDesc value - it matches more than one entry as a prefix." - . " Raw option value: `$rawValue'" - ); - } - $foundMatchingEntry = $enumEntryNameValuePair[1]; - } - } - - if (!isset($foundMatchingEntry)) { - throw new ParseException("Not a valid $this->dbgEnumDesc value. Raw option value: `$rawValue'"); - } - - return $foundMatchingEntry; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/EnvVarsRawSnapshotSource.php b/prod/php/ElasticOTel/Config/EnvVarsRawSnapshotSource.php deleted file mode 100644 index d92a755..0000000 --- a/prod/php/ElasticOTel/Config/EnvVarsRawSnapshotSource.php +++ /dev/null @@ -1,65 +0,0 @@ -envVarNamesPrefix = $envVarNamesPrefix; - } - - public static function optionNameToEnvVarName(string $envVarNamesPrefix, string $optionName): string - { - return $envVarNamesPrefix . strtoupper($optionName); - } - - public function currentSnapshot(array $optionNameToMeta): RawSnapshotInterface - { - /** @var array */ - $optionNameToEnvVarValue = []; - - foreach ($optionNameToMeta as $optionName => $optionMeta) { - $envVarValue = getenv(self::optionNameToEnvVarName($this->envVarNamesPrefix, $optionName)); - if ($envVarValue !== false) { - $optionNameToEnvVarValue[$optionName] = $envVarValue; - } - } - - return new RawSnapshotFromArray($optionNameToEnvVarValue); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/FloatOptionMetadata.php b/prod/php/ElasticOTel/Config/FloatOptionMetadata.php deleted file mode 100644 index 0300cce..0000000 --- a/prod/php/ElasticOTel/Config/FloatOptionMetadata.php +++ /dev/null @@ -1,39 +0,0 @@ - - */ -final class FloatOptionMetadata extends OptionWithDefaultValueMetadata -{ - public function __construct(?float $minValidValue, ?float $maxValidValue, float $defaultValue) - { - parent::__construct(new FloatOptionParser($minValidValue, $maxValidValue), $defaultValue); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/FloatOptionParser.php b/prod/php/ElasticOTel/Config/FloatOptionParser.php deleted file mode 100644 index 8fa35fa..0000000 --- a/prod/php/ElasticOTel/Config/FloatOptionParser.php +++ /dev/null @@ -1,52 +0,0 @@ - - */ -final class FloatOptionParser extends NumericOptionParser -{ - /** @inheritDoc */ - protected function dbgValueTypeDesc(): string - { - return 'float'; - } - - /** @inheritDoc */ - public static function isValidFormat(string $rawValue): bool - { - return filter_var($rawValue, FILTER_VALIDATE_FLOAT) !== false; - } - - /** @inheritDoc */ - protected function stringToNumber(string $rawValue) - { - return floatval($rawValue); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/IniRawSnapshotSource.php b/prod/php/ElasticOTel/Config/IniRawSnapshotSource.php deleted file mode 100644 index 4b6a85e..0000000 --- a/prod/php/ElasticOTel/Config/IniRawSnapshotSource.php +++ /dev/null @@ -1,84 +0,0 @@ -iniNamesPrefix = $iniNamesPrefix; - } - - public static function optionNameToIniName(string $iniNamesPrefix, string $optionName): string - { - return $iniNamesPrefix . $optionName; - } - - public function currentSnapshot(array $optionNameToMeta): RawSnapshotInterface - { - /** @var array */ - $optionNameToValue = []; - - /** @var array */ - $allOpts = ini_get_all(/* extension: */ null, /* details */ false); - - foreach ($optionNameToMeta as $optionName => $optionMeta) { - $iniName = self::optionNameToIniName($this->iniNamesPrefix, $optionName); - if (($iniValue = ArrayUtil::getValueIfKeyExistsElse($iniName, $allOpts, null)) !== null) { - $optionNameToValue[$optionName] = self::iniValueToString($iniValue); - } - } - - return new RawSnapshotFromArray($optionNameToValue); - } - - /** - * @param mixed $iniValue - * - * @return string - */ - private static function iniValueToString($iniValue): string - { - if (is_bool($iniValue)) { - return $iniValue ? 'true' : 'false'; - } - - return strval($iniValue); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/IntOptionMetadata.php b/prod/php/ElasticOTel/Config/IntOptionMetadata.php deleted file mode 100644 index 48b0507..0000000 --- a/prod/php/ElasticOTel/Config/IntOptionMetadata.php +++ /dev/null @@ -1,39 +0,0 @@ - - */ -final class IntOptionMetadata extends OptionWithDefaultValueMetadata -{ - public function __construct(?int $minValidValue, ?int $maxValidValue, int $defaultValue) - { - parent::__construct(new IntOptionParser($minValidValue, $maxValidValue), $defaultValue); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/IntOptionParser.php b/prod/php/ElasticOTel/Config/IntOptionParser.php deleted file mode 100644 index 272cce1..0000000 --- a/prod/php/ElasticOTel/Config/IntOptionParser.php +++ /dev/null @@ -1,52 +0,0 @@ - - */ -final class IntOptionParser extends NumericOptionParser -{ - /** @inheritDoc */ - protected function dbgValueTypeDesc(): string - { - return 'int'; - } - - /** @inheritDoc */ - public static function isValidFormat(string $rawValue): bool - { - return filter_var($rawValue, FILTER_VALIDATE_INT) !== false; - } - - /** @inheritDoc */ - protected function stringToNumber(string $rawValue) - { - return intval($rawValue); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/KeyValuePairsOptionParser.php b/prod/php/ElasticOTel/Config/KeyValuePairsOptionParser.php deleted file mode 100644 index aecf803..0000000 --- a/prod/php/ElasticOTel/Config/KeyValuePairsOptionParser.php +++ /dev/null @@ -1,72 +0,0 @@ -> - */ -final class KeyValuePairsOptionParser extends OptionParser -{ - /** - * @param string $rawValue - * - * @return array - */ - public function parse(string $rawValue): array - { - // Value format: - // key=value[,key=value[,...]] - - // Treat empty string as zero key-value pairs - if (TextUtil::isEmptyString($rawValue)) { - return []; - } - - $pairs = explode(',', $rawValue); - $result = []; - foreach ($pairs as $keyValuePair) { - $keyValueSeparatorPos = strpos($keyValuePair, '='); - if ($keyValueSeparatorPos === false) { - throw new ParseException('One of key-value pairs is missing key-value separator' . ' ;' . LoggableToString::convert(['keyValuePair' => $keyValuePair, 'rawValue' => $rawValue])); - } - $key = trim(substr($keyValuePair, /* offset */ 0, /* length */ $keyValueSeparatorPos)); - $value = ($keyValueSeparatorPos === (strlen($keyValuePair) - 1)) ? '' : trim(substr($keyValuePair, /* offset */ $keyValueSeparatorPos + 1)); - if (array_key_exists($key, $result)) { - throw new ParseException( - 'Key is present more than once' - . ' ;' . LoggableToString::convert(['key' => $key, '1st value' => $result[$key], '2nd value' => $value, '2nd keyValuePair' => $keyValuePair, 'rawValue' => $rawValue]) - ); - } - $result[$key] = $value; - } - return $result; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/LabelsOptionParser.php b/prod/php/ElasticOTel/Config/LabelsOptionParser.php deleted file mode 100644 index 58a9c46..0000000 --- a/prod/php/ElasticOTel/Config/LabelsOptionParser.php +++ /dev/null @@ -1,82 +0,0 @@ -> - */ -final class LabelsOptionParser extends OptionParser -{ - /** - * @param string $valueAsString - * - * @return string|bool|int|float|null - */ - private static function parseValue(string $valueAsString) - { - if ($valueAsString === 'true') { - return true; - } - if ($valueAsString === 'false') { - return false; - } - - if (filter_var($valueAsString, FILTER_VALIDATE_INT) !== false) { - return intval($valueAsString); - } - - if (filter_var($valueAsString, FILTER_VALIDATE_FLOAT) !== false) { - return floatval($valueAsString); - } - - if ($valueAsString === 'null') { - return null; - } - - return Tracer::limitKeywordString($valueAsString); - } - - /** - * @param string $rawValue - * - * @return array - */ - public function parse(string $rawValue): array - { - // Value format: - // key=value[,key=value[,...]] - - $result = []; - foreach ((new KeyValuePairsOptionParser())->parse($rawValue) as $key => $valueAsString) { - $result[is_string($key) ? Tracer::limitKeywordString($key) : $key] = self::parseValue($valueAsString); - } - return $result; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/LogLevelOptionMetadata.php b/prod/php/ElasticOTel/Config/LogLevelOptionMetadata.php deleted file mode 100644 index f53789d..0000000 --- a/prod/php/ElasticOTel/Config/LogLevelOptionMetadata.php +++ /dev/null @@ -1,39 +0,0 @@ - - */ -final class LogLevelOptionMetadata extends OptionWithDefaultValueMetadata -{ - public function __construct(int $defaultValue) - { - parent::__construct(new LogLevelOptionParser(), $defaultValue); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/LogLevelOptionParser.php b/prod/php/ElasticOTel/Config/LogLevelOptionParser.php deleted file mode 100644 index a126446..0000000 --- a/prod/php/ElasticOTel/Config/LogLevelOptionParser.php +++ /dev/null @@ -1,41 +0,0 @@ - - */ -final class LogLevelOptionParser extends EnumOptionParser -{ - public function __construct() - { - parent::__construct(/* dbgEnumDesc */ 'log level', Level::nameIntPairs(), /* isCaseSensitive */ false, /* isUnambiguousPrefixAllowed */ true); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/NullableBoolOptionMetadata.php b/prod/php/ElasticOTel/Config/NullableBoolOptionMetadata.php deleted file mode 100644 index 81178ce..0000000 --- a/prod/php/ElasticOTel/Config/NullableBoolOptionMetadata.php +++ /dev/null @@ -1,39 +0,0 @@ - - */ -final class NullableBoolOptionMetadata extends NullableOptionMetadata -{ - public function __construct() - { - parent::__construct(new BoolOptionParser()); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/NullableIntOptionMetadata.php b/prod/php/ElasticOTel/Config/NullableIntOptionMetadata.php deleted file mode 100644 index 6721ee6..0000000 --- a/prod/php/ElasticOTel/Config/NullableIntOptionMetadata.php +++ /dev/null @@ -1,39 +0,0 @@ - - */ -final class NullableIntOptionMetadata extends NullableOptionMetadata -{ - public function __construct(?int $minValidValue, ?int $maxValidValue) - { - parent::__construct(new IntOptionParser($minValidValue, $maxValidValue)); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/NullableLabelsOptionMetadata.php b/prod/php/ElasticOTel/Config/NullableLabelsOptionMetadata.php deleted file mode 100644 index 525b186..0000000 --- a/prod/php/ElasticOTel/Config/NullableLabelsOptionMetadata.php +++ /dev/null @@ -1,41 +0,0 @@ -> - * - * @noinspection PhpUnused - */ -final class NullableLabelsOptionMetadata extends NullableOptionMetadata -{ - public function __construct() - { - parent::__construct(new LabelsOptionParser()); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/NullableLogLevelOptionMetadata.php b/prod/php/ElasticOTel/Config/NullableLogLevelOptionMetadata.php deleted file mode 100644 index bb196d0..0000000 --- a/prod/php/ElasticOTel/Config/NullableLogLevelOptionMetadata.php +++ /dev/null @@ -1,39 +0,0 @@ - - */ -final class NullableLogLevelOptionMetadata extends NullableOptionMetadata -{ - public function __construct() - { - parent::__construct(new LogLevelOptionParser()); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/NullableOptionMetadata.php b/prod/php/ElasticOTel/Config/NullableOptionMetadata.php deleted file mode 100644 index d114fe1..0000000 --- a/prod/php/ElasticOTel/Config/NullableOptionMetadata.php +++ /dev/null @@ -1,63 +0,0 @@ - - */ -abstract class NullableOptionMetadata extends OptionMetadata -{ - /** @var OptionParser */ - private $parser; - - /** - * @param OptionParser $parser - */ - public function __construct(OptionParser $parser) - { - $this->parser = $parser; - } - - /** @inheritDoc */ - public function parser(): OptionParser - { - return $this->parser; - } - - /** - * @inheritDoc - * - * @return null - */ - public function defaultValue() - { - return null; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/NullableStringOptionMetadata.php b/prod/php/ElasticOTel/Config/NullableStringOptionMetadata.php deleted file mode 100644 index ac22a7f..0000000 --- a/prod/php/ElasticOTel/Config/NullableStringOptionMetadata.php +++ /dev/null @@ -1,39 +0,0 @@ - - */ -final class NullableStringOptionMetadata extends NullableOptionMetadata -{ - public function __construct() - { - parent::__construct(new StringOptionParser()); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/NullableWildcardListOptionMetadata.php b/prod/php/ElasticOTel/Config/NullableWildcardListOptionMetadata.php deleted file mode 100644 index bf05ad7..0000000 --- a/prod/php/ElasticOTel/Config/NullableWildcardListOptionMetadata.php +++ /dev/null @@ -1,41 +0,0 @@ - - */ -final class NullableWildcardListOptionMetadata extends NullableOptionMetadata -{ - public function __construct() - { - parent::__construct(new WildcardListOptionParser()); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/NumericOptionParser.php b/prod/php/ElasticOTel/Config/NumericOptionParser.php deleted file mode 100644 index d0926c4..0000000 --- a/prod/php/ElasticOTel/Config/NumericOptionParser.php +++ /dev/null @@ -1,121 +0,0 @@ - - */ -abstract class NumericOptionParser extends OptionParser -{ - /** @var ?TParsedValue */ - private $minValidValue; - - /** - * @var ?TParsedValue */ - private $maxValidValue; - - /** - * NumericOptionMetadata constructor. - * - * @param ?TParsedValue $minValidValue - * @param ?TParsedValue $maxValidValue - */ - public function __construct($minValidValue, $maxValidValue) - { - $this->minValidValue = $minValidValue; - $this->maxValidValue = $maxValidValue; - } - - /** - * @return string - */ - abstract protected function dbgValueTypeDesc(): string; - - /** - * @param string $rawValue - * - * @return bool - */ - abstract public static function isValidFormat(string $rawValue): bool; - - /** - * @param string $rawValue - * - * @return TParsedValue - */ - abstract protected function stringToNumber(string $rawValue); - - /** - * @param string $rawValue - * - * @return TParsedValue - */ - public function parse(string $rawValue) - { - if (!static::isValidFormat($rawValue)) { - throw new ParseException( - 'Not a valid ' . $this->dbgValueTypeDesc() . " value. Raw option value: `''$rawValue'" - ); - } - - $parsedValue = $this->stringToNumber($rawValue); - - if ( - (($this->minValidValue !== null) && ($parsedValue < $this->minValidValue)) - || (($this->maxValidValue !== null) && ($parsedValue > $this->maxValidValue)) - ) { - throw new ParseException( - 'Value is not in range between the valid minimum and maximum values.' - . ' Raw option value: `' . $rawValue . "'." - . ' Parsed option value: ' . $parsedValue . '.' - . ' The valid minimum value: ' . $this->minValidValue . '.' - . ' The valid maximum value: ' . $this->maxValidValue . '.' - ); - } - - return $parsedValue; - } - - /** - * @return ?TParsedValue - */ - public function minValidValue() - { - return $this->minValidValue; - } - - /** - * @return ?TParsedValue - */ - public function maxValidValue() - { - return $this->maxValidValue; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/OptionDefaultValues.php b/prod/php/ElasticOTel/Config/OptionDefaultValues.php deleted file mode 100644 index 4c7c76a..0000000 --- a/prod/php/ElasticOTel/Config/OptionDefaultValues.php +++ /dev/null @@ -1,40 +0,0 @@ - - */ - abstract public function parser(): OptionParser; - - /** - * @return TParsedValue|null - */ - abstract public function defaultValue(); -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/OptionNames.php b/prod/php/ElasticOTel/Config/OptionNames.php deleted file mode 100644 index d378373..0000000 --- a/prod/php/ElasticOTel/Config/OptionNames.php +++ /dev/null @@ -1,70 +0,0 @@ - - */ -abstract class OptionWithDefaultValueMetadata extends OptionMetadata -{ - /** - * @var OptionParser - */ - private $parser; - - /** - * @var TParsedValue - */ - private $defaultValue; - - /** - * @param OptionParser $parser - * @param TParsedValue $defaultValue - */ - public function __construct(OptionParser $parser, $defaultValue) - { - $this->parser = $parser; - $this->defaultValue = $defaultValue; - } - - /** - * @inheritDoc - * - * @return OptionParser - */ - public function parser(): OptionParser - { - return $this->parser; - } - - /** - * @inheritDoc - * - * @return TParsedValue - */ - public function defaultValue() - { - return $this->defaultValue; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/ParseException.php b/prod/php/ElasticOTel/Config/ParseException.php deleted file mode 100644 index 8c26669..0000000 --- a/prod/php/ElasticOTel/Config/ParseException.php +++ /dev/null @@ -1,39 +0,0 @@ -logger = $loggerFactory->loggerForClass(LogCategory::CONFIGURATION, __NAMESPACE__, __CLASS__, __FILE__); - } - - /** - * @param string $rawValue - * @param OptionParser $optionParser - * - * @return mixed - * - * @template T - * @phpstan-param OptionParser $optionParser - * @phpstan-return T - */ - public static function parseOptionRawValue(string $rawValue, OptionParser $optionParser) - { - return $optionParser->parse(trim($rawValue)); - } - - /** - * @param array> $optNameToMeta - * @param RawSnapshotInterface $rawSnapshot - * - * @return array Option name to parsed value - */ - public function parse(array $optNameToMeta, RawSnapshotInterface $rawSnapshot): array - { - $optNameToParsedValue = []; - foreach ($optNameToMeta as $optName => $optMeta) { - $rawValue = $rawSnapshot->valueFor($optName); - if ($rawValue === null) { - $parsedValue = $optMeta->defaultValue(); - - ($loggerProxy = $this->logger->ifDebugLevelEnabled(__LINE__, __FUNCTION__)) - && $loggerProxy->log( - "Input raw config snapshot doesn't have a value for the option - using default value", - ['Option name' => $optName, 'Option default value' => $optMeta->defaultValue()] - ); - } else { - try { - $parsedValue = self::parseOptionRawValue($rawValue, $optMeta->parser()); - - ($loggerProxy = $this->logger->ifDebugLevelEnabled(__LINE__, __FUNCTION__)) - && $loggerProxy->log( - 'Input raw config snapshot has a value - using parsed value', - ['Option name' => $optName, 'Raw value' => $rawValue, 'Parsed value' => $parsedValue] - ); - } catch (ParseException $ex) { - $parsedValue = $optMeta->defaultValue(); - - ($loggerProxy = $this->logger->ifErrorLevelEnabled(__LINE__, __FUNCTION__)) - && $loggerProxy->log( - "Input raw config snapshot has a value but it's invalid - using default value", - [ - 'Option name' => $optName, - 'Option default value' => $optMeta->defaultValue(), - 'Exception' => $ex, - ] - ); - } - } - $optNameToParsedValue[$optName] = $parsedValue; - } - - return $optNameToParsedValue; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/RawSnapshotFromArray.php b/prod/php/ElasticOTel/Config/RawSnapshotFromArray.php deleted file mode 100644 index d1e0898..0000000 --- a/prod/php/ElasticOTel/Config/RawSnapshotFromArray.php +++ /dev/null @@ -1,50 +0,0 @@ - */ - private $optNameToRawValue; - - /** - * @param array $optNameToRawValue - */ - public function __construct(array $optNameToRawValue) - { - $this->optNameToRawValue = $optNameToRawValue; - } - - public function valueFor(string $optionName): ?string - { - return ArrayUtil::getValueIfKeyExistsElse($optionName, $this->optNameToRawValue, null); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/RawSnapshotInterface.php b/prod/php/ElasticOTel/Config/RawSnapshotInterface.php deleted file mode 100644 index ce09c58..0000000 --- a/prod/php/ElasticOTel/Config/RawSnapshotInterface.php +++ /dev/null @@ -1,34 +0,0 @@ -> $optionNameToMeta - * - * @return RawSnapshotInterface - */ - public function currentSnapshot(array $optionNameToMeta): RawSnapshotInterface; -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/Snapshot.php b/prod/php/ElasticOTel/Config/Snapshot.php deleted file mode 100644 index 8b79275..0000000 --- a/prod/php/ElasticOTel/Config/Snapshot.php +++ /dev/null @@ -1,376 +0,0 @@ -/prod/native/ext/ConfigManager.h to add the new option for C part of the agent. - // NOTE: Build C part of the agent after making the changes above and before proceeding to the steps below. - // - // - // 2) Add - // - // public const MY_NEW_OPTION = 'my_new_option'; - // - // to class \ElasticOTel\Config\OptionNames - // - // - // 3) Add - // - // OptionNames::MY_NEW_OPTION => new OptionMetadata(), - // - // to class \ElasticOTel\Config\AllOptionsMetadata - // - // - // 4) Add - // - // /** @var */ - // private $myNewOption; - // - // to class \ElasticOTel\Config\Snapshot - // - // - // 5) Add - // - // public function myNewOption(): - // { - // return $this->myNewOption; - // } - // - // to class \ElasticOTel\Config\Snapshot - // - // - // 6) Add - // - // OptionNames::MY_NEW_OPTION => RawToParsedValues, - // - // to return value of buildOptionNameToRawToValue() - // in class \ElasticApmTests\ComponentTests\ConfigSettingTest - // - // - // 7) Optionally add option specific test such as \ElasticApmTests\ComponentTests\ApiKeyTest - // - // - use SnapshotTrait; - use LoggableTrait; - - public const LOG_LEVEL_STDERR_DEFAULT = LogLevel::CRITICAL; - public const LOG_LEVEL_SYSLOG_DEFAULT = LogLevel::INFO; - - /** @var array */ - private $optNameToParsedValue; - - /** @var string */ - private $apiKey; - - /** @var bool */ - private $asyncBackendComm; - - /** @var bool */ - private $breakdownMetrics; - - /** @var bool */ - private $captureErrors; - - /** @var ?WildcardListMatcher */ - private $devInternal; - - /** @var SnapshotDevInternal */ - private $devInternalParsed; - - /** @var ?WildcardListMatcher */ - private $disableInstrumentations; - - /** @var bool */ - private $disableSend; - - /** @var bool */ - private $enabled; - - /** @var ?string */ - private $environment; - - /** @var ?array */ - private $globalLabels; - - /** @var ?string */ - private $hostname; - - /** @var ?int */ - private $logLevel; - - /** @var ?int */ - private $logLevelStderr; - - /** @var ?int */ - private $logLevelSyslog; - - /** @var int */ - private $nonKeywordStringMaxLength; - - /** @var WildcardListMatcher */ - private $sanitizeFieldNames; - - /** @var string */ - private $secretToken; - - /** @var float - In milliseconds */ - private $serverTimeout; - - /** @var ?string */ - private $serviceName; - - /** @var ?string */ - private $serviceNodeName; - - /** @var ?string */ - private $serviceVersion; - - /** @var bool */ - private $spanCompressionEnabled; - - /** @var float */ - private $spanCompressionExactMatchMaxDuration; - - /** @var float */ - private $spanCompressionSameKindMaxDuration; - - /** @var float */ - private $spanStackTraceMinDuration; - - /** @var int */ - private $stackTraceLimit; - - /** @var ?WildcardListMatcher */ - private $transactionIgnoreUrls; - - /** @var int */ - private $transactionMaxSpans; - - /** @var float */ - private $transactionSampleRate; - - /** @var ?WildcardListMatcher */ - private $urlGroups = null; - - /** @var bool */ - private $verifyServerCert; - - /** @var int */ - private $effectiveLogLevel; - - /** - * Snapshot constructor. - * - * @param array $optNameToParsedValue - */ - public function __construct(array $optNameToParsedValue, LoggerFactory $loggerFactory) - { - $this->setPropertiesToValuesFrom($optNameToParsedValue); - - $this->setEffectiveLogLevel(); - $this->adaptTransactionSampleRate(); - - $this->devInternalParsed = new SnapshotDevInternal($this->devInternal, $loggerFactory); - } - - private function setEffectiveLogLevel(): void - { - $this->effectiveLogLevel = max( - ($this->logLevelStderr ?? $this->logLevel) ?? self::LOG_LEVEL_STDERR_DEFAULT, - ($this->logLevelSyslog ?? $this->logLevel) ?? self::LOG_LEVEL_SYSLOG_DEFAULT, - $this->logLevel ?? LogLevel::OFF - ); - } - - private function adaptTransactionSampleRate(): void - { - if ($this->transactionSampleRate === 0.0) { - return; - } - - $minNonZeroValue = 0.0001; - if ($this->transactionSampleRate < $minNonZeroValue) { - $this->transactionSampleRate = $minNonZeroValue; - return; - } - - $this->transactionSampleRate = round( - $this->transactionSampleRate, - 4 /* <- precision - number of decimal digits */ - ); - } - - /** - * @param string $optName - * - * @return mixed - */ - public function parsedValueFor(string $optName) - { - return $this->optNameToParsedValue[$optName]; - } - - public function breakdownMetrics(): bool - { - return $this->breakdownMetrics; - } - - public function captureErrors(): bool - { - return $this->captureErrors; - } - - public function devInternal(): SnapshotDevInternal - { - return $this->devInternalParsed; - } - - public function disableInstrumentations(): ?WildcardListMatcher - { - return $this->disableInstrumentations; - } - - public function disableSend(): bool - { - return $this->disableSend; - } - - public function effectiveLogLevel(): int - { - return $this->effectiveLogLevel; - } - - public function enabled(): bool - { - return $this->enabled; - } - - public function environment(): ?string - { - return $this->environment; - } - - /** - * @return ?array - */ - public function globalLabels(): ?array - { - return $this->globalLabels; - } - - public function hostname(): ?string - { - return $this->hostname; - } - - public function nonKeywordStringMaxLength(): int - { - return $this->nonKeywordStringMaxLength; - } - - public function sanitizeFieldNames(): WildcardListMatcher - { - return $this->sanitizeFieldNames; - } - - public function serverTimeout(): float - { - return $this->serverTimeout; - } - - public function serviceName(): ?string - { - return $this->serviceName; - } - - public function serviceNodeName(): ?string - { - return $this->serviceNodeName; - } - - public function serviceVersion(): ?string - { - return $this->serviceVersion; - } - - public function spanCompressionEnabled(): bool - { - return $this->spanCompressionEnabled; - } - - public function spanCompressionExactMatchMaxDuration(): float - { - return $this->spanCompressionExactMatchMaxDuration; - } - - public function spanCompressionSameKindMaxDuration(): float - { - return $this->spanCompressionSameKindMaxDuration; - } - - public function spanStackTraceMinDuration(): float - { - return $this->spanStackTraceMinDuration; - } - - public function stackTraceLimit(): int - { - return $this->stackTraceLimit; - } - - public function transactionIgnoreUrls(): ?WildcardListMatcher - { - return $this->transactionIgnoreUrls; - } - - public function transactionMaxSpans(): int - { - return $this->transactionMaxSpans; - } - - public function transactionSampleRate(): float - { - return $this->transactionSampleRate; - } - - public function urlGroups(): ?WildcardListMatcher - { - return $this->urlGroups; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/SnapshotDevInternal.php b/prod/php/ElasticOTel/Config/SnapshotDevInternal.php deleted file mode 100644 index 4948dcf..0000000 --- a/prod/php/ElasticOTel/Config/SnapshotDevInternal.php +++ /dev/null @@ -1,94 +0,0 @@ -loggerForClass(LogCategory::CONFIGURATION, __NAMESPACE__, __CLASS__, __FILE__); - - foreach (get_object_vars($this) as $propName => $propValue) { - $subOptName = TextUtil::camelToSnakeCase($propName); - $matchedExpr = WildcardListMatcher::matchNullable($devInternal, $subOptName); - if ($matchedExpr === null) { - continue; - } - - ($loggerProxy = $logger->ifInfoLevelEnabled(__LINE__, __FUNCTION__)) - && $loggerProxy->log( - OptionNames::DEV_INTERNAL . ' sub-option ' . $subOptName . ' is set', - [OptionNames::DEV_INTERNAL . ' configuration' => $devInternal] - ); - - $this->$propName = true; - } - } - - public function dropEventAfterEnd(): bool - { - return $this->dropEventAfterEnd; - } - - public function dropEventsBeforeSendCCode(): bool - { - return $this->dropEventsBeforeSendCCode; - } - - public function gcCollectCyclesAfterEveryTransaction(): bool - { - return $this->gcCollectCyclesAfterEveryTransaction; - } - - public function gcMemCachesAfterEveryTransaction(): bool - { - return $this->gcMemCachesAfterEveryTransaction; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/SnapshotTrait.php b/prod/php/ElasticOTel/Config/SnapshotTrait.php deleted file mode 100644 index 13161e1..0000000 --- a/prod/php/ElasticOTel/Config/SnapshotTrait.php +++ /dev/null @@ -1,76 +0,0 @@ - */ - private $optNameToParsedValue; - - /** - * @param array $optNameToParsedValue - */ - protected function setPropertiesToValuesFrom(array $optNameToParsedValue): void - { - $this->optNameToParsedValue = $optNameToParsedValue; - - foreach ($optNameToParsedValue as $optName => $parsedValue) { - $propertyName = TextUtil::snakeToCamelCase($optName); - $actualClass = get_called_class(); - if (!property_exists($actualClass, $propertyName)) { - throw new RuntimeException("Property `$propertyName' doesn't exist in class " . $actualClass); - } - $this->$propertyName = $parsedValue; - } - - $this->optNameToParsedValue = $optNameToParsedValue; - } - - /** - * @param string $optName - * - * @return mixed - */ - public function getOptionValueByName(string $optName) - { - return ArrayUtil::getValueIfKeyExistsElse($optName, $this->optNameToParsedValue, null); - } - - /** - * @return array - */ - public function getOptionNameToParsedValueMap(): array - { - return $this->optNameToParsedValue; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/StringOptionMetadata.php b/prod/php/ElasticOTel/Config/StringOptionMetadata.php deleted file mode 100644 index 1b411bc..0000000 --- a/prod/php/ElasticOTel/Config/StringOptionMetadata.php +++ /dev/null @@ -1,41 +0,0 @@ - - * - * @noinspection PhpUnused - */ -final class StringOptionMetadata extends OptionWithDefaultValueMetadata -{ - public function __construct(string $defaultValue) - { - parent::__construct(new StringOptionParser(), $defaultValue); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/StringOptionParser.php b/prod/php/ElasticOTel/Config/StringOptionParser.php deleted file mode 100644 index f5b9668..0000000 --- a/prod/php/ElasticOTel/Config/StringOptionParser.php +++ /dev/null @@ -1,39 +0,0 @@ - - */ -final class StringOptionParser extends OptionParser -{ - public function parse(string $rawValue): string - { - return $rawValue; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/WildcardListOptionMetadata.php b/prod/php/ElasticOTel/Config/WildcardListOptionMetadata.php deleted file mode 100644 index 10f0379..0000000 --- a/prod/php/ElasticOTel/Config/WildcardListOptionMetadata.php +++ /dev/null @@ -1,41 +0,0 @@ - - */ -final class WildcardListOptionMetadata extends OptionWithDefaultValueMetadata -{ - public function __construct(WildcardListMatcher $defaultValue) - { - parent::__construct(new WildcardListOptionParser(), $defaultValue); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Config/WildcardListOptionParser.php b/prod/php/ElasticOTel/Config/WildcardListOptionParser.php deleted file mode 100644 index 1c2893a..0000000 --- a/prod/php/ElasticOTel/Config/WildcardListOptionParser.php +++ /dev/null @@ -1,56 +0,0 @@ - - */ -final class WildcardListOptionParser extends OptionParser -{ - /** @inheritDoc */ - public function parse(string $rawValue): WildcardListMatcher - { - return self::staticParse($rawValue); - } - - public static function staticParse(string $rawValue): WildcardListMatcher - { - /** - * @return iterable - */ - $splitWildcardExpr = function () use ($rawValue): iterable { - foreach (explode(',', $rawValue) as $listElementRaw) { - yield trim($listElementRaw); - } - }; - - return new WildcardListMatcher($splitWildcardExpr()); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/HttpTransport/ElasticHttpTransport.php b/prod/php/ElasticOTel/HttpTransport/ElasticHttpTransport.php index d452e4e..99f2eb5 100644 --- a/prod/php/ElasticOTel/HttpTransport/ElasticHttpTransport.php +++ b/prod/php/ElasticOTel/HttpTransport/ElasticHttpTransport.php @@ -23,20 +23,10 @@ namespace Elastic\OTel\HttpTransport; -use function assert; -use BadMethodCallException; -use function explode; -use function in_array; use OpenTelemetry\SDK\Common\Export\TransportInterface; use OpenTelemetry\SDK\Common\Future\CancellationInterface; use OpenTelemetry\SDK\Common\Future\CompletedFuture; -use OpenTelemetry\SDK\Common\Future\ErrorFuture; use OpenTelemetry\SDK\Common\Future\FutureInterface; -use RuntimeException; -use function strtolower; -use Throwable; -use function time_nanosleep; -use function trim; /** * @psalm-template CONTENT_TYPE of string diff --git a/prod/php/ElasticOTel/Log/AdhocLoggableObject.php b/prod/php/ElasticOTel/Log/AdhocLoggableObject.php deleted file mode 100644 index 55a06ab..0000000 --- a/prod/php/ElasticOTel/Log/AdhocLoggableObject.php +++ /dev/null @@ -1,63 +0,0 @@ - */ - private $propertyNameToData = []; - - /** - * @param array $nameToValue - * @param int $logPriority - */ - public function __construct(array $nameToValue, int $logPriority = PropertyLogPriority::NORMAL) - { - $this->addProperties($nameToValue, $logPriority); - } - - /** - * @param array $nameToValue - * @param int $logPriority - * - * @return self - */ - public function addProperties( - array $nameToValue, - /** @noinspection PhpUnusedParameterInspection */ int $logPriority = PropertyLogPriority::NORMAL - ): self { - $this->propertyNameToData += $nameToValue; - return $this; - } - - public function toLog(LogStreamInterface $stream): void - { - $stream->toLogAs($this->propertyNameToData); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Log/Backend.php b/prod/php/ElasticOTel/Log/Backend.php deleted file mode 100644 index 335dec8..0000000 --- a/prod/php/ElasticOTel/Log/Backend.php +++ /dev/null @@ -1,143 +0,0 @@ -maxEnabledLevel = $maxEnabledLevel; - $this->logSink = $logSink ?? - (ElasticOTelExtensionUtil::isLoaded() - ? new SinkToCExt() - : NoopLogSink::singletonInstance()); - } - - public function isEnabledForLevel(int $level): bool - { - return $this->maxEnabledLevel >= $level; - } - - public function clone(): self - { - return new self($this->maxEnabledLevel, $this->logSink); - } - - public function setMaxEnabledLevel(int $maxEnabledLevel): void - { - $this->maxEnabledLevel = $maxEnabledLevel; - } - - /** - * @param array $statementCtx - * @param LoggerData $loggerData - * - * @return array> - */ - private static function buildContextsStack(array $statementCtx, LoggerData $loggerData): array - { - $result = []; - - for ( - $currentLoggerData = $loggerData; - $currentLoggerData !== null; - $currentLoggerData = $currentLoggerData->inheritedData - ) { - $result[] = $currentLoggerData->context; - } - - $result[] = [ - self::NAMESPACE_KEY => $loggerData->namespace, - self::CLASS_KEY => ClassNameUtil::fqToShort($loggerData->fqClassName), - ]; - - $result[] = $statementCtx; - - return $result; - } - - /** - * @param int $statementLevel - * @param string $message - * @param array $statementCtx - * @param int $srcCodeLine - * @param string $srcCodeFunc - * @param LoggerData $loggerData - * @param bool|null $includeStacktrace - * @param int $numberOfStackFramesToSkip - * - * @phpstan-param 0|positive-int $numberOfStackFramesToSkip - */ - public function log( - int $statementLevel, - string $message, - array $statementCtx, - int $srcCodeLine, - string $srcCodeFunc, - LoggerData $loggerData, - ?bool $includeStacktrace, - int $numberOfStackFramesToSkip - ): void { - $this->logSink->consume( - $statementLevel, - $message, - self::buildContextsStack($statementCtx, $loggerData), - $loggerData->category, - $loggerData->srcCodeFile, - $srcCodeLine, - $srcCodeFunc, - $includeStacktrace, - $numberOfStackFramesToSkip + 1 - ); - } - - /** @noinspection PhpUnused */ - public function getSink(): SinkInterface - { - return $this->logSink; - } - - public function toLog(LogStreamInterface $stream): void - { - $stream->toLogAs(['maxEnabledLevel' => Level::intToName($this->maxEnabledLevel), 'logSink' => DbgUtil::getType($this->logSink)]); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Log/LogStream.php b/prod/php/ElasticOTel/Log/ElasticLogWriter.php similarity index 63% rename from prod/php/ElasticOTel/Log/LogStream.php rename to prod/php/ElasticOTel/Log/ElasticLogWriter.php index 5d30037..2959764 100644 --- a/prod/php/ElasticOTel/Log/LogStream.php +++ b/prod/php/ElasticOTel/Log/ElasticLogWriter.php @@ -23,23 +23,18 @@ namespace Elastic\OTel\Log; -/** - * Code in this file is part of implementation internals and thus it is not covered by the backward compatibility. - * - * @internal - */ -class LogStream implements LogStreamInterface -{ - /** @var mixed */ - public $value; +use OpenTelemetry\API\Behavior\Internal\LogWriter\LogWriterInterface; +use OpenTelemetry\API\Behavior\Internal\Logging; - public function isLastLevel(): bool +class ElasticLogWriter implements LogWriterInterface +{ + public function write($level, string $message, array $context): void { - return false; + \elastic_otel_log_feature(0, Level::getFromPsrLevel($level), LogFeature::OTEL, '', '', 0, $context['source'] ?? '', $message . ' context: ' . var_export($context, true)); } - public function toLogAs($value): void + public static function enableLogWriter() { - $this->value = $value; + Logging::setLogWriter(new ElasticLogWriter()); } -} \ No newline at end of file +} diff --git a/prod/php/ElasticOTel/Log/EnabledLoggerProxy.php b/prod/php/ElasticOTel/Log/EnabledLoggerProxy.php deleted file mode 100644 index 9de826a..0000000 --- a/prod/php/ElasticOTel/Log/EnabledLoggerProxy.php +++ /dev/null @@ -1,112 +0,0 @@ -statementLevel = $statementLevel; - $this->srcCodeLine = $srcCodeLine; - $this->srcCodeFunc = $srcCodeFunc; - $this->loggerData = $loggerData; - } - - public function includeStackTrace(bool $shouldIncludeStackTrace = true): self - { - $this->includeStackTrace = $shouldIncludeStackTrace; - return $this; - } - - /** - * @param string $message - * @param array $statementCtx - * - * @return bool - */ - public function log(string $message, array $statementCtx = []): bool - { - $this->loggerData->backend->log( - $this->statementLevel, - $message, - $statementCtx, - $this->srcCodeLine, - $this->srcCodeFunc, - $this->loggerData, - $this->includeStackTrace, - /* numberOfStackFramesToSkip */ 1 - ); - // return dummy bool to suppress PHPStan's "Right side of && is always false" - return true; - } - - /** - * @param Throwable $throwable - * @param string $message - * @param array $statementCtx - * - * @return bool - */ - public function logThrowable(Throwable $throwable, string $message, array $statementCtx = []): bool - { - $this->loggerData->backend->log( - $this->statementLevel, - $message, - $statementCtx + ['throwable' => $throwable], - $this->srcCodeLine, - $this->srcCodeFunc, - $this->loggerData, - $this->includeStackTrace, - /* numberOfStackFramesToSkip */ 1 - ); - // return dummy bool to suppress PHPStan's "Right side of && is always false" - return true; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Log/EnabledLoggerProxyNoLine.php b/prod/php/ElasticOTel/Log/EnabledLoggerProxyNoLine.php deleted file mode 100644 index 2b592cb..0000000 --- a/prod/php/ElasticOTel/Log/EnabledLoggerProxyNoLine.php +++ /dev/null @@ -1,71 +0,0 @@ -statementLevel = $statementLevel; - $this->srcCodeFunc = $srcCodeFunc; - $this->loggerData = $loggerData; - } - - /** - * @param int $srcCodeLine - * @param string $message - * @param array $statementCtx - * - * @return bool - */ - public function log(int $srcCodeLine, string $message, array $statementCtx = []): bool - { - $this->loggerData->backend->log( - $this->statementLevel, - $message, - $statementCtx, - $srcCodeLine, - $this->srcCodeFunc, - $this->loggerData, - null /* <- includeStackTrace */, - 1 /* <- numberOfStackFramesToSkip */ - ); - // return dummy bool to suppress PHPStan's "Right side of && is always false" - return true; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Log/Level.php b/prod/php/ElasticOTel/Log/Level.php index f3a94ad..de436ab 100644 --- a/prod/php/ElasticOTel/Log/Level.php +++ b/prod/php/ElasticOTel/Log/Level.php @@ -80,4 +80,26 @@ public static function getHighest(): int { return self::TRACE; } + + public static function getFromPsrLevel($level): int + { + switch ($level) { + case \Psr\Log\LogLevel::EMERGENCY: + case \Psr\Log\LogLevel::ALERT: + case \Psr\Log\LogLevel::CRITICAL: + return Level::CRITICAL; + case \Psr\Log\LogLevel::ERROR: + return Level::ERROR; + case \Psr\Log\LogLevel::WARNING: + return Level::WARNING; + case \Psr\Log\LogLevel::NOTICE: + case \Psr\Log\LogLevel::INFO: + return Level::INFO; + case \Psr\Log\LogLevel::DEBUG: + return Level::DEBUG; + default: + return Level::OFF; + } + } + } \ No newline at end of file diff --git a/prod/php/ElasticOTel/Log/LogCategory.php b/prod/php/ElasticOTel/Log/LogCategory.php deleted file mode 100644 index f905667..0000000 --- a/prod/php/ElasticOTel/Log/LogCategory.php +++ /dev/null @@ -1,45 +0,0 @@ - */ - private $wrappedArray; - - /** - * @param array $wrappedArray - */ - public function __construct(array $wrappedArray) - { - $this->wrappedArray = $wrappedArray; - } - - public function toLog(LogStreamInterface $stream): void - { - if ($stream->isLastLevel()) { - $stream->toLogAs( - [LogConsts::TYPE_KEY => self::ARRAY_TYPE, self::COUNT_KEY => count($this->wrappedArray)] - ); - return; - } - - $stream->toLogAs( - [LogConsts::TYPE_KEY => self::ARRAY_TYPE, self::COUNT_KEY => count($this->wrappedArray)] - ); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Log/LoggableInterface.php b/prod/php/ElasticOTel/Log/LoggableInterface.php deleted file mode 100644 index cd7babd..0000000 --- a/prod/php/ElasticOTel/Log/LoggableInterface.php +++ /dev/null @@ -1,39 +0,0 @@ -captureInClassicFormat(/* offset */ $numberOfStackFramesToSkip + 1, $maxNumberOfStackFrames); - $result = []; - - foreach ($classicFormatFrames as $classicFormatFrame) { - $resultFrame = []; - $adaptFilePath = self::adaptSourceCodeFilePath($classicFormatFrame->file); - $setIfNotNull(StackTraceUtil::FILE_KEY, $adaptFilePath, $resultFrame); - $setIfNotNull(StackTraceUtil::LINE_KEY, $classicFormatFrame->line, $resultFrame); - if ($classicFormatFrame->class !== null) { - $classShortName = ClassNameUtil::fqToShort($classicFormatFrame->class); // @phpstan-ignore-line - $resultFrame[StackTraceUtil::CLASS_KEY] = $classShortName; - } - $setIfNotNull(StackTraceUtil::FUNCTION_KEY, $classicFormatFrame->function, $resultFrame); - $result[] = $resultFrame; - } - return $result; - } - - public static function adaptSourceCodeFilePath(?string $srcFile): ?string - { - return $srcFile === null ? null : basename($srcFile); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Log/LoggableToEncodedJson.php b/prod/php/ElasticOTel/Log/LoggableToEncodedJson.php deleted file mode 100644 index 1786263..0000000 --- a/prod/php/ElasticOTel/Log/LoggableToEncodedJson.php +++ /dev/null @@ -1,72 +0,0 @@ - DbgUtil::getType($value)], - $ex - ); - } - - try { - return JsonUtil::encode($jsonEncodable, $prettyPrint); - } catch (Exception $ex) { - return LoggingSubsystem::onInternalFailure( - 'JsonUtil::encode() failed', - ['$jsonEncodable type' => DbgUtil::getType($jsonEncodable)], - $ex - ); - } - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Log/LoggableToJsonEncodable.php b/prod/php/ElasticOTel/Log/LoggableToJsonEncodable.php deleted file mode 100644 index eb8daf5..0000000 --- a/prod/php/ElasticOTel/Log/LoggableToJsonEncodable.php +++ /dev/null @@ -1,421 +0,0 @@ - */ - private static $isDtoObjectCache = []; - - /** - * @param array $value - * @param int $depth - * - * @return array - */ - public static function convertArrayForMaxDepth(array $value, int $depth): array - { - return [LogConsts::MAX_DEPTH_REACHED => $depth, LogConsts::TYPE_KEY => DbgUtil::getType($value), LogConsts::ARRAY_COUNT_KEY => count($value)]; - } - - /** - * @param object $value - * @param int $depth - * - * @return array - */ - public static function convertObjectForMaxDepth(object $value, int $depth): array - { - return [LogConsts::MAX_DEPTH_REACHED => $depth, LogConsts::TYPE_KEY => DbgUtil::getType($value)]; - } - - /** - * @param mixed $value - * - * @return mixed - */ - public static function convert($value, int $depth) - { - if ($value === null) { - return null; - } - - // Scalar variables are those containing an int, float, string or bool. - // Types array, object and resource are not scalar. - if (is_scalar($value)) { - return $value; - } - - if (is_array($value)) { - if ($depth >= self::$maxDepth) { - return self::convertArrayForMaxDepth($value, $depth); - } - return self::convertArray($value, $depth + 1); - } - - if (is_resource($value)) { - return self::convertOpenResource($value); - } - - if (is_object($value)) { - if ($depth >= self::$maxDepth) { - return self::convertObjectForMaxDepth($value, $depth); - } - return self::convertObject($value, $depth); - } - - return [LogConsts::TYPE_KEY => DbgUtil::getType($value), LogConsts::VALUE_AS_STRING_KEY => strval($value)]; - } - - /** - * @param array $array - * - * @return array - */ - private static function convertArray(array $array, int $depth): array - { - return self::convertArrayImpl($array, ArrayUtil::isList($array), $depth); - } - - /** - * @param array $array - * @param bool $isListArray - * @param int $depth - * - * @return array - */ - private static function convertArrayImpl(array $array, bool $isListArray, int $depth): array - { - $arrayCount = count($array); - $smallArrayMaxCount = $isListArray - ? LogConsts::SMALL_LIST_ARRAY_MAX_COUNT - : LogConsts::SMALL_MAP_ARRAY_MAX_COUNT; - if ($arrayCount <= $smallArrayMaxCount) { - return self::convertSmallArray($array, $isListArray, $depth); - } - - $result = [LogConsts::TYPE_KEY => LogConsts::LIST_ARRAY_TYPE_VALUE]; - $result[LogConsts::ARRAY_COUNT_KEY] = $arrayCount; - - $halfOfSmallArrayMaxCount = intdiv($smallArrayMaxCount, 2); - $firstElements = array_slice($array, 0, $halfOfSmallArrayMaxCount); - $result['0-' . intdiv($smallArrayMaxCount, 2)] - = self::convertSmallArray($firstElements, $isListArray, $depth); - - $result[($arrayCount - $halfOfSmallArrayMaxCount) . '-' . $arrayCount] - = self::convertSmallArray(array_slice($array, -$halfOfSmallArrayMaxCount), $isListArray, $depth); - - return $result; - } - - /** - * @param array $array - * @param bool $isListArray - * @param int $depth - * - * @return array - */ - private static function convertSmallArray(array $array, bool $isListArray, int $depth): array - { - return $isListArray ? self::convertSmallListArray($array, $depth) : self::convertSmallMapArray($array, $depth); - } - - /** - * @param array $listArray - * - * @return array - */ - private static function convertSmallListArray(array $listArray, int $depth): array - { - $result = []; - foreach ($listArray as $value) { - $result[] = self::convert($value, $depth); - } - return $result; - } - - /** - * @param array $mapArrayValue - * - * @return array - */ - private static function convertSmallMapArray(array $mapArrayValue, int $depth): array - { - return self::isStringKeysMapArray($mapArrayValue) - ? self::convertSmallStringKeysMapArray($mapArrayValue, $depth) - : self::convertSmallMixedKeysMapArray($mapArrayValue, $depth); - } - - /** - * @param array $mapArrayValue - * - * @return bool - */ - private static function isStringKeysMapArray(array $mapArrayValue): bool - { - foreach ($mapArrayValue as $key => $_) { - if (!is_string($key)) { - return false; - } - } - return true; - } - - /** - * @param array $mapArrayValue - * - * @return array - */ - private static function convertSmallStringKeysMapArray(array $mapArrayValue, int $depth): array - { - $result = []; - foreach ($mapArrayValue as $key => $value) { - $result[$key] = self::convert($value, $depth); - } - return $result; - } - - /** - * @param array $mapArrayValue - * @param int $depth - * - * @return array - */ - private static function convertSmallMixedKeysMapArray(array $mapArrayValue, int $depth): array - { - $result = []; - foreach ($mapArrayValue as $key => $value) { - $result[] = ['key' => self::convert($key, $depth), 'value' => self::convert($value, $depth)]; - } - return $result; - } - - /** - * @param resource $resource - * - * @return array - */ - private static function convertOpenResource($resource): array - { - return [ - LogConsts::TYPE_KEY => LogConsts::RESOURCE_TYPE_VALUE, - LogConsts::RESOURCE_TYPE_KEY => get_resource_type($resource), - LogConsts::RESOURCE_ID_KEY => intval($resource), - ]; - } - - /** - * @param object $object - * @param int $depth - * - * @return mixed - */ - private static function convertObject(object $object, int $depth) - { - if ($object instanceof LoggableInterface) { - return self::convertLoggable($object, $depth); - } - - if ($object instanceof Throwable) { - return self::convertThrowable($object, $depth); - } - - $fqClassName = get_class($object); - $isFromElasticNamespace = TextUtil::isPrefixOf('Elastic\\Apm\\', $fqClassName) - || TextUtil::isPrefixOf('ElasticApmTests\\', $fqClassName); - if ($isFromElasticNamespace && self::isDtoObject($object)) { - return self::convertDtoObject($object, $depth); - } - - if (method_exists($object, '__debugInfo')) { - return [ - LogConsts::TYPE_KEY => get_class($object), - LogConsts::VALUE_AS_DEBUG_INFO_KEY => self::convert($object->__debugInfo(), $depth), - ]; - } - - if (method_exists($object, '__toString')) { - return [ - LogConsts::TYPE_KEY => get_class($object), - LogConsts::VALUE_AS_STRING_KEY => self::convert($object->__toString(), $depth), - ]; - } - - return [ - LogConsts::TYPE_KEY => get_class($object), - LogConsts::OBJECT_ID_KEY => spl_object_id($object), - LogConsts::OBJECT_HASH_KEY => spl_object_hash($object), - ]; - } - - /** - * @param LoggableInterface $loggable - * @param int $depth - * - * @return mixed - */ - private static function convertLoggable(LoggableInterface $loggable, int $depth) - { - $logStream = new LogStream(); - $loggable->toLog($logStream); - return self::convert($logStream->value, $depth); - } - - /** - * @param Throwable $throwable - * @param int $depth - * - * @return array - */ - private static function convertThrowable(Throwable $throwable, int $depth): array - { - return [ - LogConsts::TYPE_KEY => get_class($throwable), - LogConsts::VALUE_AS_STRING_KEY => self::convert($throwable->__toString(), $depth), - ]; - } - - /** - * @param object $object - * @param int $depth - * - * @return string|array - * @phpstan-return array - */ - private static function convertDtoObject(object $object, int $depth) - { - $class = get_class($object); - try { - $currentClass = new ReflectionClass($class); - /** @phpstan-ignore-next-line */ - } catch (ReflectionException $ex) { - return LoggingSubsystem::onInternalFailure('Failed to reflect', ['class' => $class], $ex); - } - - $nameToValue = []; - while (true) { - foreach ($currentClass->getProperties() as $reflectionProperty) { - if ($reflectionProperty->isStatic()) { - continue; - } - - $propName = $reflectionProperty->name; - $propValue = $reflectionProperty->getValue($object); - $nameToValue[$propName] = self::convert($propValue, $depth); - } - $currentClass = $currentClass->getParentClass(); - if ($currentClass === false) { - break; - } - } - return $nameToValue; - } - - private static function isDtoObject(object $object): bool - { - $class = get_class($object); - $valueInCache = ArrayUtil::getValueIfKeyExistsElse($class, self::$isDtoObjectCache, null); - if ($valueInCache !== null) { - return $valueInCache; - } - - $value = self::detectIfDtoObject($class); - - self::addToIsDtoObjectCache($class, $value); - - return $value; - } - - /** - * @template T of object - * - * @param class-string $className - * - * @return bool - */ - private static function detectIfDtoObject(string $className): bool - { - try { - $currentClass = new ReflectionClass($className); - /** @phpstan-ignore-next-line */ - } catch (ReflectionException $ex) { - LoggingSubsystem::onInternalFailure('Failed to reflect', ['className' => $className], $ex); - return false; - } - - while (true) { - foreach ($currentClass->getProperties() as $reflectionProperty) { - if ($reflectionProperty->isStatic()) { - continue; - } - - if (!$reflectionProperty->isPublic()) { - return false; - } - } - $currentClass = $currentClass->getParentClass(); - if ($currentClass === false) { - break; - } - } - - return true; - } - - private static function addToIsDtoObjectCache(string $class, bool $value): void - { - $isDtoObjectCacheCount = count(self::$isDtoObjectCache); - if ($isDtoObjectCacheCount >= self::IS_DTO_OBJECT_CACHE_MAX_COUNT_HIGH_WATER_MARK) { - self::$isDtoObjectCache = array_slice( - self::$isDtoObjectCache, - $isDtoObjectCacheCount - self::IS_DTO_OBJECT_CACHE_MAX_COUNT_LOW_WATER_MARK - ); - } - - self::$isDtoObjectCache[$class] = $value; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Log/LoggableToString.php b/prod/php/ElasticOTel/Log/LoggableToString.php deleted file mode 100644 index 92ec6fd..0000000 --- a/prod/php/ElasticOTel/Log/LoggableToString.php +++ /dev/null @@ -1,50 +0,0 @@ - $customPropValues - */ - protected function toLogLoggableTraitImpl(LogStreamInterface $stream, array $customPropValues = []): void - { - $nameToValue = $customPropValues; - - $classNameToLog = static::classNameToLog(); - if ($classNameToLog !== null) { - $nameToValue[LogConsts::TYPE_KEY] = $classNameToLog; - } - - try { - $currentClass = new ReflectionClass(get_class($this)); - } /** @noinspection PhpRedundantCatchClauseInspection */ catch (ReflectionException $ex) { - $stream->toLogAs( - LoggingSubsystem::onInternalFailure('Failed to reflect', ['class' => get_class($this)], $ex) - ); - return; - } - - $propertiesExcludedFromLog = array_merge(static::propertiesExcludedFromLog(), static::defaultPropertiesExcludedFromLog()); - while (true) { - foreach ($currentClass->getProperties() as $reflectionProperty) { - if ($reflectionProperty->isStatic()) { - continue; - } - - $reflectionProperty->setAccessible(true); - $propName = $reflectionProperty->name; - if (array_key_exists($propName, $customPropValues)) { - continue; - } - if (in_array($propName, $propertiesExcludedFromLog, /* strict */ true)) { - continue; - } - $nameToValue[$propName] = $reflectionProperty->getValue($this); - } - $currentClass = $currentClass->getParentClass(); - if ($currentClass === false) { - break; - } - } - - $stream->toLogAs($nameToValue); - } - - public function toLog(LogStreamInterface $stream): void - { - $this->toLogLoggableTraitImpl($stream); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Log/Logger.php b/prod/php/ElasticOTel/Log/Logger.php deleted file mode 100644 index 67051d2..0000000 --- a/prod/php/ElasticOTel/Log/Logger.php +++ /dev/null @@ -1,208 +0,0 @@ -data = $data; - } - - /** - * @param string $category - * @param string $namespace - * @param class-string $fqClassName - * @param string $srcCodeFile - * @param array $context - * @param Backend $backend - * - * @return static - */ - public static function makeRoot( - string $category, - string $namespace, - string $fqClassName, - string $srcCodeFile, - array $context, - Backend $backend - ): self { - return new self(LoggerData::makeRoot($category, $namespace, $fqClassName, $srcCodeFile, $context, $backend)); - } - - public function inherit(): self - { - return new self($this->data->inherit()); - } - - /** - * @param string $key - * @param mixed $value - * - * @return Logger - */ - public function addContext(string $key, $value): self - { - $this->data->context[$key] = $value; - return $this; - } - - /** - * @param array $keyValuePairs - * - * @return Logger - */ - public function addAllContext(array $keyValuePairs): self - { - foreach ($keyValuePairs as $key => $value) { - $this->addContext($key, $value); - } - return $this; - } - - /** - * @return array - * - * @noinspection PhpUnused - */ - public function getContext(): array - { - return $this->data->context; - } - - public function ifCriticalLevelEnabled(int $srcCodeLine, string $srcCodeFunc): ?EnabledLoggerProxy - { - return $this->ifLevelEnabled(Level::CRITICAL, $srcCodeLine, $srcCodeFunc); - } - - public function ifErrorLevelEnabled(int $srcCodeLine, string $srcCodeFunc): ?EnabledLoggerProxy - { - return $this->ifLevelEnabled(Level::ERROR, $srcCodeLine, $srcCodeFunc); - } - - public function ifWarningLevelEnabled(int $srcCodeLine, string $srcCodeFunc): ?EnabledLoggerProxy - { - return $this->ifLevelEnabled(Level::WARNING, $srcCodeLine, $srcCodeFunc); - } - - public function ifInfoLevelEnabled(int $srcCodeLine, string $srcCodeFunc): ?EnabledLoggerProxy - { - return $this->ifLevelEnabled(Level::INFO, $srcCodeLine, $srcCodeFunc); - } - - public function ifDebugLevelEnabled(int $srcCodeLine, string $srcCodeFunc): ?EnabledLoggerProxy - { - return $this->ifLevelEnabled(Level::DEBUG, $srcCodeLine, $srcCodeFunc); - } - - public function ifTraceLevelEnabled(int $srcCodeLine, string $srcCodeFunc): ?EnabledLoggerProxy - { - return $this->ifLevelEnabled(Level::TRACE, $srcCodeLine, $srcCodeFunc); - } - - /** @noinspection PhpUnused */ - public function ifCriticalLevelEnabledNoLine(string $srcCodeFunc): ?EnabledLoggerProxyNoLine - { - return $this->ifLevelEnabledNoLine(Level::CRITICAL, $srcCodeFunc); - } - - /** @noinspection PhpUnused */ - public function ifErrorLevelEnabledNoLine(string $srcCodeFunc): ?EnabledLoggerProxyNoLine - { - return $this->ifLevelEnabledNoLine(Level::ERROR, $srcCodeFunc); - } - - /** @noinspection PhpUnused */ - public function ifWarningLevelEnabledNoLine(string $srcCodeFunc): ?EnabledLoggerProxyNoLine - { - return $this->ifLevelEnabledNoLine(Level::WARNING, $srcCodeFunc); - } - - /** @noinspection PhpUnused */ - public function ifInfoLevelEnabledNoLine(string $srcCodeFunc): ?EnabledLoggerProxyNoLine - { - return $this->ifLevelEnabledNoLine(Level::INFO, $srcCodeFunc); - } - - /** @noinspection PhpUnused */ - public function ifDebugLevelEnabledNoLine(string $srcCodeFunc): ?EnabledLoggerProxyNoLine - { - return $this->ifLevelEnabledNoLine(Level::DEBUG, $srcCodeFunc); - } - - public function ifTraceLevelEnabledNoLine(string $srcCodeFunc): ?EnabledLoggerProxyNoLine - { - return $this->ifLevelEnabledNoLine(Level::TRACE, $srcCodeFunc); - } - - public function ifLevelEnabled(int $statementLevel, int $srcCodeLine, string $srcCodeFunc): ?EnabledLoggerProxy - { - return ($this->data->backend->isEnabledForLevel($statementLevel)) - ? new EnabledLoggerProxy($statementLevel, $srcCodeLine, $srcCodeFunc, $this->data) - : null; - } - - public function ifLevelEnabledNoLine(int $statementLevel, string $srcCodeFunc): ?EnabledLoggerProxyNoLine - { - return ($this->data->backend->isEnabledForLevel($statementLevel)) - ? new EnabledLoggerProxyNoLine($statementLevel, $srcCodeFunc, $this->data) - : null; - } - - public function isEnabledForLevel(int $level): bool - { - return $this->data->backend->isEnabledForLevel($level); - } - - public function isTraceLevelEnabled(): bool - { - return $this->isEnabledForLevel(Level::TRACE); - } - - /** - * @param mixed $value - * - * @return mixed - */ - public function possiblySecuritySensitive($value) - { - if ($this->data->backend->isEnabledForLevel(Level::TRACE)) { - return $value; - } - return 'REDUCTED (POSSIBLY SECURITY SENSITIVE) DATA'; - } - - public function toLog(LogStreamInterface $stream): void - { - $stream->toLogAs($this->data); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Log/LoggerData.php b/prod/php/ElasticOTel/Log/LoggerData.php deleted file mode 100644 index ce221cd..0000000 --- a/prod/php/ElasticOTel/Log/LoggerData.php +++ /dev/null @@ -1,137 +0,0 @@ - */ - public $context; - - /** @var Backend */ - public $backend; - - /** - * @param string $category - * @param string $namespace - * @param class-string $fqClassName - * @param string $srcCodeFile - * @param array $context - * @param Backend $backend - * @param ?LoggerData $inheritedData - */ - private function __construct( - string $category, - string $namespace, - string $fqClassName, - string $srcCodeFile, - array $context, - Backend $backend, - ?LoggerData $inheritedData - ) { - $this->category = $category; - $this->namespace = $namespace; - $this->fqClassName = $fqClassName; - $this->srcCodeFile = $srcCodeFile; - $this->context = $context; - $this->backend = $backend; - $this->inheritedData = $inheritedData; - } - - /** - * @param string $category - * @param string $namespace - * @param class-string $fqClassName - * @param string $srcCodeFile - * @param array $context - * @param Backend $backend - * - * @return self - */ - public static function makeRoot( - string $category, - string $namespace, - string $fqClassName, - string $srcCodeFile, - array $context, - Backend $backend - ): self { - return new self( - $category, - $namespace, - $fqClassName, - $srcCodeFile, - $context, - $backend, - /* inheritedData */ null - ); - } - - public function inherit(): self - { - return new self( - $this->category, - $this->namespace, - $this->fqClassName, - $this->srcCodeFile, - [] /* <- context */, - $this->backend, - $this - ); - } - - public function toLog(LogStreamInterface $stream): void - { - $stream->toLogAs( - [ - 'category' => $this->category, - 'namespace' => $this->namespace, - 'fqClassName' => $this->fqClassName, - 'srcCodeFile' => $this->srcCodeFile, - 'inheritedData' => $this->inheritedData, - 'count(context)' => count($this->context), - 'backend' => $this->backend, - ] - ); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Log/LoggerFactory.php b/prod/php/ElasticOTel/Log/LoggerFactory.php deleted file mode 100644 index 42100b0..0000000 --- a/prod/php/ElasticOTel/Log/LoggerFactory.php +++ /dev/null @@ -1,105 +0,0 @@ - */ - public $context; - - /** - * @param Backend $backend - * @param array $context - */ - public function __construct(Backend $backend, array $context = []) - { - $this->backend = $backend; - $this->context = $context; - } - - /** - * @param string $category - * @param string $namespace - * @param class-string $fqClassName - * @param string $srcCodeFile - * - * @return Logger - */ - public function loggerForClass( - string $category, - string $namespace, - string $fqClassName, - string $srcCodeFile - ): Logger { - return Logger::makeRoot($category, $namespace, $fqClassName, $srcCodeFile, $this->context, $this->backend); - } - - public function getBackend(): Backend - { - return $this->backend; - } - - public function isEnabledForLevel(int $level): bool - { - return $this->backend->isEnabledForLevel($level); - } - - public function inherit(): self - { - return new self($this->backend); - } - - /** - * @param string $key - * @param mixed $value - * - * @return self - */ - public function addContext(string $key, $value): self - { - $this->context[$key] = $value; - return $this; - } - - /** - * @param array $keyValuePairs - * - * @return self - */ - public function addAllContext(array $keyValuePairs): self - { - foreach ($keyValuePairs as $key => $value) { - $this->addContext($key, $value); - } - return $this; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Log/LoggingSubsystem.php b/prod/php/ElasticOTel/Log/LoggingSubsystem.php deleted file mode 100644 index 6c1b5b7..0000000 --- a/prod/php/ElasticOTel/Log/LoggingSubsystem.php +++ /dev/null @@ -1,66 +0,0 @@ - $context - * @param Throwable $causedBy - * - * @return string - */ - public static function onInternalFailure(string $message, array $context, Throwable $causedBy): string - { - self::$wereThereAnyInternalFailures = true; - if (self::$isInTestingContext) { - throw new LoggingSubsystemException(ExceptionUtil::buildMessage($message, $context), $causedBy); - } - - return $message . '. ' . LoggableToString::convert($context + ['causedBy' => $causedBy]); - } - - public static function wereThereAnyInternalFailures(): bool - { - return self::$wereThereAnyInternalFailures; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Log/LoggingSubsystemException.php b/prod/php/ElasticOTel/Log/LoggingSubsystemException.php deleted file mode 100644 index d3c1bc3..0000000 --- a/prod/php/ElasticOTel/Log/LoggingSubsystemException.php +++ /dev/null @@ -1,40 +0,0 @@ - $currentContext */ - $currentContext = current($contextsStack); - foreach ($currentContext as $key => $value) { - $combinedContext[$key] = $value; - } - } - - if ($includeStacktrace === null ? ($statementLevel <= Level::ERROR) : $includeStacktrace) { - $combinedContext[LoggableStackTrace::STACK_TRACE_KEY] = LoggableStackTrace::buildForCurrent($numberOfStackFramesToSkip + 1); - } - - $ctxAsStr = LoggableToString::convert($combinedContext); - $msgCtxSeparator = (TextUtil::isEmptyString($message) || TextUtil::isEmptyString($ctxAsStr)) ? '' : ' '; - $messageWithContext = $message . $msgCtxSeparator . $ctxAsStr; - - $this->consumePreformatted( - $statementLevel, - $category, - $srcCodeFile, - $srcCodeLine, - $srcCodeFunc, - $messageWithContext - ); - } - - /** - * @param int $statementLevel - * @param string $category - * @param string $srcCodeFile - * @param int $srcCodeLine - * @param string $srcCodeFunc - * @param string $messageWithContext - */ - abstract protected function consumePreformatted( - int $statementLevel, - string $category, - string $srcCodeFile, - int $srcCodeLine, - string $srcCodeFunc, - string $messageWithContext - ): void; -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Log/SinkInterface.php b/prod/php/ElasticOTel/Log/SinkInterface.php deleted file mode 100644 index 010da77..0000000 --- a/prod/php/ElasticOTel/Log/SinkInterface.php +++ /dev/null @@ -1,57 +0,0 @@ -[] $contextsStack - * @param string $category - * @param string $srcCodeFile - * @param int $srcCodeLine - * @param string $srcCodeFunc - * @param ?bool $includeStacktrace - * @param int $numberOfStackFramesToSkip - * - * @phpstan-param 0|positive-int $numberOfStackFramesToSkip - */ - public function consume( - int $statementLevel, - string $message, - array $contextsStack, - string $category, - string $srcCodeFile, - int $srcCodeLine, - string $srcCodeFunc, - ?bool $includeStacktrace, - int $numberOfStackFramesToSkip - ): void; -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Log/SinkToCExt.php b/prod/php/ElasticOTel/Log/SinkToCExt.php deleted file mode 100644 index 9981049..0000000 --- a/prod/php/ElasticOTel/Log/SinkToCExt.php +++ /dev/null @@ -1,57 +0,0 @@ -bootstrap(); self::prepareEnvForOTelSdk(); self::registerAutoloader(); self::registerAsyncTransportFactory(); + self::registerOtelLogWriter(); self::$singletonInstance = new self(); } catch (Throwable $throwable) { @@ -181,10 +184,12 @@ private static function registerAsyncTransportFactory(): void return; } - // TODO remove after autoloader implementation - require __DIR__ . DIRECTORY_SEPARATOR . 'HttpTransport' . DIRECTORY_SEPARATOR . 'ElasticHttpTransport.php'; - require __DIR__ . DIRECTORY_SEPARATOR . 'HttpTransport' . DIRECTORY_SEPARATOR . 'ElasticHttpTransportFactory.php'; - \OpenTelemetry\SDK\Registry::registerTransportFactory('http', \Elastic\Otel\HttpTransport\ElasticHttpTransportFactory::class, true); + \OpenTelemetry\SDK\Registry::registerTransportFactory('http', ElasticHttpTransportFactory::class, true); + } + + private static function registerOtelLogWriter() + { + ElasticLogWriter::enableLogWriter(); } /** diff --git a/prod/php/ElasticOTel/Util/ArrayUtil.php b/prod/php/ElasticOTel/Util/ArrayUtil.php deleted file mode 100644 index 1e04c6d..0000000 --- a/prod/php/ElasticOTel/Util/ArrayUtil.php +++ /dev/null @@ -1,225 +0,0 @@ - $array - * @phpstan-param-out TValue $valueDst - * @phpstan-assert-if-true TValue $valueDst - */ - public static function getValueIfKeyExists(string|int $key, array $array, mixed &$valueDst): bool - { - if (!array_key_exists($key, $array)) { - return false; - } - - $valueDst = $array[$key]; - return true; - } - - /** - * @template TKey of string|int - * @template TValue - * - * @param TKey $key - * @param array $array - * @param TValue $fallbackValue - * - * @return TValue - */ - public static function getValueIfKeyExistsElse($key, array $array, $fallbackValue) - { - return array_key_exists($key, $array) ? $array[$key] : $fallbackValue; - } - - /** - * @param string|int $key - * @param array $array - * @param string $fallbackValue - * - * @return string - */ - public static function getStringValueIfKeyExistsElse($key, array $array, string $fallbackValue): string - { - if (!array_key_exists($key, $array)) { - return $fallbackValue; - } - - $value = $array[$key]; - - if (!is_string($value)) { - return $fallbackValue; - } - - return $value; - } - - /** - * @param string|int $key - * @param array $array - * @param ?string $fallbackValue - * - * @return ?string - */ - public static function getNullableStringValueIfKeyExistsElse($key, array $array, ?string $fallbackValue): ?string - { - if (!array_key_exists($key, $array)) { - return $fallbackValue; - } - - $value = $array[$key]; - - if (!is_string($value)) { - return $fallbackValue; - } - - return $value; - } - - /** - * @param string|int $key - * @param array $array - * @param int $fallbackValue - * - * @return int - */ - public static function getIntValueIfKeyExistsElse($key, array $array, int $fallbackValue): int - { - if (!array_key_exists($key, $array)) { - return $fallbackValue; - } - - $value = $array[$key]; - - if (!is_int($value)) { - return $fallbackValue; - } - - return $value; - } - - /** - * @param string|int $key - * @param array $array - * @param ?int $fallbackValue - * - * @return ?int - */ - public static function getNullableIntValueIfKeyExistsElse($key, array $array, ?int $fallbackValue): ?int - { - if (!array_key_exists($key, $array)) { - return $fallbackValue; - } - - $value = $array[$key]; - - if (!is_int($value)) { - return $fallbackValue; - } - - return $value; - } - - /** - * @template TKey of array-key - * @template TValue - * - * @param TKey $key - * @param TValue $defaultValue - * @param array $array - * - * @return TValue - */ - public static function &getOrAdd($key, $defaultValue, array &$array) - { - if (!array_key_exists($key, $array)) { - $array[$key] = $defaultValue; - } - - return $array[$key]; - } - - /** - * @param array $array - * - * @return bool - */ - public static function isEmpty(array $array): bool - { - return count($array) === 0; - } - - /** - * @param array $array - * - * @return bool - */ - public static function isList(array $array): bool - { - $expectedKey = 0; - foreach ($array as $key => $_) { - if ($key !== $expectedKey) { - return false; - } - ++$expectedKey; - } - return true; - } - - /** - * @param array $srcArray - * @param string $key - * @param array $dstArray - */ - public static function copyByArrayKeyIfExists(array $srcArray, string $key, array &$dstArray): void - { - if (array_key_exists($key, $srcArray)) { - $dstArray[$key] = $srcArray[$key]; - } - } - - /** - * @param string $key - * @param array $array - */ - public static function removeKeyIfExists(string $key, array &$array): void - { - if (array_key_exists($key, $array)) { - unset($array[$key]); - } - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Util/Assert.php b/prod/php/ElasticOTel/Util/Assert.php deleted file mode 100644 index e9fd207..0000000 --- a/prod/php/ElasticOTel/Util/Assert.php +++ /dev/null @@ -1,52 +0,0 @@ -= $statementLevel) ? new EnabledAssertProxy() : null; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Util/AssertException.php b/prod/php/ElasticOTel/Util/AssertException.php deleted file mode 100644 index a5af1c6..0000000 --- a/prod/php/ElasticOTel/Util/AssertException.php +++ /dev/null @@ -1,37 +0,0 @@ -file = LoggableStackTrace::adaptSourceCodeFilePath($file); - $this->line = $line; - $this->class = $class; - $this->function = $function; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Util/ClassNameUtil.php b/prod/php/ElasticOTel/Util/ClassNameUtil.php deleted file mode 100644 index 9d84809..0000000 --- a/prod/php/ElasticOTel/Util/ClassNameUtil.php +++ /dev/null @@ -1,76 +0,0 @@ -file = $file; - $this->line = $line; - $this->class = $class; - $this->function = $function; - $this->isStaticMethod = $isStaticMethod; - $this->thisObj = $thisObj; - $this->args = $args; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Util/DbgUtil.php b/prod/php/ElasticOTel/Util/DbgUtil.php deleted file mode 100644 index f1a9744..0000000 --- a/prod/php/ElasticOTel/Util/DbgUtil.php +++ /dev/null @@ -1,68 +0,0 @@ -captureInClassicFormat(/* offset */ $numberOfStackFramesToSkip + 1, /* maxNumberOfFrames */ 1); - - if (ArrayUtil::isEmpty($stackFrames)) { - return new CallerInfo(null, null, null, null); - } - - $stackFrame = $stackFrames[0]; - return new CallerInfo($stackFrame->file, $stackFrame->line, $stackFrame->class, $stackFrame->function); - } - - /** - * @param mixed $value - * - * @return string - */ - public static function getType($value): string - { - if (is_object($value)) { - return get_class($value); - } - return gettype($value); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Util/ElasticOTelExtensionUtil.php b/prod/php/ElasticOTel/Util/ElasticOTelExtensionUtil.php deleted file mode 100644 index a8b017f..0000000 --- a/prod/php/ElasticOTel/Util/ElasticOTelExtensionUtil.php +++ /dev/null @@ -1,48 +0,0 @@ -info() is invoked and throws AssertException - // - // ($assertProxy = Assert::ifEnabled()) - // && $assertProxy->that($condition) - // && $assertProxy->info(...); - - return !$condition; - } - - /** - * @param string $conditionAsString - * @param array $context - * - * @return bool - * @throws AssertException - */ - public function withContext(string $conditionAsString, array $context): bool - { - $callerInfo = DbgUtil::getCallerInfoFromStacktrace(/* numberOfStackFramesToSkip: */ 1); - throw new AssertException(ExceptionUtil::buildMessage('Assertion failed', ['condition' => $conditionAsString, 'location' => $callerInfo] + $context)); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Util/ExceptionUtil.php b/prod/php/ElasticOTel/Util/ExceptionUtil.php deleted file mode 100644 index a29afdd..0000000 --- a/prod/php/ElasticOTel/Util/ExceptionUtil.php +++ /dev/null @@ -1,60 +0,0 @@ - $context - * @param ?int $numberOfStackFramesToSkip PHP_INT_MAX means no stack trace - * - * @return string - * - * @phpstan-param null|0|positive-int $numberOfStackFramesToSkip - * @noinspection PhpVarTagWithoutVariableNameInspection - */ - public static function buildMessage(string $messagePrefix, array $context = [], ?int $numberOfStackFramesToSkip = null): string - { - $messageSuffixObj = new AdhocLoggableObject($context); - if ($numberOfStackFramesToSkip !== null) { - $stacktrace = LoggableStackTrace::buildForCurrent($numberOfStackFramesToSkip + 1); - $messageSuffixObj->addProperties([LoggableStackTrace::STACK_TRACE_KEY => $stacktrace], PropertyLogPriority::MUST_BE_INCLUDED); - } - $messageSuffix = LoggableToString::convert($messageSuffixObj, /* prettyPrint */ true); - return $messagePrefix . (TextUtil::isEmptyString($messageSuffix) ? '' : ('. ' . $messageSuffix)); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Util/IdGenerator.php b/prod/php/ElasticOTel/Util/IdGenerator.php deleted file mode 100644 index 5d136f6..0000000 --- a/prod/php/ElasticOTel/Util/IdGenerator.php +++ /dev/null @@ -1,70 +0,0 @@ - $binaryId - * - * @return string - */ - private static function convertBinaryIdToString(array $binaryId): string - { - $result = ''; - for ($i = 0; $i < count($binaryId); ++$i) { - $result .= sprintf('%02x', $binaryId[$i]); - } - return $result; - } - - /** - * @param int $idLengthInBytes - * - * @return array - */ - private static function generateBinaryId(int $idLengthInBytes): array - { - $result = []; - for ($i = 0; $i < $idLengthInBytes; ++$i) { - $result[] = mt_rand(0, 255); - } - return $result; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Util/IdValidationUtil.php b/prod/php/ElasticOTel/Util/IdValidationUtil.php deleted file mode 100644 index 2c8008b..0000000 --- a/prod/php/ElasticOTel/Util/IdValidationUtil.php +++ /dev/null @@ -1,49 +0,0 @@ - $tail - * - * @return iterable - */ - public static function prepend($headVal, iterable $tail): iterable - { - yield $headVal; - yield from $tail; - } - - /** - * @template TValue - * - * @param TValue[] $inArray - * @param int $suffixStartIndex - * - * @return iterable - */ - public static function arraySuffix(array $inArray, int $suffixStartIndex): iterable - { - foreach (RangeUtil::generateFromToIncluding($suffixStartIndex, count($inArray) - 1) as $index) { - yield $inArray[$index]; - } - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Util/JsonException.php b/prod/php/ElasticOTel/Util/JsonException.php deleted file mode 100644 index 0a80ac5..0000000 --- a/prod/php/ElasticOTel/Util/JsonException.php +++ /dev/null @@ -1,35 +0,0 @@ -toLogAs([LogConsts::TYPE_KEY => ClassNameUtil::fqToShort(get_class($this))]); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Util/NumericUtil.php b/prod/php/ElasticOTel/Util/NumericUtil.php deleted file mode 100644 index 64da7e2..0000000 --- a/prod/php/ElasticOTel/Util/NumericUtil.php +++ /dev/null @@ -1,100 +0,0 @@ - */ - private $callbacks = []; - - public function add(Closure $callback): void - { - $this->callbacks[spl_object_id($callback)] = $callback; - } - - public function remove(Closure $callback): void - { - unset($this->callbacks[spl_object_id($callback)]); - } - - /** - * @param TArg $arg - * - * @return void - */ - public function callCallbacks($arg): void - { - foreach ($this->callbacks as $callback) { - $callback($arg); - } - } - - /** @inheritDoc */ - public function toLog(LogStreamInterface $stream): void - { - $stream->toLogAs(['callbacks count' => count($this->callbacks)]); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Util/PhpErrorUtil.php b/prod/php/ElasticOTel/Util/PhpErrorUtil.php deleted file mode 100644 index 7644ec4..0000000 --- a/prod/php/ElasticOTel/Util/PhpErrorUtil.php +++ /dev/null @@ -1,72 +0,0 @@ - - */ - public static function generate(int $begin, int $end, int $step = 1): iterable - { - for ($i = $begin; $i < $end; $i += $step) { - yield $i; - } - } - - /** - * @param int $begin - * @param int $end - * @param int $step - * - * @return iterable - */ - public static function generateDown(int $begin, int $end, int $step = 1): iterable - { - for ($i = $begin; $i > $end; $i -= $step) { - yield $i; - } - } - - /** - * @param int $count - * - * @return iterable - */ - public static function generateUpTo(int $count): iterable - { - return self::generate(0, $count); - } - - /** - * @param int $count - * - * @return iterable - */ - public static function generateDownFrom(int $count): iterable - { - for ($i = $count - 1; $i >= 0; --$i) { - yield $i; - } - } - - /** - * @param int $first - * @param int $last - * - * @return iterable - */ - public static function generateFromToIncluding(int $first, int $last): iterable - { - return self::generate($first, $last + 1); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Util/StackTraceUtil.php b/prod/php/ElasticOTel/Util/StackTraceUtil.php deleted file mode 100644 index 678c92c..0000000 --- a/prod/php/ElasticOTel/Util/StackTraceUtil.php +++ /dev/null @@ -1,578 +0,0 @@ -'; - public const CLASS_AND_METHOD_SEPARATOR = '::'; - public const THIS_OBJECT_KEY = 'object'; - public const ARGS_KEY = 'args'; - - public const FILE_NAME_NOT_AVAILABLE_SUBSTITUTE = 'FILE NAME N/A'; - public const LINE_NUMBER_NOT_AVAILABLE_SUBSTITUTE = 0; - - private const ELASTIC_OTEL_FQ_NAME_PREFIX = 'ElasticOTel\\'; - private const ELASTIC_OTEL_INTERNAL_FUNCTION_NAME_PREFIX = 'elastic_otel_'; - - - /** @var LoggerFactory */ - private $loggerFactory; - - /** @var Logger */ - private $logger; - - /** @var string */ - private $namePrefixForFramesToHide; - - /** @var string */ - private $namePrefixForInternalFramesToHide; - - public function __construct( - LoggerFactory $loggerFactory, - string $namePrefixForFramesToHide = self::ELASTIC_OTEL_FQ_NAME_PREFIX, - string $namePrefixForInternalFramesToHide = self::ELASTIC_OTEL_INTERNAL_FUNCTION_NAME_PREFIX - ) { - $this->loggerFactory = $loggerFactory; - $this->logger = $this->loggerFactory->loggerForClass(LogCategory::INFRASTRUCTURE, __NAMESPACE__, __CLASS__, __FILE__); - $this->namePrefixForFramesToHide = $namePrefixForFramesToHide; - $this->namePrefixForInternalFramesToHide = $namePrefixForInternalFramesToHide; - } - - /** - * @param int $offset - * @param ?positive-int $maxNumberOfFrames - * - * @return StackTraceFrame[] - * - * @phpstan-param 0|positive-int $offset - */ - public function captureInApmFormat(int $offset, ?int $maxNumberOfFrames): array - { - $phpFormatFrames = debug_backtrace(/* options */ DEBUG_BACKTRACE_IGNORE_ARGS, /* limit */ $maxNumberOfFrames === null ? 0 : ($offset + $maxNumberOfFrames)); - return $this->convertPhpToApmFormat(IterableUtil::arraySuffix($phpFormatFrames, $offset), $maxNumberOfFrames); - } - - /** - * @param iterable> $phpFormatFrames - * @param ?positive-int $maxNumberOfFrames - * - * @return StackTraceFrame[] - */ - public function convertPhpToApmFormat(iterable $phpFormatFrames, ?int $maxNumberOfFrames): array - { - $allClassicFormatFrames = $this->convertPhpToClassicFormat( - null /* <- prevPhpFormatFrame */, - $phpFormatFrames, - $maxNumberOfFrames, - false /* keepElasticApmFrames */, - false /* $includeArgs */, - false /* $includeThisObj */ - ); - - return self::convertClassicToApmFormat($allClassicFormatFrames, $maxNumberOfFrames); - } - - /** - * @param int $offset - * @param ?positive-int $maxNumberOfFrames - * - * @return ClassicFormatStackTraceFrame[] - * - * @phpstan-param 0|positive-int $offset - */ - public function captureInClassicFormatExcludeElasticApm(int $offset = 0, ?int $maxNumberOfFrames = null): array - { - return $this->captureInClassicFormat($offset + 1, $maxNumberOfFrames, /* keepElasticApmFrames */ false); - } - - /** - * @param int $offset - * @param ?positive-int $maxNumberOfFrames - * @param bool $keepElasticApmFrames - * @param bool $includeArgs - * @param bool $includeThisObj - * - * @return ClassicFormatStackTraceFrame[] - * - * @phpstan-param 0|positive-int $offset - */ - public function captureInClassicFormat(int $offset = 0, ?int $maxNumberOfFrames = null, bool $keepElasticApmFrames = true, bool $includeArgs = false, bool $includeThisObj = false): array - { - $options = ($includeArgs ? 0 : DEBUG_BACKTRACE_IGNORE_ARGS) | ($includeThisObj ? DEBUG_BACKTRACE_PROVIDE_OBJECT : 0); - return $this->convertCaptureToClassicFormat( - // If there is non-null $maxNumberOfFrames we need to capture one more frame in PHP format - debug_backtrace($options, /* limit */ $maxNumberOfFrames === null ? 0 : ($offset + $maxNumberOfFrames + 1)), - // $offset + 1 to exclude the frame for the current method (captureInClassicFormat) call - $offset + 1, - $maxNumberOfFrames, - $keepElasticApmFrames, - $includeArgs, - $includeThisObj - ); - } - - /** - * @param array> $phpFormatFrames - * @param int $offset - * @param ?positive-int $maxNumberOfFrames - * @param bool $keepElasticApmFrames - * @param bool $includeArgs - * @param bool $includeThisObj - * - * @return ClassicFormatStackTraceFrame[] - * - * @phpstan-param 0|positive-int $offset - */ - public function convertCaptureToClassicFormat(array $phpFormatFrames, int $offset, ?int $maxNumberOfFrames, bool $keepElasticApmFrames, bool $includeArgs, bool $includeThisObj): array - { - if ($offset >= count($phpFormatFrames)) { - return []; - } - - return $this->convertPhpToClassicFormat( - $offset === 0 ? null : $phpFormatFrames[$offset - 1] /* <- prevPhpFormatFrame */, - $offset === 0 ? $phpFormatFrames : IterableUtil::arraySuffix($phpFormatFrames, $offset), - $maxNumberOfFrames, - $keepElasticApmFrames, - $includeArgs, - $includeThisObj - ); - } - - /** - * @param ?array $prevPhpFormatFrame - * @param iterable> $phpFormatFrames - * @param ?positive-int $maxNumberOfFrames - * @param bool $keepElasticApmFrames - * @param bool $includeArgs - * @param bool $includeThisObj - * - * @return ClassicFormatStackTraceFrame[] - */ - public function convertPhpToClassicFormat( - ?array $prevPhpFormatFrame, - iterable $phpFormatFrames, - ?int $maxNumberOfFrames, - bool $keepElasticApmFrames, - bool $includeArgs, - bool $includeThisObj - ): array { - $allClassicFormatFrames = []; - $prevInFrame = $prevPhpFormatFrame; - foreach ($phpFormatFrames as $currentInFrame) { - $outFrame = new ClassicFormatStackTraceFrame(); - $isOutFrameEmpty = true; - if ($prevInFrame !== null && $this->hasLocationPropertiesInPhpFormat($prevInFrame)) { - $this->copyLocationPropertiesFromPhpToClassicFormat($prevInFrame, $outFrame); - $isOutFrameEmpty = false; - } - if ($this->hasNonLocationPropertiesInPhpFormat($currentInFrame)) { - $this->copyNonLocationPropertiesFromPhpToClassicFormat($currentInFrame, $includeArgs, $includeThisObj, $outFrame); - $isOutFrameEmpty = false; - } - if (!$isOutFrameEmpty) { - $allClassicFormatFrames[] = $outFrame; - } - $prevInFrame = $currentInFrame; - } - - if ($prevInFrame !== null && $this->hasLocationPropertiesInPhpFormat($prevInFrame)) { - $outFrame = new ClassicFormatStackTraceFrame(); - $this->copyLocationPropertiesFromPhpToClassicFormat($prevInFrame, $outFrame); - $allClassicFormatFrames[] = $outFrame; - } - - return $keepElasticApmFrames - ? ($maxNumberOfFrames === null ? $allClassicFormatFrames : array_slice($allClassicFormatFrames, /* offset */ 0, $maxNumberOfFrames)) - : $this->excludeCodeToHide($allClassicFormatFrames, $maxNumberOfFrames); - } - - - /** - * @param ClassicFormatStackTraceFrame[] $inFrames - * @param ?positive-int $maxNumberOfFrames - * - * @return ClassicFormatStackTraceFrame[] - */ - private function excludeCodeToHide(array $inFrames, ?int $maxNumberOfFrames): array - { - $outFrames = []; - /** @var ?int $bufferedFromIndex */ - $bufferedFromIndex = null; - foreach (RangeUtil::generateUpTo(count($inFrames)) as $currentInFrameIndex) { - $currentInFrame = $inFrames[$currentInFrameIndex]; - if (self::isTrampolineCall($currentInFrame)) { - if ($bufferedFromIndex === null) { - $bufferedFromIndex = $currentInFrameIndex; - } - continue; - } - - if ($this->isCallToCodeToHide($currentInFrame)) { - $bufferedFromIndex = null; - continue; - } - - for ($index = $bufferedFromIndex ?? $currentInFrameIndex; $index <= $currentInFrameIndex; ++$index) { - self::addToOutputFrames($inFrames[$index], $maxNumberOfFrames, /* ref */ $outFrames); - } - $bufferedFromIndex = null; - } - - return $outFrames; - } - - public static function buildApmFormatFunctionForClassMethod(?string $classicName, ?bool $isStaticMethod, ?string $methodName): ?string - { - if ($methodName === null) { - return null; - } - - if ($classicName === null) { - return $methodName; - } - - return $classicName . StackTraceUtil::CLASS_AND_METHOD_SEPARATOR . $methodName; - } - - private static function isTrampolineCall(ClassicFormatStackTraceFrame $frame): bool - { - return $frame->class === null && $frame->isStaticMethod === null && ($frame->function === 'call_user_func' || $frame->function === 'call_user_func_array'); - } - - private function isCallToCodeToHide(ClassicFormatStackTraceFrame $frame): bool - { - return ($frame->class !== null && TextUtil::isPrefixOf($this->namePrefixForFramesToHide, $frame->class)) - || ($frame->function !== null && TextUtil::isPrefixOf($this->namePrefixForFramesToHide, $frame->function)) - || ($frame->function !== null && $frame->file === null && TextUtil::isPrefixOf($this->namePrefixForInternalFramesToHide, $frame->function)); - } - - /** - * @param array $frame - * - * @return ?bool - */ - private function isStaticMethodInPhpFormat(array $frame): ?bool - { - if (($funcType = self::getNullableStringValue(StackTraceUtil::TYPE_KEY, $frame)) === null) { - return null; - } - - switch ($funcType) { - case StackTraceUtil::FUNCTION_IS_STATIC_METHOD_TYPE_VALUE: - return true; - case StackTraceUtil::FUNCTION_IS_METHOD_TYPE_VALUE: - return false; - default: - ($loggerProxy = $this->logger->ifErrorLevelEnabled(__LINE__, __FUNCTION__)) - && $loggerProxy->log('Unexpected `' . StackTraceUtil::TYPE_KEY . '\' value', ['type' => $funcType]); - return null; - } - } - - /** - * @param string $key - * @param array $phpFormatFormatFrame - * - * @return ?string - */ - private function getNullableStringValue(string $key, array $phpFormatFormatFrame): ?string - { - /** @var ?string $value */ - $value = $this->getNullableValue($key, 'is_string', 'string', $phpFormatFormatFrame); - return $value; - } - - /** - * @param string $key - * @param array $phpFormatFormatFrame - * - * @return ?int - * - * @noinspection PhpSameParameterValueInspection - */ - private function getNullableIntValue(string $key, array $phpFormatFormatFrame): ?int - { - /** @var ?int $value */ - $value = $this->getNullableValue($key, 'is_int', 'int', $phpFormatFormatFrame); - return $value; - } - - /** - * @param string $key - * @param array $phpFormatFormatFrame - * - * @return ?object - * - * @noinspection PhpSameParameterValueInspection - */ - private function getNullableObjectValue(string $key, array $phpFormatFormatFrame): ?object - { - /** @var ?object $value */ - $value = $this->getNullableValue($key, 'is_object', 'object', $phpFormatFormatFrame); - return $value; - } - - /** - * @param string $key - * @param array $phpFormatFormatFrame - * - * @return null|mixed[] - * - * @noinspection PhpSameParameterValueInspection - */ - private function getNullableArrayValue(string $key, array $phpFormatFormatFrame): ?array - { - /** @var ?array $value */ - $value = $this->getNullableValue($key, 'is_array', 'array', $phpFormatFormatFrame); - return $value; - } - - /** - * @param string $key - * @param callable(mixed): bool $isValueTypeFunc - * @param string $dbgExpectedType - * @param array $phpFormatFormatFrame - * - * @return mixed - */ - private function getNullableValue(string $key, callable $isValueTypeFunc, string $dbgExpectedType, array $phpFormatFormatFrame) - { - if (!array_key_exists($key, $phpFormatFormatFrame)) { - return null; - } - - $value = $phpFormatFormatFrame[$key]; - if ($value === null) { - return null; - } - - if (!$isValueTypeFunc($value)) { - ($loggerProxy = $this->logger->ifErrorLevelEnabled(__LINE__, __FUNCTION__)) - && $loggerProxy->log( - 'Unexpected type for value under key (expected ' . $dbgExpectedType . ')', - ['$key' => $key, 'value type' => DbgUtil::getType($value), 'value' => $value] - ); - return null; - } - - return $value; - } - - /** - * @param array $frame - */ - private function hasNonLocationPropertiesInPhpFormat(array $frame): bool - { - return $this->getNullableStringValue(StackTraceUtil::FUNCTION_KEY, $frame) !== null; - } - - /** - * @param array $frame - */ - private function hasLocationPropertiesInPhpFormat(array $frame): bool - { - return $this->getNullableStringValue(StackTraceUtil::FILE_KEY, $frame) !== null; - } - - private static function hasLocationPropertiesInClassicFormat(ClassicFormatStackTraceFrame $frame): bool - { - return $frame->file !== null; - } - - /** - * @param array $srcFrame - * @param ClassicFormatStackTraceFrame $dstFrame - */ - private function copyLocationPropertiesFromPhpToClassicFormat(array $srcFrame, ClassicFormatStackTraceFrame $dstFrame): void - { - $dstFrame->file = $this->getNullableStringValue(StackTraceUtil::FILE_KEY, $srcFrame); - $dstFrame->line = $this->getNullableIntValue(StackTraceUtil::LINE_KEY, $srcFrame); - } - - /** - * @param array $srcFrame - * @param bool $includeArgs - * @param bool $includeThisObj - * @param ClassicFormatStackTraceFrame $dstFrame - */ - private function copyNonLocationPropertiesFromPhpToClassicFormat(array $srcFrame, bool $includeArgs, bool $includeThisObj, ClassicFormatStackTraceFrame $dstFrame): void - { - $dstFrame->class = $this->getNullableStringValue(StackTraceUtil::CLASS_KEY, $srcFrame); - $dstFrame->function = $this->getNullableStringValue(StackTraceUtil::FUNCTION_KEY, $srcFrame); - $dstFrame->isStaticMethod = $this->isStaticMethodInPhpFormat($srcFrame); - if ($includeThisObj) { - $dstFrame->thisObj = $this->getNullableObjectValue(StackTraceUtil::THIS_OBJECT_KEY, $srcFrame); - } - if ($includeArgs) { - $dstFrame->args = $this->getNullableArrayValue(StackTraceUtil::ARGS_KEY, $srcFrame); - } - } - - /** - * @template TOutputFrame - * - * @param TOutputFrame $frameToAdd - * @param ?int $maxNumberOfFrames - * @param TOutputFrame[] &$outputFrames - * - * @return bool - * - * @phpstan-param null|positive-int $maxNumberOfFrames - */ - private static function addToOutputFrames($frameToAdd, ?int $maxNumberOfFrames, /* ref */ array &$outputFrames): bool - { - $outputFrames[] = $frameToAdd; - return (count($outputFrames) !== $maxNumberOfFrames); - } - - /** - * @param Throwable $throwable - * @param ?positive-int $maxNumberOfFrames - * - * @return StackTraceFrame[] - */ - public function convertThrowableTraceToApmFormat(Throwable $throwable, ?int $maxNumberOfFrames): array - { - $frameForThrowLocation = [StackTraceUtil::FILE_KEY => $throwable->getFile(), StackTraceUtil::LINE_KEY => $throwable->getLine()]; - return $this->convertPhpToApmFormat(IterableUtil::prepend($frameForThrowLocation, $throwable->getTrace()), $maxNumberOfFrames); - } - - // TODO: Sergey Kleyman: REMOVE: - // /** - // * @param iterable $inFrames - // * @param ?positive-int $maxNumberOfFrames - // * - // * @return StackTraceFrame[] - // */ - // private static function convertClassicToApmFormat(iterable $inFrames, ?int $maxNumberOfFrames): array - // { - // /** @var StackTraceFrame[] $outFrames */ - // $outFrames = []; - // - // /** @var ?ClassicFormatStackTraceFrame $prevInFrame */ - // $prevInFrame = null; - // foreach ($inFrames as $currentInFrame) { - // if ($currentInFrame->file === null) { - // $isOutFrameEmpty = true; - // $outFrame = new StackTraceFrame(self::FILE_NAME_NOT_AVAILABLE_SUBSTITUTE, self::LINE_NUMBER_NOT_AVAILABLE_SUBSTITUTE); - // } else { - // $isOutFrameEmpty = false; - // $outFrame = new StackTraceFrame($currentInFrame->file, $currentInFrame->line ?? self::LINE_NUMBER_NOT_AVAILABLE_SUBSTITUTE); - // } - // if ($prevInFrame !== null && $prevInFrame->function !== null) { - // $isOutFrameEmpty = false; - // $outFrame->function = self::buildApmFormatFunctionForClassMethod($prevInFrame->class, $prevInFrame->isStaticMethod, $prevInFrame->function); - // } - // if (!$isOutFrameEmpty && !self::addToOutputFrames($outFrame, $maxNumberOfFrames, /* ref */ $outFrames)) { - // break; - // } - // $prevInFrame = $currentInFrame; - // } - // - // return $outFrames; - // } - - /** - * @param iterable $inputFrames - * @param ?positive-int $maxNumberOfFrames - * - * @return StackTraceFrame[] - */ - public static function convertClassicToApmFormat(iterable $inputFrames, ?int $maxNumberOfFrames): array - { - $outputFrames = []; - /** @var ?ClassicFormatStackTraceFrame $prevInputFrame */ - $prevInputFrame = null; - $exitedEarly = false; - foreach ($inputFrames as $currentInputFrame) { - if ($prevInputFrame === null) { - if (self::hasLocationPropertiesInClassicFormat($currentInputFrame)) { - $outputFrame = new StackTraceFrame($currentInputFrame->file ?? self::FILE_NAME_NOT_AVAILABLE_SUBSTITUTE, $currentInputFrame->line ?? self::LINE_NUMBER_NOT_AVAILABLE_SUBSTITUTE); - if (!self::addToOutputFrames($outputFrame, $maxNumberOfFrames, /* ref */ $outputFrames)) { - $exitedEarly = true; - break; - } - } - $prevInputFrame = $currentInputFrame; - continue; - } - - $outputFrame = new StackTraceFrame($currentInputFrame->file ?? self::FILE_NAME_NOT_AVAILABLE_SUBSTITUTE, $currentInputFrame->line ?? self::LINE_NUMBER_NOT_AVAILABLE_SUBSTITUTE); - $outputFrame->function = StackTraceUtil::buildApmFormatFunctionForClassMethod($prevInputFrame->class, $prevInputFrame->isStaticMethod, $prevInputFrame->function); - if (!self::addToOutputFrames($outputFrame, $maxNumberOfFrames, /* ref */ $outputFrames)) { - $exitedEarly = true; - break; - } - - $prevInputFrame = $currentInputFrame; - } - - if (!$exitedEarly && $prevInputFrame !== null && $prevInputFrame->function !== null) { - $outputFrame = new StackTraceFrame( - self::FILE_NAME_NOT_AVAILABLE_SUBSTITUTE, - self::LINE_NUMBER_NOT_AVAILABLE_SUBSTITUTE, - StackTraceUtil::buildApmFormatFunctionForClassMethod($prevInputFrame->class, $prevInputFrame->isStaticMethod, $prevInputFrame->function) - ); - self::addToOutputFrames($outputFrame, $maxNumberOfFrames, /* ref */ $outputFrames); - } - - return $outputFrames; - } - - /** - * @param int $stackTraceLimit - * - * @return ?int - * @phpstan-return null|0|positive-int - */ - public static function convertLimitConfigToMaxNumberOfFrames(int $stackTraceLimit): ?int - { - /** - * stack_trace_limit - * 0 - stack trace collection should be disabled - * any positive value - the value is the maximum number of frames to collect - * any negative value - all frames should be collected - */ - return $stackTraceLimit < 0 ? null : $stackTraceLimit; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Util/TextUtil.php b/prod/php/ElasticOTel/Util/TextUtil.php deleted file mode 100644 index 72946b4..0000000 --- a/prod/php/ElasticOTel/Util/TextUtil.php +++ /dev/null @@ -1,224 +0,0 @@ -= $beginTime) ? ($endTime - $beginTime) : 0; - } - - /** - * @param float $beginTime Begin time in microseconds - * @param float $endTime End time in microseconds - * - * @return float Duration in milliseconds - * - * @see ClockInterface::getMonotonicClockCurrentTime() For the description - */ - public static function calcDurationInMillisecondsClampNegativeToZero(float $beginTime, float $endTime): float - { - return self::microsecondsToMilliseconds( - self::calcDurationInMicrosecondsClampNegativeToZero($beginTime, $endTime) - ); - } - - public static function microsecondsToMilliseconds(float $microseconds): float - { - return $microseconds / self::NUMBER_OF_MICROSECONDS_IN_MILLISECOND; - } - - public static function millisecondsToMicroseconds(float $milliseconds): float - { - return $milliseconds * self::NUMBER_OF_MICROSECONDS_IN_MILLISECOND; - } - - public static function nanosecondsToMicroseconds(float $nanoseconds): float - { - return $nanoseconds / self::NUMBER_OF_NANOSECONDS_IN_MICROSECOND; - } - - public static function secondsToMicroseconds(float $seconds): float - { - return $seconds * self::NUMBER_OF_MICROSECONDS_IN_SECOND; - } - - public static function microsecondsToSeconds(float $microseconds): float - { - return $microseconds / self::NUMBER_OF_MICROSECONDS_IN_SECOND; - } - - private static function calcWholeTimesAndRemainderForFloat( - float $largeVal, - int $smallVal, - float &$wholeTimes, - float &$remainder - ): void { - $wholeTimes = floor($largeVal / $smallVal); - $remainder = $largeVal - ($smallVal * $wholeTimes); - } - - public static function formatDurationInMicroseconds(float $durationInMicroseconds): string - { - if ($durationInMicroseconds === 0.0) { - return '0us'; - } - - $isNegative = ($durationInMicroseconds < 0); - $microsecondsTotalFloat = abs($durationInMicroseconds); - $microsecondsTotalWhole = floor($microsecondsTotalFloat); - $microsecondsFraction = $microsecondsTotalFloat - $microsecondsTotalWhole; - - $millisecondsTotalWhole = 0.0; - $microsecondsRemainder = 0.0; - self::calcWholeTimesAndRemainderForFloat( - $microsecondsTotalWhole, - TimeUtil::NUMBER_OF_MICROSECONDS_IN_MILLISECOND, - /* ref */ $millisecondsTotalWhole, - /* ref */ $microsecondsRemainder - ); - - $secondsTotalWhole = 0.0; - $millisecondsRemainder = 0.0; - self::calcWholeTimesAndRemainderForFloat( - $millisecondsTotalWhole, - TimeUtil::NUMBER_OF_MILLISECONDS_IN_SECOND, - /* ref */ $secondsTotalWhole, - /* ref */ $millisecondsRemainder - ); - - $minutesTotalWhole = 0.0; - $secondsRemainder = 0.0; - self::calcWholeTimesAndRemainderForFloat( - $secondsTotalWhole, - TimeUtil::NUMBER_OF_SECONDS_IN_MINUTE, - /* ref */ $minutesTotalWhole, - /* ref */ $secondsRemainder - ); - - $hoursTotalWhole = 0.0; - $minutesRemainder = 0.0; - self::calcWholeTimesAndRemainderForFloat( - $minutesTotalWhole, - TimeUtil::NUMBER_OF_MINUTES_IN_HOUR, - /* ref */ $hoursTotalWhole, - /* ref */ $minutesRemainder - ); - - $hoursRemainder = 0.0; - $daysTotalWhole = 0.0; - self::calcWholeTimesAndRemainderForFloat( - $hoursTotalWhole, - TimeUtil::NUMBER_OF_HOURS_IN_DAY, - /* ref */ $daysTotalWhole, - /* ref */ $hoursRemainder - ); - - $appendRemainder = function (string $appendTo, float $remainder, string $units): string { - if ($remainder === 0.0) { - return $appendTo; - } - - $remainderAsString = ($remainder === floor($remainder)) ? strval(intval($remainder)) : strval($remainder); - return $appendTo . (TextUtil::isEmptyString($appendTo) ? '' : ' ') . $remainderAsString . $units; - }; - - $result = ''; - $result = $appendRemainder($result, $daysTotalWhole, 'd'); - $result = $appendRemainder($result, $hoursRemainder, 'h'); - $result = $appendRemainder($result, $minutesRemainder, 'm'); - $result = $appendRemainder($result, $secondsRemainder, 's'); - $result = $appendRemainder($result, $millisecondsRemainder, 'ms'); - $result = $appendRemainder($result, $microsecondsRemainder + $microsecondsFraction, 'us'); - - return ($isNegative ? '-' : '') . $result; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Util/UrlParts.php b/prod/php/ElasticOTel/Util/UrlParts.php deleted file mode 100644 index c1fdef9..0000000 --- a/prod/php/ElasticOTel/Util/UrlParts.php +++ /dev/null @@ -1,91 +0,0 @@ -scheme = $scheme; - return $this; - } - - public function host(?string $host): self - { - $this->host = $host; - return $this; - } - - public function port(?int $port): self - { - $this->port = $port; - return $this; - } - - public function path(?string $path): self - { - $this->path = $path; - return $this; - } - - public function query(?string $query): self - { - $this->query = $query; - return $this; - } - - public function __toString(): string - { - return '{' - . 'path: ' . $this->path - . ', ' - . 'query: ' . $this->query - . '}'; - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Util/UrlUtil.php b/prod/php/ElasticOTel/Util/UrlUtil.php deleted file mode 100644 index 92cc251..0000000 --- a/prod/php/ElasticOTel/Util/UrlUtil.php +++ /dev/null @@ -1,168 +0,0 @@ -scheme ?? 'http') . '://'; - $result .= $urlParts->host ?? 'localhost'; - if ($urlParts->port !== null) { - $result .= ':' . $urlParts->port; - } - return $result; - } - - public static function normalizeUrlPath(string $urlPath): string - { - return TextUtil::isPrefixOf('/', $urlPath) ? $urlPath : ('/' . $urlPath); - } - - public static function buildRequestMethodArg(UrlParts $urlParts): string - { - $result = $urlParts->path === null - ? '/' - : self::normalizeUrlPath($urlParts->path); - - if ($urlParts->query !== null) { - $result .= '?' . $urlParts->query; - } - - return $result; - } - - public static function buildFullUrl(UrlParts $urlParts): string - { - return self::buildRequestBaseUrl($urlParts) . self::buildRequestMethodArg($urlParts); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Util/WildcardListMatcher.php b/prod/php/ElasticOTel/Util/WildcardListMatcher.php deleted file mode 100644 index 5f1dbb3..0000000 --- a/prod/php/ElasticOTel/Util/WildcardListMatcher.php +++ /dev/null @@ -1,70 +0,0 @@ - $wildcardExprs - */ - public function __construct(iterable $wildcardExprs) - { - $this->matchers = []; - foreach ($wildcardExprs as $wildcardExpr) { - $this->matchers[] = new WildcardMatcher($wildcardExpr); - } - } - - public function match(string $text): ?string - { - foreach ($this->matchers as $matcher) { - if ($matcher->match($text)) { - return $matcher->groupName(); - } - } - return null; - } - - public static function matchNullable(?WildcardListMatcher $nullableMatcher, string $text): ?string - { - if ($nullableMatcher === null) { - return null; - } - - return $nullableMatcher->match($text); - } - - public function __toString(): string - { - return implode(', ', $this->matchers); - } -} \ No newline at end of file diff --git a/prod/php/ElasticOTel/Util/WildcardMatcher.php b/prod/php/ElasticOTel/Util/WildcardMatcher.php deleted file mode 100644 index 91496a4..0000000 --- a/prod/php/ElasticOTel/Util/WildcardMatcher.php +++ /dev/null @@ -1,177 +0,0 @@ -isCaseSensitive = TextUtil::isPrefixOf(self::CASE_SENSITIVE_PREFIX, $expr); - $exprPos = $this->isCaseSensitive ? strlen(self::CASE_SENSITIVE_PREFIX) : 0; - $exprLen = strlen($expr); - $this->literalParts = []; - $this->startsWithWildcard = false; - $lastPartWasWildcard = false; - while ($exprPos < $exprLen) { - $nextWildcardPos = strpos($expr, self::WILDCARD, $exprPos); - if ($nextWildcardPos === $exprPos) { - $lastPartWasWildcard = true; - if ($this->literalParts === []) { - $this->startsWithWildcard = true; - } - $exprPos += self::$wildcardLen; - continue; - } - - $lastPartWasWildcard = false; - $literalPartEndPos = ($nextWildcardPos === false) ? $exprLen : $nextWildcardPos; - $literalPartLen = $literalPartEndPos - $exprPos; - $this->literalParts[] = substr($expr, /* offset */ $exprPos, /* length */ $literalPartLen); - $exprPos += $literalPartLen; - } - $this->endsWithWildcard = $lastPartWasWildcard; - } - - /** - * @param string $haystack - * @param string $needle - * @param int $offset - * @param bool $isCaseSensitive - * - * @return false|int - */ - private static function findSubString(string $haystack, string $needle, int $offset, bool $isCaseSensitive) - { - return $isCaseSensitive ? strpos($haystack, $needle, $offset) : stripos($haystack, $needle, $offset); - } - - private static function areStringsEqual(string $str1, string $str2, bool $isCaseSensitive): bool - { - return $isCaseSensitive ? (strcmp($str1, $str2) === 0) : (strcasecmp($str1, $str2) === 0); - } - - public function match(string $text): bool - { - if (!$this->startsWithWildcard && $this->literalParts === [] && $text !== '') { - return false; - } - - $allowAnyPrefix = $this->startsWithWildcard; - $textPos = 0; - $numberOfPartsToCheckInLoop = count($this->literalParts); - if ($numberOfPartsToCheckInLoop > 0 && !$this->endsWithWildcard) { - --$numberOfPartsToCheckInLoop; - } - for ($i = 0; $i < $numberOfPartsToCheckInLoop; ++$i) { - $currentLiteralPart = $this->literalParts[$i]; - $literalPartMatchPos = self::findSubString($text, $currentLiteralPart, $textPos, $this->isCaseSensitive); - if ($literalPartMatchPos === false) { - return false; - } - if (!$allowAnyPrefix && $literalPartMatchPos !== $textPos) { - return false; - } - $textPos += strlen($currentLiteralPart); - $allowAnyPrefix = true; - } - if ($numberOfPartsToCheckInLoop < count($this->literalParts)) { - $lastPart = $this->literalParts[count($this->literalParts) - 1]; - if (!$this->startsWithWildcard && count($this->literalParts) === 1) { - if (!self::areStringsEqual($lastPart, $text, $this->isCaseSensitive)) { - return false; - } - } else { - if (!TextUtil::isSuffixOf($lastPart, $text, $this->isCaseSensitive)) { - return false; - } - } - } - - return true; - } - - public function groupName(): string - { - $result = ''; - - if ($this->startsWithWildcard) { - $result .= self::WILDCARD; - } - - $isFirstLiteralPart = true; - foreach ($this->literalParts as $literalPart) { - if ($isFirstLiteralPart) { - $isFirstLiteralPart = false; - } else { - $result .= self::WILDCARD; - } - $result .= $literalPart; - } - - if ($this->endsWithWildcard) { - $result .= self::WILDCARD; - } - - return $result; - } - - public function __toString(): string - { - $result = $this->groupName(); - - if ($this->isCaseSensitive) { - $result = self::CASE_SENSITIVE_PREFIX . $result; - } - - return $result; - } -} \ No newline at end of file