diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml index 764e8b336..8d84acaef 100644 --- a/.github/workflows/php.yml +++ b/.github/workflows/php.yml @@ -13,7 +13,7 @@ jobs: strategy: fail-fast: false matrix: - php-version: ['7.4', '8.0', '8.1', '8.2', '8.3'] + php-version: ['8.0', '8.1', '8.2', '8.3'] experimental: [false] composer_args: [""] include: @@ -138,4 +138,5 @@ jobs: needs: php with: matrix_extension: '["ast, json, grpc"]' + matrix_php_version: '["8.0", "8.1", "8.2", "8.3"]' install_directory: '~/.test/.packages' diff --git a/.github/workflows/publish-otel-php-base-docker-image.yml b/.github/workflows/publish-otel-php-base-docker-image.yml index 154c38f47..622fa0882 100644 --- a/.github/workflows/publish-otel-php-base-docker-image.yml +++ b/.github/workflows/publish-otel-php-base-docker-image.yml @@ -8,7 +8,7 @@ jobs: name: OpenTelemetry PHP base docker image creation strategy: matrix: - php-version: ['7.4', '8.0', '8.1', '8.2', '8.3'] + php-version: ['8.0', '8.1', '8.2', '8.3'] runs-on: ubuntu-latest permissions: packages: write diff --git a/.phan/config.php b/.phan/config.php index f0e92471d..24b9eeaa5 100644 --- a/.phan/config.php +++ b/.phan/config.php @@ -44,7 +44,7 @@ // // Note that the **only** effect of choosing `'5.6'` is to infer that functions removed in php 7.0 exist. // (See `backward_compatibility_checks` for additional options) - 'target_php_version' => '7.4', + 'target_php_version' => '8.0', // If enabled, missing properties will be created when // they are first seen. If false, we'll report an diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php index b6811e3eb..7d3434de0 100644 --- a/.php-cs-fixer.php +++ b/.php-cs-fixer.php @@ -25,10 +25,10 @@ 'blank_line_before_statement' => true, 'cast_spaces' => true, 'declare_strict_types' => true, - 'function_typehint_space' => true, + 'type_declaration_spaces' => true, 'include' => true, 'lowercase_cast' => true, - 'new_with_braces' => true, + 'new_with_parentheses' => true, 'no_extra_blank_lines' => true, 'no_leading_import_slash' => true, 'no_trailing_whitespace' => true, @@ -41,9 +41,9 @@ 'phpdoc_scalar' => true, 'phpdoc_types' => true, 'short_scalar_cast' => true, - 'single_blank_line_before_namespace' => true, + 'blank_lines_before_namespace' => true, 'single_quote' => true, - 'trailing_comma_in_multiline' => true, + 'trailing_comma_in_multiline' => ['elements' => ['arrays', 'parameters', 'match']], ]) ->setRiskyAllowed(true) ->setFinder($finder); diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 5f5a1ab5e..851a5817d 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -71,8 +71,8 @@ This does the following things: ### Other PHP versions We aim to support officially supported PHP versions, according to https://www.php.net/supported-versions.php. The -developer image `ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base` is tagged as `7.4`, `8.0`, `8.1` and `8.2` -respectively, with `7.4` being the default. You can execute the test suite against other PHP versions by running the +developer image `ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base` is tagged as `8.0`, `8.1`, `8.2` and `8.3` +respectively, with `8.0` being the default. You can execute the test suite against other PHP versions by running the following command: ```bash diff --git a/Makefile b/Makefile index de3cfa1e7..5b71997bc 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ include .env -PHP_VERSION ?= 7.4 +PHP_VERSION ?= 8.0 DOCKER_COMPOSE ?= docker-compose DC_RUN_PHP = $(DOCKER_COMPOSE) run --rm php diff --git a/composer.json b/composer.json index b86c11037..7d8b14697 100644 --- a/composer.json +++ b/composer.json @@ -7,7 +7,7 @@ "readme": "./README.md", "license": "Apache-2.0", "require": { - "php": "^7.4 || ^8.0", + "php": "^8.0", "ext-json": "*", "google/protobuf": "^3.22", "php-http/discovery": "^1.14", @@ -17,7 +17,6 @@ "psr/http-message": "^1.0.1|^2.0", "psr/log": "^1.1|^2.0|^3.0", "symfony/polyfill-mbstring": "^1.23", - "symfony/polyfill-php80": "^1.26", "symfony/polyfill-php81": "^1.26", "symfony/polyfill-php82": "^1.26" }, @@ -77,9 +76,9 @@ "ext-grpc": "*", "grpc/grpc": "^1.30", "assertwell/phpunit-global-state": "^0.2.2", - "composer/xdebug-handler": "^2.0", + "composer/xdebug-handler": "^3.0", "dg/bypass-finals": "^1.4", - "friendsofphp/php-cs-fixer": "^3.4", + "friendsofphp/php-cs-fixer": "^3.51", "guzzlehttp/guzzle": "^7.4", "guzzlehttp/psr7": "^2.1", "mikey179/vfsstream": "^1.6.11", diff --git a/docker-compose.collector.yaml b/docker-compose.collector.yaml index 83d223ce8..2a5cbf698 100644 --- a/docker-compose.collector.yaml +++ b/docker-compose.collector.yaml @@ -1,7 +1,7 @@ version: '3.7' services: php: - image: ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base:${PHP_VERSION:-7.4} + image: ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base:${PHP_VERSION:-8.0} volumes: - ./:/usr/src/myapp depends_on: diff --git a/docker-compose.prometheus.yaml b/docker-compose.prometheus.yaml index 6069aab56..ffb77174c 100644 --- a/docker-compose.prometheus.yaml +++ b/docker-compose.prometheus.yaml @@ -23,7 +23,7 @@ services: context: . dockerfile: docker/examples/Dockerfile args: - - PHP_VERSION=7.4-fpm + - PHP_VERSION=8.0-fpm - EXT_ENABLE=redis volumes: - ./examples/prometheus/index.php:/var/www/public/index.php diff --git a/docker-compose.w3cTraceContext.yaml b/docker-compose.w3cTraceContext.yaml index 6ec1ca968..6d0e3680f 100644 --- a/docker-compose.w3cTraceContext.yaml +++ b/docker-compose.w3cTraceContext.yaml @@ -1,7 +1,7 @@ version: '3.7' services: php: - image: ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base:${PHP_VERSION:-7.4} + image: ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base:${PHP_VERSION:-8.0} volumes: - ./:/usr/src/myapp - ./:/usr/src/open-telemetry/ diff --git a/docker-compose.yaml b/docker-compose.yaml index bd4fbcb94..6e71fff7a 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -1,7 +1,7 @@ version: '3.7' services: php: - image: ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base:${PHP_VERSION:-7.4} + image: ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base:${PHP_VERSION:-8.0} volumes: - ./:/usr/src/myapp user: "${PHP_USER}:root" diff --git a/docker/Dockerfile b/docker/Dockerfile index 147a9c968..cd10be6cd 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -1,4 +1,4 @@ -ARG PHP_VERSION=7.4 +ARG PHP_VERSION=8.0 FROM php:${PHP_VERSION}-cli-alpine as php_build ADD https://github.com/mlocati/docker-php-extension-installer/releases/latest/download/install-php-extensions /usr/local/bin/ diff --git a/examples/traces/features/batch_exporting_with_self_diagnostics.php b/examples/traces/features/batch_exporting_with_self_diagnostics.php new file mode 100644 index 000000000..5cfee88d0 --- /dev/null +++ b/examples/traces/features/batch_exporting_with_self_diagnostics.php @@ -0,0 +1,26 @@ +getTracer('io.opentelemetry.contrib.php'); +$tracer->spanBuilder('root')->startSpan()->end(); + +echo PHP_EOL . 'Example complete! ' . PHP_EOL; diff --git a/proto/otel/composer.json b/proto/otel/composer.json index dc8d24585..1ee4865e8 100644 --- a/proto/otel/composer.json +++ b/proto/otel/composer.json @@ -17,7 +17,7 @@ } ], "require": { - "php": "^7.4 || ^8.0", + "php": "^8.0", "google/protobuf": "^3.3.0" }, "autoload": { diff --git a/psalm.xml.dist b/psalm.xml.dist index cfc12dd06..bbcd259c9 100644 --- a/psalm.xml.dist +++ b/psalm.xml.dist @@ -18,4 +18,11 @@ + + + + + + + diff --git a/rector.php b/rector.php index 347905025..69f46d8e8 100644 --- a/rector.php +++ b/rector.php @@ -5,18 +5,18 @@ use Rector\CodeQuality\Rector\Array_\CallableThisArrayToAnonymousFunctionRector; use Rector\CodeQuality\Rector\Identical\FlipTypeControlToUseExclusiveTypeRector; use Rector\Config\RectorConfig; -use Rector\Core\ValueObject\PhpVersion; +use Rector\ValueObject\PhpVersion; use Rector\Set\ValueObject\SetList; return static function (RectorConfig $rectorConfig): void { - $rectorConfig->phpVersion(PhpVersion::PHP_74); + $rectorConfig->phpVersion(PhpVersion::PHP_80); $rectorConfig->paths([ __DIR__ . '/src', ]); $rectorConfig->sets([ - SetList::PHP_74, + SetList::PHP_80, SetList::CODE_QUALITY, ]); $rectorConfig->skip([ diff --git a/src/API/Baggage/Baggage.php b/src/API/Baggage/Baggage.php index 06c701605..e91e14bca 100644 --- a/src/API/Baggage/Baggage.php +++ b/src/API/Baggage/Baggage.php @@ -41,13 +41,9 @@ public static function getEmpty(): BaggageInterface return self::$emptyBaggage; } - /** @var array */ - private array $entries; - /** @param array $entries */ - public function __construct(array $entries = []) + public function __construct(private array $entries = []) { - $this->entries = $entries; } /** @inheritDoc */ diff --git a/src/API/Baggage/BaggageBuilder.php b/src/API/Baggage/BaggageBuilder.php index d4500eac5..80778661c 100644 --- a/src/API/Baggage/BaggageBuilder.php +++ b/src/API/Baggage/BaggageBuilder.php @@ -6,13 +6,9 @@ final class BaggageBuilder implements BaggageBuilderInterface { - /** @var array */ - private array $entries; - /** @param array $entries */ - public function __construct(array $entries = []) + public function __construct(private array $entries = []) { - $this->entries = $entries; } /** @inheritDoc */ diff --git a/src/API/Baggage/BaggageBuilderInterface.php b/src/API/Baggage/BaggageBuilderInterface.php index 301cfbc3c..a65fcc0f7 100644 --- a/src/API/Baggage/BaggageBuilderInterface.php +++ b/src/API/Baggage/BaggageBuilderInterface.php @@ -10,9 +10,8 @@ interface BaggageBuilderInterface { /** * @see https://github.com/open-telemetry/opentelemetry-specification/blob/v1.6.1/specification/baggage/api.md#set-value - * @param mixed $value */ - public function set(string $key, $value, API\MetadataInterface $metadata = null): API\BaggageBuilderInterface; + public function set(string $key, mixed $value, API\MetadataInterface $metadata = null): API\BaggageBuilderInterface; /** * @see https://github.com/open-telemetry/opentelemetry-specification/blob/v1.6.1/specification/baggage/api.md#remove-value diff --git a/src/API/Baggage/Entry.php b/src/API/Baggage/Entry.php index eb3d0de5b..659f166cc 100644 --- a/src/API/Baggage/Entry.php +++ b/src/API/Baggage/Entry.php @@ -6,27 +6,13 @@ final class Entry { - /** @var mixed */ - private $value; - - private MetadataInterface $metadata; - - /** - * @param mixed $value - * @param MetadataInterface $metadata - */ public function __construct( - $value, - MetadataInterface $metadata + private mixed $value, + private MetadataInterface $metadata, ) { - $this->value = $value; - $this->metadata = $metadata; } - /** - * @return mixed - */ - public function getValue() + public function getValue(): mixed { return $this->value; } diff --git a/src/API/Baggage/Metadata.php b/src/API/Baggage/Metadata.php index 043c96a8a..bf2a4fbf4 100644 --- a/src/API/Baggage/Metadata.php +++ b/src/API/Baggage/Metadata.php @@ -13,11 +13,8 @@ public static function getEmpty(): Metadata return self::$instance ??= new self(''); } - private string $metadata; - - public function __construct(string $metadata) + public function __construct(private string $metadata) { - $this->metadata = $metadata; } public function getValue(): string diff --git a/src/API/Baggage/Propagation/Parser.php b/src/API/Baggage/Propagation/Parser.php index 3518b858d..2473c8235 100644 --- a/src/API/Baggage/Propagation/Parser.php +++ b/src/API/Baggage/Propagation/Parser.php @@ -17,12 +17,10 @@ final class Parser private const EXCLUDED_VALUE_CHARS = [' ', '"', ',', ';', '\\']; private const EQUALS = '='; - /** @readonly */ - private string $baggageHeader; - - public function __construct(string $baggageHeader) - { - $this->baggageHeader = $baggageHeader; + public function __construct( + /** @readonly */ + private string $baggageHeader, + ) { } public function parseInto(BaggageBuilderInterface $baggageBuilder): void diff --git a/src/API/Behavior/Internal/LogWriter/Psr3LogWriter.php b/src/API/Behavior/Internal/LogWriter/Psr3LogWriter.php index 5b2d19c15..c83b2631e 100644 --- a/src/API/Behavior/Internal/LogWriter/Psr3LogWriter.php +++ b/src/API/Behavior/Internal/LogWriter/Psr3LogWriter.php @@ -8,11 +8,8 @@ class Psr3LogWriter implements LogWriterInterface { - private LoggerInterface $logger; - - public function __construct(LoggerInterface $logger) + public function __construct(private LoggerInterface $logger) { - $this->logger = $logger; } public function write($level, string $message, array $context): void diff --git a/src/API/Behavior/Internal/LogWriterFactory.php b/src/API/Behavior/Internal/LogWriterFactory.php index 07c48cea5..5bf5a3af2 100644 --- a/src/API/Behavior/Internal/LogWriterFactory.php +++ b/src/API/Behavior/Internal/LogWriterFactory.php @@ -33,6 +33,7 @@ public function create(): LogWriterInterface return new Psr3LogWriter($logger); } error_log('OpenTelemetry: cannot use OTEL_PHP_LOG_DESTINATION=psr3 without providing a PSR-3 logger'); + //default to error log return new ErrorLogWriter(); case 'error_log': diff --git a/src/API/Globals.php b/src/API/Globals.php index abf164a53..7256c1ac7 100644 --- a/src/API/Globals.php +++ b/src/API/Globals.php @@ -27,21 +27,12 @@ final class Globals private static array $initializers = []; private static ?self $globals = null; - private TracerProviderInterface $tracerProvider; - private MeterProviderInterface $meterProvider; - private TextMapPropagatorInterface $propagator; - private LoggerProviderInterface $loggerProvider; - public function __construct( - TracerProviderInterface $tracerProvider, - MeterProviderInterface $meterProvider, - LoggerProviderInterface $loggerProvider, - TextMapPropagatorInterface $propagator + private TracerProviderInterface $tracerProvider, + private MeterProviderInterface $meterProvider, + private LoggerProviderInterface $loggerProvider, + private TextMapPropagatorInterface $propagator, ) { - $this->tracerProvider = $tracerProvider; - $this->meterProvider = $meterProvider; - $this->loggerProvider = $loggerProvider; - $this->propagator = $propagator; } public static function tracerProvider(): TracerProviderInterface diff --git a/src/API/Instrumentation/CachedInstrumentation.php b/src/API/Instrumentation/CachedInstrumentation.php index 5ffb3950d..18609b66b 100644 --- a/src/API/Instrumentation/CachedInstrumentation.php +++ b/src/API/Instrumentation/CachedInstrumentation.php @@ -4,9 +4,6 @@ namespace OpenTelemetry\API\Instrumentation; -use ArrayAccess; -use function assert; -use function class_exists; use OpenTelemetry\API\Globals; use OpenTelemetry\API\Logs\LoggerInterface; use OpenTelemetry\API\Logs\LoggerProviderInterface; @@ -14,7 +11,7 @@ use OpenTelemetry\API\Metrics\MeterProviderInterface; use OpenTelemetry\API\Trace\TracerInterface; use OpenTelemetry\API\Trace\TracerProviderInterface; -use const PHP_VERSION_ID; +use WeakMap; /** * Provides access to cached {@link TracerInterface} and {@link MeterInterface} @@ -26,51 +23,31 @@ */ final class CachedInstrumentation { - private string $name; - private ?string $version; - private ?string $schemaUrl; - private iterable $attributes; - /** @var ArrayAccess|null */ - private ?ArrayAccess $tracers; - /** @var ArrayAccess|null */ - private ?ArrayAccess $meters; - /** @var ArrayAccess|null */ - private ?ArrayAccess $loggers; - - public function __construct(string $name, ?string $version = null, ?string $schemaUrl = null, iterable $attributes = []) - { - $this->name = $name; - $this->version = $version; - $this->schemaUrl = $schemaUrl; - $this->attributes = $attributes; - $this->tracers = self::createWeakMap(); - $this->meters = self::createWeakMap(); - $this->loggers = self::createWeakMap(); - } - - private static function createWeakMap(): ?ArrayAccess - { - if (PHP_VERSION_ID < 80000) { - return null; - } - - /** @phan-suppress-next-line PhanUndeclaredClassReference */ - assert(class_exists(\WeakMap::class, false)); - /** @phan-suppress-next-line PhanUndeclaredClassMethod */ - $map = new \WeakMap(); - assert($map instanceof ArrayAccess); - - return $map; + /** @var WeakMap */ + private WeakMap $tracers; + /** @var WeakMap */ + private WeakMap $meters; + /** @var WeakMap */ + private WeakMap $loggers; + + /** + * @psalm-suppress PropertyTypeCoercion + */ + public function __construct( + private string $name, + private ?string $version = null, + private ?string $schemaUrl = null, + private iterable $attributes = [], + ) { + $this->tracers = new \WeakMap(); + $this->meters = new \WeakMap(); + $this->loggers = new \WeakMap(); } public function tracer(): TracerInterface { $tracerProvider = Globals::tracerProvider(); - if ($this->tracers === null) { - return $tracerProvider->getTracer($this->name, $this->version, $this->schemaUrl, $this->attributes); - } - return $this->tracers[$tracerProvider] ??= $tracerProvider->getTracer($this->name, $this->version, $this->schemaUrl, $this->attributes); } @@ -78,20 +55,12 @@ public function meter(): MeterInterface { $meterProvider = Globals::meterProvider(); - if ($this->meters === null) { - return $meterProvider->getMeter($this->name, $this->version, $this->schemaUrl, $this->attributes); - } - return $this->meters[$meterProvider] ??= $meterProvider->getMeter($this->name, $this->version, $this->schemaUrl, $this->attributes); } public function logger(): LoggerInterface { $loggerProvider = Globals::loggerProvider(); - if ($this->loggers === null) { - return $loggerProvider->getLogger($this->name, $this->version, $this->schemaUrl, $this->attributes); - } - return $this->loggers[$loggerProvider] ??= $loggerProvider->getLogger($this->name, $this->version, $this->schemaUrl, $this->attributes); } } diff --git a/src/API/Instrumentation/InstrumentationTrait.php b/src/API/Instrumentation/InstrumentationTrait.php index 1e695adb5..b46372d1a 100644 --- a/src/API/Instrumentation/InstrumentationTrait.php +++ b/src/API/Instrumentation/InstrumentationTrait.php @@ -111,6 +111,7 @@ abstract public function init(): bool; public function activate(): bool { $this->validateImplementation(); + // activate instrumentation with the API. not implemented yet. return true; } diff --git a/src/API/Logs/EventLogger.php b/src/API/Logs/EventLogger.php index 68deb865c..89e942ce7 100644 --- a/src/API/Logs/EventLogger.php +++ b/src/API/Logs/EventLogger.php @@ -6,13 +6,10 @@ class EventLogger implements EventLoggerInterface { - private LoggerInterface $logger; - private string $domain; - - public function __construct(LoggerInterface $logger, string $domain) - { - $this->logger = $logger; - $this->domain = $domain; + public function __construct( + private LoggerInterface $logger, + private string $domain, + ) { } public function logEvent(string $eventName, LogRecord $logRecord): void diff --git a/src/API/Logs/LogRecord.php b/src/API/Logs/LogRecord.php index 6833c71f9..755344e74 100644 --- a/src/API/Logs/LogRecord.php +++ b/src/API/Logs/LogRecord.php @@ -15,15 +15,10 @@ class LogRecord protected ?ContextInterface $context = null; protected int $severityNumber = 0; protected ?string $severityText = null; - protected $body = null; protected array $attributes = []; - /** - * @param mixed $body - */ - public function __construct($body = null) + public function __construct(protected mixed $body = null) { - $this->body = $body; } /** @@ -45,7 +40,6 @@ public function setContext(?ContextInterface $context = null): self } /** - * @param int $severityNumber Severity number * @see https://opentelemetry.io/docs/reference/specification/logs/data-model/#field-severitynumber */ public function setSeverityNumber(int $severityNumber): self @@ -79,7 +73,7 @@ public function setAttributes(iterable $attributes): self return $this; } - public function setAttribute(string $name, $value): self + public function setAttribute(string $name, mixed $value): self { $this->attributes[$name] = $value; @@ -89,7 +83,7 @@ public function setAttribute(string $name, $value): self /** * @param mixed $body The log record body */ - public function setBody($body = null): self + public function setBody(mixed $body = null): self { $this->body = $body; diff --git a/src/API/Logs/LoggerProviderInterface.php b/src/API/Logs/LoggerProviderInterface.php index e60353de2..340f49d47 100644 --- a/src/API/Logs/LoggerProviderInterface.php +++ b/src/API/Logs/LoggerProviderInterface.php @@ -13,6 +13,6 @@ public function getLogger( string $name, ?string $version = null, ?string $schemaUrl = null, - iterable $attributes = [] //instrumentation scope attributes + iterable $attributes = [], //instrumentation scope attributes ): LoggerInterface; } diff --git a/src/API/Logs/Map/Psr3.php b/src/API/Logs/Map/Psr3.php index 8fd85fad0..63a00e7b9 100644 --- a/src/API/Logs/Map/Psr3.php +++ b/src/API/Logs/Map/Psr3.php @@ -16,25 +16,16 @@ class Psr3 */ public static function severityNumber(string $level): int { - switch (strtolower($level)) { - case LogLevel::DEBUG: - return 5; - case LogLevel::INFO: - return 9; - case LogLevel::NOTICE: - return 10; - case LogLevel::WARNING: - return 13; - case LogLevel::ERROR: - return 17; - case LogLevel::CRITICAL: - return 18; - case LogLevel::ALERT: - return 19; - case LogLevel::EMERGENCY: - return 21; - default: - return 0; - } + return match (strtolower($level)) { + LogLevel::DEBUG => 5, + LogLevel::INFO => 9, + LogLevel::NOTICE => 10, + LogLevel::WARNING => 13, + LogLevel::ERROR => 17, + LogLevel::CRITICAL => 18, + LogLevel::ALERT => 19, + LogLevel::EMERGENCY => 21, + default => 0, + }; } } diff --git a/src/API/Metrics/CounterInterface.php b/src/API/Metrics/CounterInterface.php index 56f488caf..c5cec7f69 100644 --- a/src/API/Metrics/CounterInterface.php +++ b/src/API/Metrics/CounterInterface.php @@ -13,9 +13,8 @@ interface CounterInterface extends SynchronousInstrument * @param float|int $amount non-negative amount to increment by * @param iterable $attributes * attributes of the data point - * @param ContextInterface|false|null $context execution context * * @see https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#add */ - public function add($amount, iterable $attributes = [], $context = null): void; + public function add(float|int $amount, iterable $attributes = [], ContextInterface|false|null $context = null): void; } diff --git a/src/API/Metrics/HistogramInterface.php b/src/API/Metrics/HistogramInterface.php index 34e4e8d2d..71a9091cf 100644 --- a/src/API/Metrics/HistogramInterface.php +++ b/src/API/Metrics/HistogramInterface.php @@ -17,5 +17,5 @@ interface HistogramInterface extends SynchronousInstrument * * @see https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#record */ - public function record($amount, iterable $attributes = [], $context = null): void; + public function record(float|int $amount, iterable $attributes = [], ContextInterface|false|null $context = null): void; } diff --git a/src/API/Metrics/MeterInterface.php b/src/API/Metrics/MeterInterface.php index 55779fe41..192a0cd08 100644 --- a/src/API/Metrics/MeterInterface.php +++ b/src/API/Metrics/MeterInterface.php @@ -38,15 +38,15 @@ interface MeterInterface public function batchObserve( callable $callback, AsynchronousInstrument $instrument, - AsynchronousInstrument ...$instruments + AsynchronousInstrument ...$instruments, ): ObservableCallbackInterface; /** * Creates a `Counter`. * * @param string $name name of the instrument - * @param string|null $unit unit of measure - * @param string|null $description description of the instrument + * @param ?string $unit unit of measure + * @param ?string $description description of the instrument * @param array $advisory an optional set of recommendations * @return CounterInterface created instrument * @@ -56,15 +56,15 @@ public function createCounter( string $name, ?string $unit = null, ?string $description = null, - array $advisory = [] + array $advisory = [], ): CounterInterface; /** * Creates an `ObservableCounter`. * * @param string $name name of the instrument - * @param string|null $unit unit of measure - * @param string|null $description description of the instrument + * @param ?string $unit unit of measure + * @param ?string $description description of the instrument * @param array|callable $advisory an optional set of recommendations, or * deprecated: the first callback to report measurements * @param callable ...$callbacks responsible for reporting measurements @@ -76,8 +76,8 @@ public function createObservableCounter( string $name, ?string $unit = null, ?string $description = null, - $advisory = [], - callable ...$callbacks + array|callable $advisory = [], + callable ...$callbacks, ): ObservableCounterInterface; /** @@ -96,7 +96,7 @@ public function createHistogram( string $name, ?string $unit = null, ?string $description = null, - array $advisory = [] + array $advisory = [], ): HistogramInterface; /** @@ -116,8 +116,8 @@ public function createObservableGauge( string $name, ?string $unit = null, ?string $description = null, - $advisory = [], - callable ...$callbacks + array|callable $advisory = [], + callable ...$callbacks, ): ObservableGaugeInterface; /** @@ -135,7 +135,7 @@ public function createUpDownCounter( string $name, ?string $unit = null, ?string $description = null, - array $advisory = [] + array $advisory = [], ): UpDownCounterInterface; /** @@ -155,7 +155,7 @@ public function createObservableUpDownCounter( string $name, ?string $unit = null, ?string $description = null, - $advisory = [], - callable ...$callbacks + array|callable $advisory = [], + callable ...$callbacks, ): ObservableUpDownCounterInterface; } diff --git a/src/API/Metrics/MeterProviderInterface.php b/src/API/Metrics/MeterProviderInterface.php index f8fa07a2e..fe9393910 100644 --- a/src/API/Metrics/MeterProviderInterface.php +++ b/src/API/Metrics/MeterProviderInterface.php @@ -23,6 +23,6 @@ public function getMeter( string $name, ?string $version = null, ?string $schemaUrl = null, - iterable $attributes = [] + iterable $attributes = [], ): MeterInterface; } diff --git a/src/API/Metrics/Noop/NoopMeterProvider.php b/src/API/Metrics/Noop/NoopMeterProvider.php index b4b5810eb..6ee6d6774 100644 --- a/src/API/Metrics/Noop/NoopMeterProvider.php +++ b/src/API/Metrics/Noop/NoopMeterProvider.php @@ -13,7 +13,7 @@ public function getMeter( string $name, ?string $version = null, ?string $schemaUrl = null, - iterable $attributes = [] + iterable $attributes = [], ): MeterInterface { return new NoopMeter(); } diff --git a/src/API/Metrics/ObserverInterface.php b/src/API/Metrics/ObserverInterface.php index 36e0ea791..f9975c1bc 100644 --- a/src/API/Metrics/ObserverInterface.php +++ b/src/API/Metrics/ObserverInterface.php @@ -14,5 +14,5 @@ interface ObserverInterface * @param iterable $attributes * attributes of the data point */ - public function observe($amount, iterable $attributes = []): void; + public function observe(float|int $amount, iterable $attributes = []): void; } diff --git a/src/API/Trace/NonRecordingSpan.php b/src/API/Trace/NonRecordingSpan.php index 67d74d39b..b94d46305 100644 --- a/src/API/Trace/NonRecordingSpan.php +++ b/src/API/Trace/NonRecordingSpan.php @@ -13,12 +13,8 @@ */ final class NonRecordingSpan extends Span { - private SpanContextInterface $context; - - public function __construct( - SpanContextInterface $context - ) { - $this->context = $context; + public function __construct(private SpanContextInterface $context) + { } /** @inheritDoc */ diff --git a/src/API/Trace/NoopSpanBuilder.php b/src/API/Trace/NoopSpanBuilder.php index 6f971e525..024118d35 100644 --- a/src/API/Trace/NoopSpanBuilder.php +++ b/src/API/Trace/NoopSpanBuilder.php @@ -10,17 +10,13 @@ final class NoopSpanBuilder implements SpanBuilderInterface { - private ContextStorageInterface $contextStorage; + private ContextInterface|false|null $parentContext = null; - /** @var ContextInterface|false|null */ - private $parentContext = null; - - public function __construct(ContextStorageInterface $contextStorage) + public function __construct(private ContextStorageInterface $contextStorage) { - $this->contextStorage = $contextStorage; } - public function setParent($context): SpanBuilderInterface + public function setParent(ContextInterface|false|null $context): SpanBuilderInterface { $this->parentContext = $context; @@ -32,7 +28,7 @@ public function addLink(SpanContextInterface $context, iterable $attributes = [] return $this; } - public function setAttribute(string $key, $value): SpanBuilderInterface + public function setAttribute(string $key, mixed $value): SpanBuilderInterface { return $this; } diff --git a/src/API/Trace/NoopTracerProvider.php b/src/API/Trace/NoopTracerProvider.php index e186a6fd9..1ffb4be74 100644 --- a/src/API/Trace/NoopTracerProvider.php +++ b/src/API/Trace/NoopTracerProvider.php @@ -10,7 +10,7 @@ public function getTracer( string $name, ?string $version = null, ?string $schemaUrl = null, - iterable $attributes = [] + iterable $attributes = [], ): TracerInterface { return NoopTracer::getInstance(); } diff --git a/src/API/Trace/Propagation/TraceContextValidator.php b/src/API/Trace/Propagation/TraceContextValidator.php index 5fb3f12c7..167cc0daa 100644 --- a/src/API/Trace/Propagation/TraceContextValidator.php +++ b/src/API/Trace/Propagation/TraceContextValidator.php @@ -11,10 +11,6 @@ class TraceContextValidator public const TRACE_FLAG_LENGTH = 2; public const TRACE_VERSION_REGEX = '/^(?!ff)[\da-f]{2}$/'; - /** - * @param string $traceVersion - * @return bool Returns a value that indicates whether a trace version is valid. - */ public static function isValidTraceVersion(string $traceVersion): bool { return 1 === preg_match(self::TRACE_VERSION_REGEX, $traceVersion); diff --git a/src/API/Trace/SpanBuilderInterface.php b/src/API/Trace/SpanBuilderInterface.php index 52070933a..b8a9bce72 100644 --- a/src/API/Trace/SpanBuilderInterface.php +++ b/src/API/Trace/SpanBuilderInterface.php @@ -20,10 +20,10 @@ interface SpanBuilderInterface * * @see https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#span-creation */ - public function setParent($context): SpanBuilderInterface; + public function setParent(ContextInterface|false|null $context): SpanBuilderInterface; public function addLink(SpanContextInterface $context, iterable $attributes = []): SpanBuilderInterface; - public function setAttribute(string $key, $value): SpanBuilderInterface; + public function setAttribute(string $key, mixed $value): SpanBuilderInterface; public function setAttributes(iterable $attributes): SpanBuilderInterface; /** diff --git a/src/API/Trace/SpanContext.php b/src/API/Trace/SpanContext.php index 7da7c0701..7724def86 100644 --- a/src/API/Trace/SpanContext.php +++ b/src/API/Trace/SpanContext.php @@ -15,35 +15,24 @@ final class SpanContext implements SpanContextInterface * @see https://www.w3.org/TR/trace-context/#sampled-flag */ private bool $isSampled; - - private string $traceId; - private string $spanId; - private ?TraceStateInterface $traceState; private bool $isValid = true; - private bool $isRemote; - private int $traceFlags; private function __construct( - string $traceId, - string $spanId, - int $traceFlags, - bool $isRemote, - TraceStateInterface $traceState = null + private string $traceId, + private string $spanId, + private int $traceFlags, + private bool $isRemote, + private ?TraceStateInterface $traceState = null, ) { // TraceId must be exactly 16 bytes (32 chars) and at least one non-zero byte // SpanId must be exactly 8 bytes (16 chars) and at least one non-zero byte if (!SpanContextValidator::isValidTraceId($traceId) || !SpanContextValidator::isValidSpanId($spanId)) { - $traceId = SpanContextValidator::INVALID_TRACE; - $spanId = SpanContextValidator::INVALID_SPAN; + $this->traceId = SpanContextValidator::INVALID_TRACE; + $this->spanId = SpanContextValidator::INVALID_SPAN; $this->isValid=false; } - $this->traceId = $traceId; - $this->spanId = $spanId; - $this->traceState = $traceState; - $this->isRemote = $isRemote; $this->isSampled = ($traceFlags & TraceFlags::SAMPLED) === TraceFlags::SAMPLED; - $this->traceFlags = $traceFlags; } public function getTraceId(): string diff --git a/src/API/Trace/SpanInterface.php b/src/API/Trace/SpanInterface.php index 274a257ea..72c042603 100644 --- a/src/API/Trace/SpanInterface.php +++ b/src/API/Trace/SpanInterface.php @@ -55,7 +55,7 @@ public function isRecording(): bool; * @param non-empty-string $key * @param bool|int|float|string|array|null $value Note: arrays MUST be homogeneous, i.e. it MUST NOT contain values of different types. */ - public function setAttribute(string $key, $value): SpanInterface; + public function setAttribute(string $key, bool|int|float|string|array|null $value): SpanInterface; /** * @see https://github.com/open-telemetry/opentelemetry-specification/blob/v1.6.1/specification/trace/api.md#set-attributes diff --git a/src/API/Trace/TraceStateInterface.php b/src/API/Trace/TraceStateInterface.php index 79d4e0299..394ea1b95 100644 --- a/src/API/Trace/TraceStateInterface.php +++ b/src/API/Trace/TraceStateInterface.php @@ -24,8 +24,6 @@ interface TraceStateInterface * Return a new TraceState object that inherits from this TraceState * and contains the given key value pair. * - * @param string $key - * @param string $value * @return TraceStateInterface */ public function with(string $key, string $value): TraceStateInterface; @@ -34,7 +32,6 @@ public function with(string $key, string $value): TraceStateInterface; * Return a new TraceState object that inherits from this TraceState * without the given key value pair. * - * @param string $key * @return TraceStateInterface */ public function without(string $key): TraceStateInterface; @@ -42,7 +39,6 @@ public function without(string $key): TraceStateInterface; /** * Return the value of a given key from this TraceState if it exists * - * @param string $key * @return string|null */ public function get(string $key): ?string; diff --git a/src/API/Trace/TracerProviderInterface.php b/src/API/Trace/TracerProviderInterface.php index 9f5d20759..31a51c0a0 100644 --- a/src/API/Trace/TracerProviderInterface.php +++ b/src/API/Trace/TracerProviderInterface.php @@ -14,6 +14,6 @@ public function getTracer( string $name, ?string $version = null, ?string $schemaUrl = null, - iterable $attributes = [] + iterable $attributes = [], ): TracerInterface; } diff --git a/src/API/composer.json b/src/API/composer.json index c756df119..78c9c5ee0 100644 --- a/src/API/composer.json +++ b/src/API/composer.json @@ -17,10 +17,9 @@ } ], "require": { - "php": "^7.4 || ^8.0", + "php": "^8.0", "open-telemetry/context": "^1.0", "psr/log": "^1.1|^2.0|^3.0", - "symfony/polyfill-php80": "^1.26", "symfony/polyfill-php81": "^1.26", "symfony/polyfill-php82": "^1.26" }, diff --git a/src/Context/Context.php b/src/Context/Context.php index 1a0b26226..278c27d3e 100644 --- a/src/Context/Context.php +++ b/src/Context/Context.php @@ -39,6 +39,7 @@ public static function createKey(string $key): ContextKeyInterface /** * @param ContextStorageInterface&ExecutionContextAwareInterface $storage + * @todo update type-hint (php >= 8.1) */ public static function setStorage(ContextStorageInterface $storage): void { @@ -47,6 +48,7 @@ public static function setStorage(ContextStorageInterface $storage): void /** * @return ContextStorageInterface&ExecutionContextAwareInterface + * @todo update return type-hint (php >= 8.1) */ public static function storage(): ContextStorageInterface { @@ -55,11 +57,9 @@ public static function storage(): ContextStorageInterface } /** - * @param ContextInterface|false|null $context - * * @internal OpenTelemetry */ - public static function resolve($context, ?ContextStorageInterface $contextStorage = null): ContextInterface + public static function resolve(ContextInterface|false|null $context, ?ContextStorageInterface $contextStorage = null): ContextInterface { return $context ?? ($contextStorage ?? self::storage())->current() diff --git a/src/Context/ContextKey.php b/src/Context/ContextKey.php index f7450249e..16ecb49ee 100644 --- a/src/Context/ContextKey.php +++ b/src/Context/ContextKey.php @@ -9,11 +9,8 @@ */ final class ContextKey implements ContextKeyInterface { - private ?string $name; - - public function __construct(?string $name=null) + public function __construct(private ?string $name = null) { - $this->name = $name; } public function name(): ?string diff --git a/src/Context/ContextStorageHead.php b/src/Context/ContextStorageHead.php index 3cc4d7181..a942496dd 100644 --- a/src/Context/ContextStorageHead.php +++ b/src/Context/ContextStorageHead.php @@ -9,11 +9,9 @@ */ final class ContextStorageHead { - public ContextStorage $storage; public ?ContextStorageNode $node = null; - public function __construct(ContextStorage $storage) + public function __construct(public ContextStorage $storage) { - $this->storage = $storage; } } diff --git a/src/Context/ContextStorageNode.php b/src/Context/ContextStorageNode.php index 12d521660..241fe951e 100644 --- a/src/Context/ContextStorageNode.php +++ b/src/Context/ContextStorageNode.php @@ -11,19 +11,13 @@ */ final class ContextStorageNode implements ScopeInterface, ContextStorageScopeInterface { - public ContextInterface $context; - public ContextStorageHead $head; - private ?ContextStorageNode $previous; private array $localStorage = []; public function __construct( - ContextInterface $context, - ContextStorageHead $head, - ?ContextStorageNode $previous = null + public ContextInterface $context, + public ContextStorageHead $head, + private ?ContextStorageNode $previous = null, ) { - $this->context = $context; - $this->head = $head; - $this->previous = $previous; } public function offsetExists($offset): bool @@ -76,8 +70,8 @@ public function detach(): int assert($this->head->node !== null); for ($n = $this->head->node, $depth = 1; - $n->previous !== $this; - $n = $n->previous, $depth++) { + $n->previous !== $this; + $n = $n->previous, $depth++) { assert($n->previous !== null); } $n->previous = $this->previous; diff --git a/src/Context/DebugScope.php b/src/Context/DebugScope.php index 887762025..437234e40 100644 --- a/src/Context/DebugScope.php +++ b/src/Context/DebugScope.php @@ -24,15 +24,12 @@ final class DebugScope implements ScopeInterface { private static bool $shutdownHandlerInitialized = false; private static bool $finalShutdownPhase = false; - - private ContextStorageScopeInterface $scope; private ?int $fiberId; private array $createdAt; private ?array $detachedAt = null; - public function __construct(ContextStorageScopeInterface $scope) + public function __construct(private ContextStorageScopeInterface $scope) { - $this->scope = $scope; $this->fiberId = self::currentFiberId(); $this->createdAt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); diff --git a/src/Context/FiberBoundContextStorage.php b/src/Context/FiberBoundContextStorage.php index 667f73b3d..180846f91 100644 --- a/src/Context/FiberBoundContextStorage.php +++ b/src/Context/FiberBoundContextStorage.php @@ -20,15 +20,11 @@ */ final class FiberBoundContextStorage implements ContextStorageInterface, ExecutionContextAwareInterface { - /** @var ContextStorageInterface&ExecutionContextAwareInterface */ - private ContextStorageInterface $storage; - /** * @param ContextStorageInterface&ExecutionContextAwareInterface $storage */ - public function __construct(ContextStorageInterface $storage) + public function __construct(private ContextStorageInterface $storage) { - $this->storage = $storage; } public function fork($id): void diff --git a/src/Context/FiberBoundContextStorageScope.php b/src/Context/FiberBoundContextStorageScope.php index 647552244..f4708f216 100644 --- a/src/Context/FiberBoundContextStorageScope.php +++ b/src/Context/FiberBoundContextStorageScope.php @@ -18,11 +18,8 @@ */ final class FiberBoundContextStorageScope implements ScopeInterface, ContextStorageScopeInterface { - private ContextStorageScopeInterface $scope; - - public function __construct(ContextStorageScopeInterface $scope) + public function __construct(private ContextStorageScopeInterface $scope) { - $this->scope = $scope; } public function offsetExists($offset): bool diff --git a/src/Context/Propagation/ArrayAccessGetterSetter.php b/src/Context/Propagation/ArrayAccessGetterSetter.php index 51263044d..5345de261 100644 --- a/src/Context/Propagation/ArrayAccessGetterSetter.php +++ b/src/Context/Propagation/ArrayAccessGetterSetter.php @@ -6,11 +6,8 @@ use function array_key_first; use ArrayAccess; -use function get_class; -use function gettype; use InvalidArgumentException; use function is_array; -use function is_object; use function is_string; use function sprintf; use function strcasecmp; @@ -53,7 +50,7 @@ public function keys($carrier): array throw new InvalidArgumentException( sprintf( 'Unsupported carrier type: %s.', - is_object($carrier) ? get_class($carrier) : gettype($carrier), + get_debug_type($carrier), ) ); } @@ -75,7 +72,7 @@ public function get($carrier, string $key): ?string throw new InvalidArgumentException( sprintf( 'Unsupported carrier type: %s. Unable to get value associated with key:%s', - is_object($carrier) ? get_class($carrier) : gettype($carrier), + get_debug_type($carrier), $key ) ); @@ -100,7 +97,7 @@ public function set(&$carrier, string $key, string $value): void throw new InvalidArgumentException( sprintf( 'Unsupported carrier type: %s. Unable to set value associated with key:%s', - is_object($carrier) ? get_class($carrier) : gettype($carrier), + get_debug_type($carrier), $key ) ); diff --git a/src/Context/Propagation/MultiTextMapPropagator.php b/src/Context/Propagation/MultiTextMapPropagator.php index 075fe98fe..9a81324fc 100644 --- a/src/Context/Propagation/MultiTextMapPropagator.php +++ b/src/Context/Propagation/MultiTextMapPropagator.php @@ -15,14 +15,6 @@ final class MultiTextMapPropagator implements TextMapPropagatorInterface { /** * @readonly - * - * @var list - */ - private array $propagators = []; - - /** - * @readonly - * * @var list */ private array $fields; @@ -32,10 +24,11 @@ final class MultiTextMapPropagator implements TextMapPropagatorInterface * * @param list $propagators */ - public function __construct(array $propagators) - { - $this->propagators = $propagators; - $this->fields = $this->extractFields($propagators); + public function __construct( + /** @readonly */ + private array $propagators, + ) { + $this->fields = $this->extractFields($this->propagators); } public function fields(): array diff --git a/src/Context/Propagation/SanitizeCombinedHeadersPropagationGetter.php b/src/Context/Propagation/SanitizeCombinedHeadersPropagationGetter.php index 40652982e..cab2b7b19 100644 --- a/src/Context/Propagation/SanitizeCombinedHeadersPropagationGetter.php +++ b/src/Context/Propagation/SanitizeCombinedHeadersPropagationGetter.php @@ -18,11 +18,8 @@ final class SanitizeCombinedHeadersPropagationGetter implements PropagationGette private const SERVER_CONCAT_HEADERS_REGEX = '/;(?=[^,=;]*=|$)/'; private const TRAILING_LEADING_SEPARATOR_REGEX = '/^' . self::LIST_MEMBERS_SEPARATOR . '+|' . self::LIST_MEMBERS_SEPARATOR . '+$/'; - private PropagationGetterInterface $getter; - - public function __construct(PropagationGetterInterface $getter) + public function __construct(private PropagationGetterInterface $getter) { - $this->getter = $getter; } public function keys($carrier): array diff --git a/src/Context/Propagation/TextMapPropagatorInterface.php b/src/Context/Propagation/TextMapPropagatorInterface.php index fdf2d5141..b2e6582fa 100644 --- a/src/Context/Propagation/TextMapPropagatorInterface.php +++ b/src/Context/Propagation/TextMapPropagatorInterface.php @@ -25,10 +25,8 @@ public function fields() : array; * via an {@see PropagationSetterInterface}. * * @see https://github.com/open-telemetry/opentelemetry-specification/blob/v1.6.1/specification/context/api-propagators.md#textmap-inject - * - * @param mixed $carrier */ - public function inject(&$carrier, PropagationSetterInterface $setter = null, ContextInterface $context = null): void; + public function inject(mixed &$carrier, PropagationSetterInterface $setter = null, ContextInterface $context = null): void; /** * Extracts specific values from the provided carrier into the provided {@see ContextInterface} diff --git a/src/Context/composer.json b/src/Context/composer.json index 348b57f73..ee191de9b 100644 --- a/src/Context/composer.json +++ b/src/Context/composer.json @@ -17,8 +17,7 @@ } ], "require": { - "php": "^7.4 || ^8.0", - "symfony/polyfill-php80": "^1.26", + "php": "^8.0", "symfony/polyfill-php81": "^1.26", "symfony/polyfill-php82": "^1.26" }, diff --git a/src/Contrib/Grpc/GrpcTransport.php b/src/Contrib/Grpc/GrpcTransport.php index 664516844..338b89b3b 100644 --- a/src/Contrib/Grpc/GrpcTransport.php +++ b/src/Contrib/Grpc/GrpcTransport.php @@ -18,6 +18,7 @@ use const Grpc\OP_SEND_MESSAGE; use const Grpc\STATUS_OK; use Grpc\Timeval; +use OpenTelemetry\Contrib\Otlp\ContentTypes; use OpenTelemetry\SDK\Common\Export\TransportInterface; use OpenTelemetry\SDK\Common\Future\CancellationInterface; use OpenTelemetry\SDK\Common\Future\CompletedFuture; @@ -36,23 +37,21 @@ final class GrpcTransport implements TransportInterface { private array $metadata; private Channel $channel; - private string $method; private bool $closed = false; public function __construct( string $endpoint, array $opts, - string $method, - array $headers = [] + private string $method, + array $headers = [], ) { $this->channel = new Channel($endpoint, $opts); - $this->method = $method; $this->metadata = $this->formatMetadata(array_change_key_case($headers)); } public function contentType(): string { - return 'application/x-protobuf'; + return ContentTypes::PROTOBUF; } public function send(string $payload, ?CancellationInterface $cancellation = null): FutureInterface diff --git a/src/Contrib/Grpc/GrpcTransportFactory.php b/src/Contrib/Grpc/GrpcTransportFactory.php index d290fd542..d2c9ecf4b 100644 --- a/src/Contrib/Grpc/GrpcTransportFactory.php +++ b/src/Contrib/Grpc/GrpcTransportFactory.php @@ -12,6 +12,7 @@ use InvalidArgumentException; use function json_encode; use OpenTelemetry\API\Behavior\LogsMessagesTrait; +use OpenTelemetry\Contrib\Otlp\ContentTypes; use OpenTelemetry\SDK\Common\Export\TransportFactoryInterface; use OpenTelemetry\SDK\Common\Export\TransportInterface; use function parse_url; @@ -31,7 +32,7 @@ final class GrpcTransportFactory implements TransportFactoryInterface */ public function create( string $endpoint, - string $contentType = 'application/x-protobuf', + string $contentType = ContentTypes::PROTOBUF, array $headers = [], $compression = null, float $timeout = 10., @@ -39,15 +40,15 @@ public function create( int $maxRetries = 3, ?string $cacert = null, ?string $cert = null, - ?string $key = null + ?string $key = null, ): TransportInterface { $parts = parse_url($endpoint); if (!isset($parts['scheme'], $parts['host'], $parts['path'])) { throw new InvalidArgumentException('Endpoint has to contain scheme, host and path'); } /** @phpstan-ignore-next-line */ - if ($contentType !== 'application/x-protobuf') { - throw new InvalidArgumentException(sprintf('Unsupported content type "%s", grpc transport supports only application/x-protobuf', $contentType)); + if ($contentType !== ContentTypes::PROTOBUF) { + throw new InvalidArgumentException(sprintf('Unsupported content type "%s", grpc transport supports only %s', $contentType, ContentTypes::PROTOBUF)); } $scheme = $parts['scheme']; @@ -86,7 +87,7 @@ private static function createOpts( $compression, float $timeout, int $maxRetries, - int $retryDelay + int $retryDelay, ): array { $opts = []; diff --git a/src/Contrib/Grpc/composer.json b/src/Contrib/Grpc/composer.json index e5311430e..96b829741 100644 --- a/src/Contrib/Grpc/composer.json +++ b/src/Contrib/Grpc/composer.json @@ -17,7 +17,7 @@ } ], "require": { - "php": "^7.4 || ^8.0", + "php": "^8.0", "ext-grpc": "*", "grpc/grpc": "*", "open-telemetry/sdk": "^1.0" diff --git a/src/Contrib/Otlp/LogsExporter.php b/src/Contrib/Otlp/LogsExporter.php index fb100391f..254e407dd 100644 --- a/src/Contrib/Otlp/LogsExporter.php +++ b/src/Contrib/Otlp/LogsExporter.php @@ -20,20 +20,17 @@ class LogsExporter implements LogRecordExporterInterface { use LogsMessagesTrait; - - private TransportInterface $transport; private ProtobufSerializer $serializer; /** * @psalm-param TransportInterface $transport */ - public function __construct(TransportInterface $transport) + public function __construct(private TransportInterface $transport) { if (!class_exists('\Google\Protobuf\Api')) { throw new RuntimeException('No protobuf implementation found (ext-protobuf or google/protobuf)'); } - $this->transport = $transport; - $this->serializer = ProtobufSerializer::forTransport($transport); + $this->serializer = ProtobufSerializer::forTransport($this->transport); } /** diff --git a/src/Contrib/Otlp/LogsExporterFactory.php b/src/Contrib/Otlp/LogsExporterFactory.php index 4a6d78263..f588cfa27 100644 --- a/src/Contrib/Otlp/LogsExporterFactory.php +++ b/src/Contrib/Otlp/LogsExporterFactory.php @@ -18,11 +18,8 @@ class LogsExporterFactory implements LogRecordExporterFactoryInterface { private const DEFAULT_COMPRESSION = 'none'; - private ?TransportFactoryInterface $transportFactory; - - public function __construct(?TransportFactoryInterface $transportFactory = null) + public function __construct(private ?TransportFactoryInterface $transportFactory = null) { - $this->transportFactory = $transportFactory; } /** diff --git a/src/Contrib/Otlp/MetricConverter.php b/src/Contrib/Otlp/MetricConverter.php index 584c41365..ba3a0b42b 100644 --- a/src/Contrib/Otlp/MetricConverter.php +++ b/src/Contrib/Otlp/MetricConverter.php @@ -132,15 +132,11 @@ private function convertMetric(SDK\Metrics\Data\Metric $metric): Metric private function convertTemporality($temporality): int { - switch ($temporality) { - case SDK\Metrics\Data\Temporality::DELTA: - return AggregationTemporality::AGGREGATION_TEMPORALITY_DELTA; - case SDK\Metrics\Data\Temporality::CUMULATIVE: - return AggregationTemporality::AGGREGATION_TEMPORALITY_CUMULATIVE; - } - - // @codeCoverageIgnoreStart - return AggregationTemporality::AGGREGATION_TEMPORALITY_UNSPECIFIED; + return match ($temporality) { + SDK\Metrics\Data\Temporality::DELTA => AggregationTemporality::AGGREGATION_TEMPORALITY_DELTA, + SDK\Metrics\Data\Temporality::CUMULATIVE => AggregationTemporality::AGGREGATION_TEMPORALITY_CUMULATIVE, + default => AggregationTemporality::AGGREGATION_TEMPORALITY_UNSPECIFIED, + }; // @codeCoverageIgnoreEnd } diff --git a/src/Contrib/Otlp/MetricExporter.php b/src/Contrib/Otlp/MetricExporter.php index efd149c7f..8025766bd 100644 --- a/src/Contrib/Otlp/MetricExporter.php +++ b/src/Contrib/Otlp/MetricExporter.php @@ -22,27 +22,19 @@ final class MetricExporter implements PushMetricExporterInterface, AggregationTemporalitySelectorInterface { use LogsMessagesTrait; - - private TransportInterface $transport; private ProtobufSerializer $serializer; - /** - * @var string|Temporality|null - */ - private $temporality; /** - * @param string|Temporality|null $temporality - * * @psalm-param TransportInterface $transport */ - public function __construct(TransportInterface $transport, $temporality = null) - { + public function __construct( + private TransportInterface $transport, + private string|Temporality|null $temporality = null, + ) { if (!class_exists('\Google\Protobuf\Api')) { throw new RuntimeException('No protobuf implementation found (ext-protobuf or google/protobuf)'); } - $this->transport = $transport; - $this->serializer = ProtobufSerializer::forTransport($transport); - $this->temporality = $temporality; + $this->serializer = ProtobufSerializer::forTransport($this->transport); } public function temporality(MetricMetadataInterface $metric) diff --git a/src/Contrib/Otlp/MetricExporterFactory.php b/src/Contrib/Otlp/MetricExporterFactory.php index e1befe65b..8a201fd53 100644 --- a/src/Contrib/Otlp/MetricExporterFactory.php +++ b/src/Contrib/Otlp/MetricExporterFactory.php @@ -19,11 +19,8 @@ class MetricExporterFactory implements MetricExporterFactoryInterface { private const DEFAULT_COMPRESSION = 'none'; - private ?TransportFactoryInterface $transportFactory; - - public function __construct(?TransportFactoryInterface $transportFactory = null) + public function __construct(private ?TransportFactoryInterface $transportFactory = null) { - $this->transportFactory = $transportFactory; } /** @@ -66,21 +63,18 @@ private function buildTransport(string $protocol): TransportInterface } /** - * @todo return string|Temporality|null (php >= 8.0) + * @phpstan-ignore-next-line */ - private function getTemporality() + private function getTemporality(): string|Temporality|null { $value = Configuration::getEnum(Variables::OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE); - switch (strtolower($value)) { - case 'cumulative': - return Temporality::CUMULATIVE; - case 'delta': - return Temporality::DELTA; - case 'lowmemory': - return null; - default: - throw new \UnexpectedValueException('Unknown temporality: ' . $value); - } + + return match (strtolower($value)) { + 'cumulative' => Temporality::CUMULATIVE, + 'delta' => Temporality::DELTA, + 'lowmemory' => null, + default => throw new \UnexpectedValueException('Unknown temporality: ' . $value), + }; } private function getCompression(): string diff --git a/src/Contrib/Otlp/OtlpHttpTransportFactory.php b/src/Contrib/Otlp/OtlpHttpTransportFactory.php index 5cf3ff9e4..637e3ae5f 100644 --- a/src/Contrib/Otlp/OtlpHttpTransportFactory.php +++ b/src/Contrib/Otlp/OtlpHttpTransportFactory.php @@ -22,7 +22,7 @@ public function create( int $maxRetries = 3, ?string $cacert = null, ?string $cert = null, - ?string $key = null + ?string $key = null, ): PsrTransport { if ($compression === self::DEFAULT_COMPRESSION) { $compression = null; diff --git a/src/Contrib/Otlp/ProtobufSerializer.php b/src/Contrib/Otlp/ProtobufSerializer.php index a8b83acb0..f8897d193 100644 --- a/src/Contrib/Otlp/ProtobufSerializer.php +++ b/src/Contrib/Otlp/ProtobufSerializer.php @@ -4,11 +4,9 @@ namespace OpenTelemetry\Contrib\Otlp; -use AssertionError; use function base64_decode; use function bin2hex; use Exception; -use function get_class; use Google\Protobuf\Descriptor; use Google\Protobuf\DescriptorPool; use Google\Protobuf\FieldDescriptor; @@ -28,25 +26,17 @@ /** * @internal - * - * @psalm-type SUPPORTED_CONTENT_TYPES = self::PROTOBUF|self::JSON|self::NDJSON + * @psalm-type SUPPORTED_CONTENT_TYPES = ContentTypes::PROTOBUF|ContentTypes::JSON|ContentTypes::NDJSON */ final class ProtobufSerializer { - private const PROTOBUF = 'application/x-protobuf'; - private const JSON = 'application/json'; - private const NDJSON = 'application/x-ndjson'; - - private string $contentType; - - private function __construct(string $contentType) + private function __construct(private string $contentType) { - $this->contentType = $contentType; } public static function getDefault(): ProtobufSerializer { - return new self(self::PROTOBUF); + return new self(ContentTypes::PROTOBUF); } /** @@ -54,75 +44,51 @@ public static function getDefault(): ProtobufSerializer */ public static function forTransport(TransportInterface $transport): ProtobufSerializer { - switch ($contentType = $transport->contentType()) { - case self::PROTOBUF: - case self::JSON: - case self::NDJSON: - return new self($contentType); - default: - throw new InvalidArgumentException(sprintf('Not supported content type "%s"', $contentType)); - } + return match ($contentType = $transport->contentType()) { + ContentTypes::PROTOBUF, ContentTypes::JSON, ContentTypes::NDJSON => new self($contentType), + default => throw new InvalidArgumentException(sprintf('Not supported content type "%s"', $contentType)), + }; } public function serializeTraceId(string $traceId): string { - switch ($this->contentType) { - case self::PROTOBUF: - return $traceId; - case self::JSON: - case self::NDJSON: - return base64_decode(bin2hex($traceId)); - default: - throw new AssertionError(); - } + // @phpstan-ignore-next-line + return match ($this->contentType) { + ContentTypes::PROTOBUF => $traceId, + ContentTypes::JSON, ContentTypes::NDJSON => base64_decode(bin2hex($traceId)), + }; } public function serializeSpanId(string $spanId): string { - switch ($this->contentType) { - case self::PROTOBUF: - return $spanId; - case self::JSON: - case self::NDJSON: - return base64_decode(bin2hex($spanId)); - default: - throw new AssertionError(); - } + // @phpstan-ignore-next-line + return match ($this->contentType) { + ContentTypes::PROTOBUF => $spanId, + ContentTypes::JSON, ContentTypes::NDJSON => base64_decode(bin2hex($spanId)), + }; } public function serialize(Message $message): string { - switch ($this->contentType) { - case self::PROTOBUF: - return $message->serializeToString(); - case self::JSON: - return self::postProcessJsonEnumValues($message, $message->serializeToJsonString()); - case self::NDJSON: - return self::postProcessJsonEnumValues($message, $message->serializeToJsonString()) . "\n"; - default: - throw new AssertionError(); - } + // @phpstan-ignore-next-line + return match ($this->contentType) { + ContentTypes::PROTOBUF => $message->serializeToString(), + ContentTypes::JSON => self::postProcessJsonEnumValues($message, $message->serializeToJsonString()), + ContentTypes::NDJSON => self::postProcessJsonEnumValues($message, $message->serializeToJsonString()) . "\n", + }; } /** + * @phan-suppress PhanParamTooManyInternal (@see https://github.com/phan/phan/pull/4840) * @throws Exception */ public function hydrate(Message $message, string $payload): void { - switch ($this->contentType) { - case self::PROTOBUF: - $message->mergeFromString($payload); - - break; - case self::JSON: - case self::NDJSON: - // @phan-suppress-next-line PhanParamTooManyInternal - $message->mergeFromJsonString($payload, true); - - break; - default: - throw new AssertionError(); - } + // @phpstan-ignore-next-line + match ($this->contentType) { + ContentTypes::PROTOBUF => $message->mergeFromString($payload), + ContentTypes::JSON, ContentTypes::NDJSON => $message->mergeFromJsonString($payload, true), + }; } /** @@ -137,7 +103,7 @@ public function hydrate(Message $message, string $payload): void private static function postProcessJsonEnumValues(Message $message, string $payload): string { $pool = DescriptorPool::getGeneratedPool(); - $desc = $pool->getDescriptorByClassName(get_class($message)); + $desc = $pool->getDescriptorByClassName($message::class); if (!$desc instanceof Descriptor) { return $payload; } diff --git a/src/Contrib/Otlp/SpanConverter.php b/src/Contrib/Otlp/SpanConverter.php index cab84cbd5..fba1e9727 100644 --- a/src/Contrib/Otlp/SpanConverter.php +++ b/src/Contrib/Otlp/SpanConverter.php @@ -121,15 +121,14 @@ private function setAttributes($pElement, AttributesInterface $attributes): void private function convertSpanKind(int $kind): int { - switch ($kind) { - case API\SpanKind::KIND_INTERNAL: return SpanKind::SPAN_KIND_INTERNAL; - case API\SpanKind::KIND_CLIENT: return SpanKind::SPAN_KIND_CLIENT; - case API\SpanKind::KIND_SERVER: return SpanKind::SPAN_KIND_SERVER; - case API\SpanKind::KIND_PRODUCER: return SpanKind::SPAN_KIND_PRODUCER; - case API\SpanKind::KIND_CONSUMER: return SpanKind::SPAN_KIND_CONSUMER; - } - - return SpanKind::SPAN_KIND_UNSPECIFIED; + return match ($kind) { + API\SpanKind::KIND_INTERNAL => SpanKind::SPAN_KIND_INTERNAL, + API\SpanKind::KIND_CLIENT => SpanKind::SPAN_KIND_CLIENT, + API\SpanKind::KIND_SERVER => SpanKind::SPAN_KIND_SERVER, + API\SpanKind::KIND_PRODUCER => SpanKind::SPAN_KIND_PRODUCER, + API\SpanKind::KIND_CONSUMER => SpanKind::SPAN_KIND_CONSUMER, + default => SpanKind::SPAN_KIND_UNSPECIFIED, + }; } private function convertStatusCode(string $status): int diff --git a/src/Contrib/Otlp/SpanExporter.php b/src/Contrib/Otlp/SpanExporter.php index a496206f4..f8e8b28e4 100644 --- a/src/Contrib/Otlp/SpanExporter.php +++ b/src/Contrib/Otlp/SpanExporter.php @@ -19,20 +19,17 @@ final class SpanExporter implements SpanExporterInterface { use LogsMessagesTrait; - - private TransportInterface $transport; private ProtobufSerializer $serializer; /** * @psalm-param TransportInterface $transport */ - public function __construct(TransportInterface $transport) + public function __construct(private TransportInterface $transport) { if (!class_exists('\Google\Protobuf\Api')) { throw new RuntimeException('No protobuf implementation found (ext-protobuf or google/protobuf)'); } - $this->transport = $transport; - $this->serializer = ProtobufSerializer::forTransport($transport); + $this->serializer = ProtobufSerializer::forTransport($this->transport); } public function export(iterable $batch, ?CancellationInterface $cancellation = null): FutureInterface diff --git a/src/Contrib/Otlp/SpanExporterFactory.php b/src/Contrib/Otlp/SpanExporterFactory.php index 667f79a5b..67627a7b9 100644 --- a/src/Contrib/Otlp/SpanExporterFactory.php +++ b/src/Contrib/Otlp/SpanExporterFactory.php @@ -19,13 +19,10 @@ class SpanExporterFactory implements SpanExporterFactoryInterface { use LogsMessagesTrait; - private ?TransportFactoryInterface $transportFactory; - private const DEFAULT_COMPRESSION = 'none'; - public function __construct(?TransportFactoryInterface $transportFactory = null) + public function __construct(private ?TransportFactoryInterface $transportFactory = null) { - $this->transportFactory = $transportFactory; } /** diff --git a/src/Contrib/Otlp/composer.json b/src/Contrib/Otlp/composer.json index e4e2604eb..519a09a63 100644 --- a/src/Contrib/Otlp/composer.json +++ b/src/Contrib/Otlp/composer.json @@ -17,7 +17,7 @@ } ], "require": { - "php": "^7.4 || ^8.0", + "php": "^8.0", "php-http/discovery": "^1.14", "open-telemetry/gen-otlp-protobuf": "^1.1", "open-telemetry/api": "^1.0", diff --git a/src/Contrib/Zipkin/Exporter.php b/src/Contrib/Zipkin/Exporter.php index 78608bdc5..ef5298c00 100644 --- a/src/Contrib/Zipkin/Exporter.php +++ b/src/Contrib/Zipkin/Exporter.php @@ -23,13 +23,10 @@ class Exporter implements SpanExporterInterface use LogsMessagesTrait; use UsesSpanConverterTrait; - private TransportInterface $transport; - public function __construct( - TransportInterface $transport, - SpanConverterInterface $spanConverter = null + private TransportInterface $transport, + SpanConverterInterface $spanConverter = null, ) { - $this->transport = $transport; $this->setSpanConverter($spanConverter ?? new SpanConverter()); } diff --git a/src/Contrib/Zipkin/SpanConverter.php b/src/Contrib/Zipkin/SpanConverter.php index a8ed3471e..9f00d514a 100644 --- a/src/Contrib/Zipkin/SpanConverter.php +++ b/src/Contrib/Zipkin/SpanConverter.php @@ -171,20 +171,14 @@ private function convertSpan(SpanDataInterface $span): array private static function toSpanKind(SpanDataInterface $span): ?string { - switch ($span->getKind()) { - case SpanKind::KIND_SERVER: - return ZipkinSpanKind::SERVER; - case SpanKind::KIND_CLIENT: - return ZipkinSpanKind::CLIENT; - case SpanKind::KIND_PRODUCER: - return ZipkinSpanKind::PRODUCER; - case SpanKind::KIND_CONSUMER: - return ZipkinSpanKind::CONSUMER; - case SpanKind::KIND_INTERNAL: - return null; - } - - return null; + return match ($span->getKind()) { + SpanKind::KIND_SERVER => ZipkinSpanKind::SERVER, + SpanKind::KIND_CLIENT => ZipkinSpanKind::CLIENT, + SpanKind::KIND_PRODUCER => ZipkinSpanKind::PRODUCER, + SpanKind::KIND_CONSUMER => ZipkinSpanKind::CONSUMER, + SpanKind::KIND_INTERNAL => null, + default => null, + }; } private static function toAnnotation(EventInterface $event): array @@ -231,17 +225,15 @@ private static function toRemoteEndpoint(SpanDataInterface $span): ?array return null; } - switch ($key) { - case SpanConverter::NET_PEER_IP_KEY: - return SpanConverter::getRemoteEndpointDataFromIpAddressAndPort( - $value, - SpanConverter::getPortNumberFromSpanAttributes($span) - ); - default: - return [ - 'serviceName' => $value, - ]; - } + return match ($key) { + SpanConverter::NET_PEER_IP_KEY => SpanConverter::getRemoteEndpointDataFromIpAddressAndPort( + $value, + SpanConverter::getPortNumberFromSpanAttributes($span) + ), + default => [ + 'serviceName' => $value, + ], + }; } private static function findRemoteEndpointPreferredAttribute(SpanDataInterface $span): ?array diff --git a/src/Contrib/Zipkin/composer.json b/src/Contrib/Zipkin/composer.json index 6db63d782..4eb7604b5 100644 --- a/src/Contrib/Zipkin/composer.json +++ b/src/Contrib/Zipkin/composer.json @@ -17,7 +17,7 @@ } ], "require": { - "php": "^7.4 || ^8.0", + "php": "^8.0", "open-telemetry/api": "^1.0", "open-telemetry/sdk": "^1.0", "php-http/async-client-implementation": "^1.0", diff --git a/src/Contrib/composer.json b/src/Contrib/composer.json index 28277dc55..603aaeb5f 100644 --- a/src/Contrib/composer.json +++ b/src/Contrib/composer.json @@ -11,7 +11,7 @@ } ], "require": { - "php": "^7.4 || ^8.0", + "php": "^8.0", "ext-json": "*", "open-telemetry/api": "^1.0", "open-telemetry/context": "^1.0", @@ -23,7 +23,6 @@ "psr/http-factory-implementation": "^1.0", "psr/log": "^1.1|^2.0|^3.0", "symfony/polyfill-mbstring": "^1.23", - "symfony/polyfill-php80": "^1.26", "symfony/polyfill-php81": "^1.26", "symfony/polyfill-php82": "^1.26" }, diff --git a/src/Extension/Propagator/B3/B3Propagator.php b/src/Extension/Propagator/B3/B3Propagator.php index 841c5c96c..d796049f6 100644 --- a/src/Extension/Propagator/B3/B3Propagator.php +++ b/src/Extension/Propagator/B3/B3Propagator.php @@ -18,11 +18,8 @@ */ final class B3Propagator implements TextMapPropagatorInterface { - private TextMapPropagatorInterface $propagator; - - private function __construct(TextMapPropagatorInterface $propagator) + private function __construct(private TextMapPropagatorInterface $propagator) { - $this->propagator = $propagator; } public static function getB3SingleHeaderInstance(): self diff --git a/src/Extension/Propagator/B3/composer.json b/src/Extension/Propagator/B3/composer.json index f15cd74c3..c7c094c52 100644 --- a/src/Extension/Propagator/B3/composer.json +++ b/src/Extension/Propagator/B3/composer.json @@ -17,7 +17,7 @@ } ], "require": { - "php": "^7.4 || ^8.0", + "php": "^8.0", "open-telemetry/api": "^1.0", "open-telemetry/context": "^1.0" }, diff --git a/src/Extension/Propagator/CloudTrace/CloudTraceFormatter.php b/src/Extension/Propagator/CloudTrace/CloudTraceFormatter.php index c03a18e89..1309cfddc 100644 --- a/src/Extension/Propagator/CloudTrace/CloudTraceFormatter.php +++ b/src/Extension/Propagator/CloudTrace/CloudTraceFormatter.php @@ -20,9 +20,6 @@ final class CloudTraceFormatter /** * Generate a SpanContext object from the Trace Context header - * - * @param string $header - * @return SpanContextInterface */ public static function deserialize(string $header) : SpanContextInterface { @@ -47,9 +44,6 @@ public static function deserialize(string $header) : SpanContextInterface /** * Convert a SpanContextInterface to header string - * - * @param SpanContextInterface $context - * @return string */ public static function serialize(SpanContextInterface $context) : string { diff --git a/src/Extension/Propagator/CloudTrace/CloudTracePropagator.php b/src/Extension/Propagator/CloudTrace/CloudTracePropagator.php index 8bb062eba..60d59a1c9 100644 --- a/src/Extension/Propagator/CloudTrace/CloudTracePropagator.php +++ b/src/Extension/Propagator/CloudTrace/CloudTracePropagator.php @@ -46,11 +46,8 @@ public static function getInstance(): TextMapPropagatorInterface self::XCLOUD, ]; - private bool $oneWay; - - private function __construct(bool $oneWay) + private function __construct(private bool $oneWay) { - $this->oneWay = $oneWay; } /** {@inheritdoc} */ diff --git a/src/Extension/Propagator/CloudTrace/composer.json b/src/Extension/Propagator/CloudTrace/composer.json index e571d954e..216f730c8 100644 --- a/src/Extension/Propagator/CloudTrace/composer.json +++ b/src/Extension/Propagator/CloudTrace/composer.json @@ -17,7 +17,7 @@ } ], "require": { - "php": "^7.4 || ^8.0", + "php": "^8.0", "open-telemetry/api": "^1.0", "open-telemetry/context": "^1.0" }, diff --git a/src/Extension/Propagator/Jaeger/JaegerBaggagePropagator.php b/src/Extension/Propagator/Jaeger/JaegerBaggagePropagator.php index 3a2ba76e1..a7a2b6c9b 100644 --- a/src/Extension/Propagator/Jaeger/JaegerBaggagePropagator.php +++ b/src/Extension/Propagator/Jaeger/JaegerBaggagePropagator.php @@ -73,7 +73,7 @@ public function extract($carrier, PropagationGetterInterface $getter = null, Con $baggageBuilder = Baggage::getBuilder(); foreach ($baggageKeys as $key) { - if (strpos($key, self::UBER_BAGGAGE_HEADER_PREFIX) === 0) { + if (str_starts_with($key, self::UBER_BAGGAGE_HEADER_PREFIX)) { $baggageKey = substr($key, strlen(self::UBER_BAGGAGE_HEADER_PREFIX)); $value = $getter->get($carrier, $key) ?? ''; $baggageBuilder->set($baggageKey, rawurldecode($value)); diff --git a/src/SDK/Common/Adapter/HttpDiscovery/DependencyResolver.php b/src/SDK/Common/Adapter/HttpDiscovery/DependencyResolver.php index 8ba992f9a..057e4434d 100644 --- a/src/SDK/Common/Adapter/HttpDiscovery/DependencyResolver.php +++ b/src/SDK/Common/Adapter/HttpDiscovery/DependencyResolver.php @@ -26,7 +26,7 @@ final class DependencyResolver implements DependencyResolverInterface public function __construct( ?MessageFactoryResolverInterface $messageFactoryResolver = null, ?PsrClientResolverInterface $psrClientResolver = null, - ?HttpPlugClientResolverInterface $httpPlugClientResolver = null + ?HttpPlugClientResolverInterface $httpPlugClientResolver = null, ) { $this->messageFactoryResolver = $messageFactoryResolver ?? MessageFactoryResolver::create(); $this->psrClientResolver = $psrClientResolver ?? PsrClientResolver::create(); @@ -36,7 +36,7 @@ public function __construct( public static function create( ?MessageFactoryResolverInterface $messageFactoryResolver = null, ?PsrClientResolverInterface $psrClientResolver = null, - ?HttpPlugClientResolverInterface $httpPlugClientResolver = null + ?HttpPlugClientResolverInterface $httpPlugClientResolver = null, ): self { return new self($messageFactoryResolver, $psrClientResolver, $httpPlugClientResolver); } diff --git a/src/SDK/Common/Adapter/HttpDiscovery/HttpPlugClientResolver.php b/src/SDK/Common/Adapter/HttpDiscovery/HttpPlugClientResolver.php index 9751984ee..d297a1b13 100644 --- a/src/SDK/Common/Adapter/HttpDiscovery/HttpPlugClientResolver.php +++ b/src/SDK/Common/Adapter/HttpDiscovery/HttpPlugClientResolver.php @@ -10,11 +10,8 @@ final class HttpPlugClientResolver implements ResolverInterface { - private ?HttpAsyncClient $httpAsyncClient; - - public function __construct(?HttpAsyncClient $httpAsyncClient = null) + public function __construct(private ?HttpAsyncClient $httpAsyncClient = null) { - $this->httpAsyncClient = $httpAsyncClient; } public static function create(?HttpAsyncClient $httpAsyncClient = null): self diff --git a/src/SDK/Common/Adapter/HttpDiscovery/MessageFactoryResolver.php b/src/SDK/Common/Adapter/HttpDiscovery/MessageFactoryResolver.php index 6ed0895ff..ae4028b61 100644 --- a/src/SDK/Common/Adapter/HttpDiscovery/MessageFactoryResolver.php +++ b/src/SDK/Common/Adapter/HttpDiscovery/MessageFactoryResolver.php @@ -15,27 +15,14 @@ final class MessageFactoryResolver implements FactoryResolverInterface { - private ?RequestFactoryInterface $requestFactory; - private ?ResponseFactoryInterface $responseFactory; - private ?ServerRequestFactoryInterface $serverRequestFactory; - private ?StreamFactoryInterface $streamFactory; - private ?UploadedFileFactoryInterface $uploadedFileFactory; - private ?UriFactoryInterface $uriFactory; - public function __construct( - ?RequestFactoryInterface $requestFactory = null, - ?ResponseFactoryInterface $responseFactory = null, - ?ServerRequestFactoryInterface $serverRequestFactory = null, - ?StreamFactoryInterface $streamFactory = null, - ?UploadedFileFactoryInterface $uploadedFileFactory = null, - ?UriFactoryInterface $uriFactory = null + private ?RequestFactoryInterface $requestFactory = null, + private ?ResponseFactoryInterface $responseFactory = null, + private ?ServerRequestFactoryInterface $serverRequestFactory = null, + private ?StreamFactoryInterface $streamFactory = null, + private ?UploadedFileFactoryInterface $uploadedFileFactory = null, + private ?UriFactoryInterface $uriFactory = null, ) { - $this->requestFactory = $requestFactory; - $this->responseFactory = $responseFactory; - $this->serverRequestFactory = $serverRequestFactory; - $this->streamFactory = $streamFactory; - $this->uploadedFileFactory = $uploadedFileFactory; - $this->uriFactory = $uriFactory; } public static function create( @@ -44,7 +31,7 @@ public static function create( ?ServerRequestFactoryInterface $serverRequestFactory = null, ?StreamFactoryInterface $streamFactory = null, ?UploadedFileFactoryInterface $uploadedFileFactory = null, - ?UriFactoryInterface $uriFactory = null + ?UriFactoryInterface $uriFactory = null, ): self { return new self( $requestFactory, diff --git a/src/SDK/Common/Adapter/HttpDiscovery/PsrClientResolver.php b/src/SDK/Common/Adapter/HttpDiscovery/PsrClientResolver.php index 46fb36312..1a362c91d 100644 --- a/src/SDK/Common/Adapter/HttpDiscovery/PsrClientResolver.php +++ b/src/SDK/Common/Adapter/HttpDiscovery/PsrClientResolver.php @@ -10,11 +10,8 @@ final class PsrClientResolver implements ResolverInterface { - private ?ClientInterface $client; - - public function __construct(?ClientInterface $client = null) + public function __construct(private ?ClientInterface $client = null) { - $this->client = $client; } public static function create(?ClientInterface $client = null): self diff --git a/src/SDK/Common/Attribute/Attributes.php b/src/SDK/Common/Attribute/Attributes.php index bb131ce94..cebf063fd 100644 --- a/src/SDK/Common/Attribute/Attributes.php +++ b/src/SDK/Common/Attribute/Attributes.php @@ -10,16 +10,13 @@ final class Attributes implements AttributesInterface, IteratorAggregate { - private array $attributes; - private int $droppedAttributesCount; - /** * @internal */ - public function __construct(array $attributes, int $droppedAttributesCount) - { - $this->attributes = $attributes; - $this->droppedAttributesCount = $droppedAttributesCount; + public function __construct( + private array $attributes, + private int $droppedAttributesCount, + ) { } public static function create(iterable $attributes): AttributesInterface diff --git a/src/SDK/Common/Attribute/AttributesBuilder.php b/src/SDK/Common/Attribute/AttributesBuilder.php index ee855b34a..cd3232a46 100644 --- a/src/SDK/Common/Attribute/AttributesBuilder.php +++ b/src/SDK/Common/Attribute/AttributesBuilder.php @@ -17,24 +17,15 @@ final class AttributesBuilder implements AttributesBuilderInterface { use LogsMessagesTrait; - - private array $attributes; - private ?int $attributeCountLimit; - private ?int $attributeValueLengthLimit; - private int $droppedAttributesCount; private AttributeValidatorInterface $attributeValidator; public function __construct( - array $attributes, - ?int $attributeCountLimit, - ?int $attributeValueLengthLimit, - int $droppedAttributesCount, - ?AttributeValidatorInterface $attributeValidator + private array $attributes, + private ?int $attributeCountLimit, + private ?int $attributeValueLengthLimit, + private int $droppedAttributesCount, + ?AttributeValidatorInterface $attributeValidator, ) { - $this->attributes = $attributes; - $this->attributeCountLimit = $attributeCountLimit; - $this->attributeValueLengthLimit = $attributeValueLengthLimit; - $this->droppedAttributesCount = $droppedAttributesCount; $this->attributeValidator = $attributeValidator ?? new AttributeValidator(); } diff --git a/src/SDK/Common/Attribute/AttributesFactory.php b/src/SDK/Common/Attribute/AttributesFactory.php index d53ab25aa..8e072c7ab 100644 --- a/src/SDK/Common/Attribute/AttributesFactory.php +++ b/src/SDK/Common/Attribute/AttributesFactory.php @@ -9,13 +9,10 @@ */ final class AttributesFactory implements AttributesFactoryInterface { - private ?int $attributeCountLimit; - private ?int $attributeValueLengthLimit; - - public function __construct(?int $attributeCountLimit = null, ?int $attributeValueLengthLimit = null) - { - $this->attributeCountLimit = $attributeCountLimit; - $this->attributeValueLengthLimit = $attributeValueLengthLimit; + public function __construct( + private ?int $attributeCountLimit = null, + private ?int $attributeValueLengthLimit = null, + ) { } public function builder(iterable $attributes = [], ?AttributeValidatorInterface $attributeValidator = null): AttributesBuilderInterface diff --git a/src/SDK/Common/Attribute/FilteredAttributesBuilder.php b/src/SDK/Common/Attribute/FilteredAttributesBuilder.php index 28bb00905..a0269ea49 100644 --- a/src/SDK/Common/Attribute/FilteredAttributesBuilder.php +++ b/src/SDK/Common/Attribute/FilteredAttributesBuilder.php @@ -11,17 +11,15 @@ */ final class FilteredAttributesBuilder implements AttributesBuilderInterface { - private AttributesBuilderInterface $builder; - private array $rejectedKeys; private int $rejected = 0; /** * @param list $rejectedKeys */ - public function __construct(AttributesBuilderInterface $builder, array $rejectedKeys) - { - $this->builder = $builder; - $this->rejectedKeys = $rejectedKeys; + public function __construct( + private AttributesBuilderInterface $builder, + private array $rejectedKeys, + ) { } public function __clone() diff --git a/src/SDK/Common/Attribute/FilteredAttributesFactory.php b/src/SDK/Common/Attribute/FilteredAttributesFactory.php index 1d9c4ae1c..fca0ce492 100644 --- a/src/SDK/Common/Attribute/FilteredAttributesFactory.php +++ b/src/SDK/Common/Attribute/FilteredAttributesFactory.php @@ -9,16 +9,13 @@ */ final class FilteredAttributesFactory implements AttributesFactoryInterface { - private AttributesFactoryInterface $factory; - private array $rejectedKeys; - /** * @param list $rejectedKeys */ - public function __construct(AttributesFactoryInterface $factory, array $rejectedKeys) - { - $this->factory = $factory; - $this->rejectedKeys = $rejectedKeys; + public function __construct( + private AttributesFactoryInterface $factory, + private array $rejectedKeys, + ) { } public function builder(iterable $attributes = [], ?AttributeValidatorInterface $attributeValidator = null): AttributesBuilderInterface diff --git a/src/SDK/Common/Configuration/Configuration.php b/src/SDK/Common/Configuration/Configuration.php index 58673fd98..577c85708 100644 --- a/src/SDK/Common/Configuration/Configuration.php +++ b/src/SDK/Common/Configuration/Configuration.php @@ -61,7 +61,7 @@ public static function getBoolean(string $key, bool $default = null): bool try { return BooleanParser::parse($resolved); - } catch (InvalidArgumentException $e) { + } catch (InvalidArgumentException) { self::logWarning(sprintf('Invalid boolean value "%s" interpreted as "false" for %s', $resolved, $key)); return false; diff --git a/src/SDK/Common/Configuration/Parser/MapParser.php b/src/SDK/Common/Configuration/Parser/MapParser.php index 273d57c87..7e0d44534 100644 --- a/src/SDK/Common/Configuration/Parser/MapParser.php +++ b/src/SDK/Common/Configuration/Parser/MapParser.php @@ -34,7 +34,7 @@ public static function parse($value): array private static function validateKeyValuePair(string $pair) { - if (strpos($pair, self::KEY_VALUE_SEPARATOR) === false) { + if (!str_contains($pair, self::KEY_VALUE_SEPARATOR)) { throw new InvalidArgumentException(sprintf( 'Key-Value pair "%s" does not contain separator "%s"', $pair, diff --git a/src/SDK/Common/Dev/Compatibility/Util.php b/src/SDK/Common/Dev/Compatibility/Util.php index 1a3debfdd..fdc2930b7 100644 --- a/src/SDK/Common/Dev/Compatibility/Util.php +++ b/src/SDK/Common/Dev/Compatibility/Util.php @@ -57,7 +57,7 @@ public static function triggerClassDeprecationNotice(string $className, string $ public static function triggerMethodDeprecationNotice( string $methodName, string $alternativeMethodName = null, - string $alternativeClassName = null + string $alternativeClassName = null, ): void { if (self::getErrorLevel() === self::E_NONE) { return; diff --git a/src/SDK/Common/Exception/StackTraceFormatter.php b/src/SDK/Common/Exception/StackTraceFormatter.php index 0d0fa7cb6..8fc7a2104 100644 --- a/src/SDK/Common/Exception/StackTraceFormatter.php +++ b/src/SDK/Common/Exception/StackTraceFormatter.php @@ -6,7 +6,6 @@ use function basename; use function count; -use function get_class; use function sprintf; use function str_repeat; @@ -77,8 +76,8 @@ private static function writeFrames(string &$s, array $frames, ?array $enclosing $n = count($frames); if ($enclosing) { for ($m = count($enclosing); - $n && $m && $frames[$n - 1] === $enclosing[$m - 1]; - $n--, $m--) { + $n && $m && $frames[$n - 1] === $enclosing[$m - 1]; + $n--, $m--) { } } for ($i = 0; $i < $n; $i++) { @@ -110,7 +109,7 @@ private static function writeFrames(string &$s, array $frames, ?array $enclosing private static function writeInlineHeader(string &$s, Throwable $e): void { - $s .= self::formatName(get_class($e)); + $s .= self::formatName($e::class); if ($e->getMessage() !== '') { $s .= ': '; $s .= $e->getMessage(); diff --git a/src/SDK/Common/Export/Http/PsrTransport.php b/src/SDK/Common/Export/Http/PsrTransport.php index a53e5b80a..99530fcc1 100644 --- a/src/SDK/Common/Export/Http/PsrTransport.php +++ b/src/SDK/Common/Export/Http/PsrTransport.php @@ -30,42 +30,22 @@ */ final class PsrTransport implements TransportInterface { - private ClientInterface $client; - private RequestFactoryInterface $requestFactory; - private StreamFactoryInterface $streamFactory; - - private string $endpoint; - private string $contentType; - private array $headers; - private array $compression; - private int $retryDelay; - private int $maxRetries; - private bool $closed = false; /** * @psalm-param CONTENT_TYPE $contentType */ public function __construct( - ClientInterface $client, - RequestFactoryInterface $requestFactory, - StreamFactoryInterface $streamFactory, - string $endpoint, - string $contentType, - array $headers, - array $compression, - int $retryDelay, - int $maxRetries + private ClientInterface $client, + private RequestFactoryInterface $requestFactory, + private StreamFactoryInterface $streamFactory, + private string $endpoint, + private string $contentType, + private array $headers, + private array $compression, + private int $retryDelay, + private int $maxRetries, ) { - $this->client = $client; - $this->requestFactory = $requestFactory; - $this->streamFactory = $streamFactory; - $this->endpoint = $endpoint; - $this->contentType = $contentType; - $this->headers = $headers; - $this->compression = $compression; - $this->retryDelay = $retryDelay; - $this->maxRetries = $maxRetries; } public function contentType(): string diff --git a/src/SDK/Common/Export/Http/PsrTransportFactory.php b/src/SDK/Common/Export/Http/PsrTransportFactory.php index 5ef78d82c..200f7d1ba 100644 --- a/src/SDK/Common/Export/Http/PsrTransportFactory.php +++ b/src/SDK/Common/Export/Http/PsrTransportFactory.php @@ -16,18 +16,11 @@ final class PsrTransportFactory implements TransportFactoryInterface { - private ClientInterface $client; - private RequestFactoryInterface $requestFactory; - private StreamFactoryInterface $streamFactory; - public function __construct( - ClientInterface $client, - RequestFactoryInterface $requestFactory, - StreamFactoryInterface $streamFactory + private ClientInterface $client, + private RequestFactoryInterface $requestFactory, + private StreamFactoryInterface $streamFactory, ) { - $this->client = $client; - $this->requestFactory = $requestFactory; - $this->streamFactory = $streamFactory; } /** @@ -43,7 +36,7 @@ public function create( int $maxRetries = 3, ?string $cacert = null, ?string $cert = null, - ?string $key = null + ?string $key = null, ): PsrTransport { if (!filter_var($endpoint, FILTER_VALIDATE_URL)) { throw new InvalidArgumentException(sprintf('Invalid endpoint url "%s"', $endpoint)); diff --git a/src/SDK/Common/Export/Http/PsrUtils.php b/src/SDK/Common/Export/Http/PsrUtils.php index eaf2f3b47..7cc020818 100644 --- a/src/SDK/Common/Export/Http/PsrUtils.php +++ b/src/SDK/Common/Export/Http/PsrUtils.php @@ -75,7 +75,7 @@ public static function encode(string $value, array $encodings, ?array &$appliedE try { $value = $encoder($value); - } catch (Throwable $e) { + } catch (Throwable) { unset($encodings[$i]); } } @@ -115,7 +115,7 @@ public static function compression($compression): array if (!$compression) { return []; } - if (strpos($compression, ',') === false) { + if (!str_contains($compression, ',')) { return [$compression]; } diff --git a/src/SDK/Common/Export/Stream/StreamTransport.php b/src/SDK/Common/Export/Stream/StreamTransport.php index 4b99cf756..e22295cb6 100644 --- a/src/SDK/Common/Export/Stream/StreamTransport.php +++ b/src/SDK/Common/Export/Stream/StreamTransport.php @@ -28,20 +28,14 @@ final class StreamTransport implements TransportInterface { /** - * @var resource|null - */ - private $stream; - private string $contentType; - - /** - * @param resource $stream + * @param resource|null $stream * * @psalm-param CONTENT_TYPE $contentType */ - public function __construct($stream, string $contentType) - { - $this->stream = $stream; - $this->contentType = $contentType; + public function __construct( + private $stream, + private string $contentType, + ) { } public function contentType(): string diff --git a/src/SDK/Common/Export/Stream/StreamTransportFactory.php b/src/SDK/Common/Export/Stream/StreamTransportFactory.php index 59e411318..c6544bbe5 100644 --- a/src/SDK/Common/Export/Stream/StreamTransportFactory.php +++ b/src/SDK/Common/Export/Stream/StreamTransportFactory.php @@ -29,6 +29,7 @@ final class StreamTransportFactory implements TransportFactoryInterface * @psalm-template CONTENT_TYPE of string * @psalm-param CONTENT_TYPE $contentType * @psalm-return TransportInterface + * @throws ErrorException */ public function create( $endpoint, @@ -40,7 +41,7 @@ public function create( int $maxRetries = 3, ?string $cacert = null, ?string $cert = null, - ?string $key = null + ?string $key = null, ): TransportInterface { assert(!empty($endpoint)); $stream = is_resource($endpoint) @@ -69,7 +70,7 @@ private static function createStream( float $timeout = 10., ?string $cacert = null, ?string $cert = null, - ?string $key = null + ?string $key = null, ) { $context = stream_context_create([ 'http' => [ diff --git a/src/SDK/Common/Export/TransportFactoryInterface.php b/src/SDK/Common/Export/TransportFactoryInterface.php index 48e538443..a2dd3a1e1 100644 --- a/src/SDK/Common/Export/TransportFactoryInterface.php +++ b/src/SDK/Common/Export/TransportFactoryInterface.php @@ -27,6 +27,6 @@ public function create( int $maxRetries = 3, ?string $cacert = null, ?string $cert = null, - ?string $key = null + ?string $key = null, ): TransportInterface; } diff --git a/src/SDK/Common/Future/CompletedFuture.php b/src/SDK/Common/Future/CompletedFuture.php index 7f0cd6536..b6e01c41f 100644 --- a/src/SDK/Common/Future/CompletedFuture.php +++ b/src/SDK/Common/Future/CompletedFuture.php @@ -13,15 +13,11 @@ */ final class CompletedFuture implements FutureInterface { - /** @var T */ - private $value; - /** * @param T $value */ - public function __construct($value) + public function __construct(private $value) { - $this->value = $value; } public function await() diff --git a/src/SDK/Common/Future/ErrorFuture.php b/src/SDK/Common/Future/ErrorFuture.php index 32cf3d995..253ca803e 100644 --- a/src/SDK/Common/Future/ErrorFuture.php +++ b/src/SDK/Common/Future/ErrorFuture.php @@ -9,11 +9,8 @@ final class ErrorFuture implements FutureInterface { - private Throwable $throwable; - - public function __construct(Throwable $throwable) + public function __construct(private Throwable $throwable) { - $this->throwable = $throwable; } public function await() diff --git a/src/SDK/Common/Http/Psr/Message/MessageFactory.php b/src/SDK/Common/Http/Psr/Message/MessageFactory.php index 8e99d64c0..63aac0850 100644 --- a/src/SDK/Common/Http/Psr/Message/MessageFactory.php +++ b/src/SDK/Common/Http/Psr/Message/MessageFactory.php @@ -13,24 +13,17 @@ final class MessageFactory implements MessageFactoryInterface { - private RequestFactoryInterface $requestFactory; - private ResponseFactoryInterface $responseFactory; - private ServerRequestFactoryInterface $serverRequestFactory; - public function __construct( - RequestFactoryInterface $requestFactory, - ResponseFactoryInterface $responseFactory, - ServerRequestFactoryInterface $serverRequestFactory + private RequestFactoryInterface $requestFactory, + private ResponseFactoryInterface $responseFactory, + private ServerRequestFactoryInterface $serverRequestFactory, ) { - $this->requestFactory = $requestFactory; - $this->responseFactory = $responseFactory; - $this->serverRequestFactory = $serverRequestFactory; } public static function create( RequestFactoryInterface $requestFactory, ResponseFactoryInterface $responseFactory, - ServerRequestFactoryInterface $serverRequestFactory + ServerRequestFactoryInterface $serverRequestFactory, ): self { return new self($requestFactory, $responseFactory, $serverRequestFactory); } diff --git a/src/SDK/Common/Instrumentation/InstrumentationScope.php b/src/SDK/Common/Instrumentation/InstrumentationScope.php index ec9b52fb0..f6a009624 100644 --- a/src/SDK/Common/Instrumentation/InstrumentationScope.php +++ b/src/SDK/Common/Instrumentation/InstrumentationScope.php @@ -11,17 +11,12 @@ */ final class InstrumentationScope implements InstrumentationScopeInterface { - private string $name; - private ?string $version; - private ?string $schemaUrl; - private AttributesInterface $attributes; - - public function __construct(string $name, ?string $version, ?string $schemaUrl, AttributesInterface $attributes) - { - $this->name = $name; - $this->version = $version; - $this->schemaUrl = $schemaUrl; - $this->attributes = $attributes; + public function __construct( + private string $name, + private ?string $version, + private ?string $schemaUrl, + private AttributesInterface $attributes, + ) { } public function getName(): string diff --git a/src/SDK/Common/Instrumentation/InstrumentationScopeFactory.php b/src/SDK/Common/Instrumentation/InstrumentationScopeFactory.php index f1ae7c072..f3f73341d 100644 --- a/src/SDK/Common/Instrumentation/InstrumentationScopeFactory.php +++ b/src/SDK/Common/Instrumentation/InstrumentationScopeFactory.php @@ -8,18 +8,15 @@ final class InstrumentationScopeFactory implements InstrumentationScopeFactoryInterface { - private AttributesFactoryInterface $attributesFactory; - - public function __construct(AttributesFactoryInterface $attributesFactory) + public function __construct(private AttributesFactoryInterface $attributesFactory) { - $this->attributesFactory = $attributesFactory; } public function create( string $name, ?string $version = null, ?string $schemaUrl = null, - iterable $attributes = [] + iterable $attributes = [], ): InstrumentationScopeInterface { return new InstrumentationScope( $name, diff --git a/src/SDK/Common/Instrumentation/InstrumentationScopeFactoryInterface.php b/src/SDK/Common/Instrumentation/InstrumentationScopeFactoryInterface.php index 78292de58..ddc45eb04 100644 --- a/src/SDK/Common/Instrumentation/InstrumentationScopeFactoryInterface.php +++ b/src/SDK/Common/Instrumentation/InstrumentationScopeFactoryInterface.php @@ -10,6 +10,6 @@ public function create( string $name, ?string $version = null, ?string $schemaUrl = null, - iterable $attributes = [] + iterable $attributes = [], ): InstrumentationScopeInterface; } diff --git a/src/SDK/Common/Time/StopWatch.php b/src/SDK/Common/Time/StopWatch.php index b2abdabae..10b967e9e 100644 --- a/src/SDK/Common/Time/StopWatch.php +++ b/src/SDK/Common/Time/StopWatch.php @@ -7,17 +7,14 @@ final class StopWatch implements StopWatchInterface { private const INITIAL_ELAPSED_TIME = 0; - - private ClockInterface $clock; private bool $running = false; - private ?int $initialStartTime; private ?int $startTime = null; private ?int $stopTime = null; - public function __construct(ClockInterface $clock, ?int $initialStartTime = null) - { - $this->clock = $clock; - $this->initialStartTime = $initialStartTime; + public function __construct( + private ClockInterface $clock, + private ?int $initialStartTime = null, + ) { } public function isRunning(): bool diff --git a/src/SDK/Common/Time/StopWatchFactory.php b/src/SDK/Common/Time/StopWatchFactory.php index f60c377fc..080cdce57 100644 --- a/src/SDK/Common/Time/StopWatchFactory.php +++ b/src/SDK/Common/Time/StopWatchFactory.php @@ -9,12 +9,12 @@ final class StopWatchFactory implements StopWatchFactoryInterface private static ?StopWatchInterface $default = null; private ClockInterface $clock; - private ?int $initialStartTime; - public function __construct(?ClockInterface $clock = null, ?int $initialStartTime = null) - { + public function __construct( + ?ClockInterface $clock = null, + private ?int $initialStartTime = null, + ) { $this->clock = $clock ?? ClockFactory::getDefault(); - $this->initialStartTime = $initialStartTime; } public static function create(?ClockInterface $clock = null, ?int $initialStartTime = null): self diff --git a/src/SDK/Common/Util/ShutdownHandler.php b/src/SDK/Common/Util/ShutdownHandler.php index 2de6d47df..d748c3e81 100644 --- a/src/SDK/Common/Util/ShutdownHandler.php +++ b/src/SDK/Common/Util/ShutdownHandler.php @@ -5,16 +5,16 @@ namespace OpenTelemetry\SDK\Common\Util; use function array_key_last; -use ArrayAccess; use Closure; use function register_shutdown_function; +use WeakMap; final class ShutdownHandler { /** @var array|null */ private static ?array $handlers = null; - /** @var ArrayAccess|null */ - private static ?ArrayAccess $weakMap = null; + /** @var WeakMap|null */ + private static ?WeakMap $weakMap = null; private array $ids = []; @@ -56,7 +56,7 @@ public static function register(callable $shutdownFunction): void return; } - self::$weakMap ??= WeakMap::create(); + self::$weakMap ??= new WeakMap(); $handler = self::$weakMap[$object] ??= new self(); $handler->ids[] = array_key_last(self::$handlers); } diff --git a/src/SDK/Common/Util/WeakMap.php b/src/SDK/Common/Util/WeakMap.php deleted file mode 100644 index 3b62d6d64..000000000 --- a/src/SDK/Common/Util/WeakMap.php +++ /dev/null @@ -1,175 +0,0 @@ - - */ - private array $objects = []; - - private function __construct() - { - } - - /** - * @return ArrayAccess&Countable&IteratorAggregate - */ - public static function create(): ArrayAccess - { - if (PHP_VERSION_ID >= 80000) { - /** @phan-suppress-next-line PhanUndeclaredClassReference */ - assert(class_exists(\WeakMap::class, false)); - /** @phan-suppress-next-line PhanUndeclaredClassMethod */ - $map = new \WeakMap(); - assert($map instanceof ArrayAccess); - assert($map instanceof Countable); - assert($map instanceof IteratorAggregate); - - return $map; - } - - return new self(); - } - - public function offsetExists($offset): bool - { - if (!is_object($offset)) { - throw new TypeError('WeakMap key must be an object'); - } - - return isset($offset->{self::KEY}[spl_object_id($this)]); - } - - /** - * @phan-suppress PhanUndeclaredClassAttribute - */ - #[\ReturnTypeWillChange] - public function offsetGet($offset) - { - if (!is_object($offset)) { - throw new TypeError('WeakMap key must be an object'); - } - if (!$this->contains($offset)) { - throw new Error(sprintf('Object %s#%d not contained in WeakMap', get_class($offset), spl_object_id($offset))); - } - - return $offset->{self::KEY}[spl_object_id($this)]; - } - - public function offsetSet($offset, $value): void - { - if ($offset === null) { - throw new Error('Cannot append to WeakMap'); - } - if (!is_object($offset)) { - throw new TypeError('WeakMap key must be an object'); - } - if (!$this->contains($offset)) { - $this->expunge(); - } - - $offset->{self::KEY}[spl_object_id($this)] = $value; - $this->objects[spl_object_id($offset)] = WeakReference::create($offset); - } - - public function offsetUnset($offset): void - { - if (!is_object($offset)) { - throw new TypeError('WeakMap key must be an object'); - } - if (!$this->contains($offset)) { - return; - } - - unset( - $offset->{self::KEY}[spl_object_id($this)], - $this->objects[spl_object_id($offset)], - ); - if (!$offset->{self::KEY}) { - unset($offset->{self::KEY}); - } - } - - public function count(): int - { - $this->expunge(); - - return count($this->objects); - } - - public function getIterator(): Traversable - { - $this->expunge(); - - foreach ($this->objects as $reference) { - if (($object = $reference->get()) && $this->contains($object)) { - yield $object => $this[$object]; - } - } - } - - public function __debugInfo(): array - { - $debugInfo = []; - foreach ($this as $key => $value) { - $debugInfo[] = ['key' => $key, 'value' => $value]; - } - - return $debugInfo; - } - - public function __destruct() - { - foreach ($this->objects as $reference) { - if ($object = $reference->get()) { - unset($this[$object]); - } - } - } - - private function contains(object $offset): bool - { - $reference = $this->objects[spl_object_id($offset)] ?? null; - if ($reference && $reference->get() === $offset) { - return true; - } - - unset($this->objects[spl_object_id($offset)]); - - return false; - } - - private function expunge(): void - { - foreach ($this->objects as $id => $reference) { - if (!$reference->get()) { - unset($this->objects[$id]); - } - } - } -} diff --git a/src/SDK/Common/Util/functions.php b/src/SDK/Common/Util/functions.php index f4fb13b80..dcda96241 100644 --- a/src/SDK/Common/Util/functions.php +++ b/src/SDK/Common/Util/functions.php @@ -5,7 +5,6 @@ namespace OpenTelemetry\SDK\Common\Util; use Closure; -use function get_class; use ReflectionFunction; use stdClass; use WeakReference; @@ -46,7 +45,7 @@ function weaken(Closure $closure, ?object &$target = null): Closure $ref = WeakReference::create($target); /** @psalm-suppress PossiblyInvalidFunctionCall */ - return $scope && get_class($target) === $scope->name && !$scope->isInternal() + return $scope && $target::class === $scope->name && !$scope->isInternal() ? static fn (...$args) => ($obj = $ref->get()) ? $closure->call($obj, ...$args) : null : static fn (...$args) => ($obj = $ref->get()) ? $closure->bindTo($obj)(...$args) : null; } diff --git a/src/SDK/Logs/Exporter/ConsoleExporter.php b/src/SDK/Logs/Exporter/ConsoleExporter.php index e34fa308c..500fe6e1a 100644 --- a/src/SDK/Logs/Exporter/ConsoleExporter.php +++ b/src/SDK/Logs/Exporter/ConsoleExporter.php @@ -19,11 +19,8 @@ */ class ConsoleExporter implements LogRecordExporterInterface { - private TransportInterface $transport; - - public function __construct(TransportInterface $transport) + public function __construct(private TransportInterface $transport) { - $this->transport = $transport; } /** diff --git a/src/SDK/Logs/LogRecordLimits.php b/src/SDK/Logs/LogRecordLimits.php index 9f71e62ee..70d87e13a 100644 --- a/src/SDK/Logs/LogRecordLimits.php +++ b/src/SDK/Logs/LogRecordLimits.php @@ -11,15 +11,11 @@ */ class LogRecordLimits { - private AttributesFactoryInterface $attributesFactory; - /** * @internal Use {@see SpanLimitsBuilder} to create {@see SpanLimits} instance. */ - public function __construct( - AttributesFactoryInterface $attributesFactory - ) { - $this->attributesFactory = $attributesFactory; + public function __construct(private AttributesFactoryInterface $attributesFactory) + { } public function getAttributeFactory(): AttributesFactoryInterface diff --git a/src/SDK/Logs/LogRecordProcessorFactory.php b/src/SDK/Logs/LogRecordProcessorFactory.php index dec463735..869345cce 100644 --- a/src/SDK/Logs/LogRecordProcessorFactory.php +++ b/src/SDK/Logs/LogRecordProcessorFactory.php @@ -26,37 +26,29 @@ public function create(LogRecordExporterInterface $exporter, ?MeterProviderInter $processors[] = $this->createProcessor($name, $exporter, $meterProvider); } - switch (count($processors)) { - case 0: - return NoopLogRecordProcessor::getInstance(); - case 1: - return $processors[0]; - default: - return new MultiLogRecordProcessor($processors); - } + return match (count($processors)) { + 0 => NoopLogRecordProcessor::getInstance(), + 1 => $processors[0], + default => new MultiLogRecordProcessor($processors), + }; } private function createProcessor(string $name, LogRecordExporterInterface $exporter, ?MeterProviderInterface $meterProvider = null): LogRecordProcessorInterface { - switch ($name) { - case KnownValues::VALUE_BATCH: - return new BatchLogRecordProcessor( - $exporter, - ClockFactory::getDefault(), - Configuration::getInt(Variables::OTEL_BLRP_MAX_QUEUE_SIZE), - Configuration::getInt(Variables::OTEL_BLRP_SCHEDULE_DELAY), - Configuration::getInt(Variables::OTEL_BLRP_EXPORT_TIMEOUT), - Configuration::getInt(Variables::OTEL_BLRP_MAX_EXPORT_BATCH_SIZE), - true, - $meterProvider, - ); - case KnownValues::VALUE_SIMPLE: - return new SimpleLogRecordProcessor($exporter); - case Values::VALUE_NOOP: - case Values::VALUE_NONE: - return NoopLogRecordProcessor::getInstance(); - default: - throw new InvalidArgumentException('Unknown processor: ' . $name); - } + return match ($name) { + KnownValues::VALUE_BATCH => new BatchLogRecordProcessor( + $exporter, + ClockFactory::getDefault(), + Configuration::getInt(Variables::OTEL_BLRP_MAX_QUEUE_SIZE), + Configuration::getInt(Variables::OTEL_BLRP_SCHEDULE_DELAY), + Configuration::getInt(Variables::OTEL_BLRP_EXPORT_TIMEOUT), + Configuration::getInt(Variables::OTEL_BLRP_MAX_EXPORT_BATCH_SIZE), + true, + $meterProvider, + ), + KnownValues::VALUE_SIMPLE => new SimpleLogRecordProcessor($exporter), + Values::VALUE_NOOP, Values::VALUE_NONE => NoopLogRecordProcessor::getInstance(), + default => throw new InvalidArgumentException('Unknown processor: ' . $name), + }; } } diff --git a/src/SDK/Logs/Logger.php b/src/SDK/Logs/Logger.php index 0b8db152d..ff2d40cb5 100644 --- a/src/SDK/Logs/Logger.php +++ b/src/SDK/Logs/Logger.php @@ -16,13 +16,10 @@ */ class Logger implements LoggerInterface { - private InstrumentationScopeInterface $scope; - private LoggerSharedState $loggerSharedState; - - public function __construct(LoggerSharedState $loggerSharedState, InstrumentationScopeInterface $scope) - { - $this->loggerSharedState = $loggerSharedState; - $this->scope = $scope; + public function __construct( + private LoggerSharedState $loggerSharedState, + private InstrumentationScopeInterface $scope, + ) { } public function emit(LogRecord $logRecord): void diff --git a/src/SDK/Logs/LoggerProvider.php b/src/SDK/Logs/LoggerProvider.php index f0a8266c1..f06cdbebf 100644 --- a/src/SDK/Logs/LoggerProvider.php +++ b/src/SDK/Logs/LoggerProvider.php @@ -14,16 +14,17 @@ class LoggerProvider implements LoggerProviderInterface { private LoggerSharedState $loggerSharedState; - private InstrumentationScopeFactoryInterface $instrumentationScopeFactory; - public function __construct(LogRecordProcessorInterface $processor, InstrumentationScopeFactoryInterface $instrumentationScopeFactory, ?ResourceInfo $resource = null) - { + public function __construct( + LogRecordProcessorInterface $processor, + private InstrumentationScopeFactoryInterface $instrumentationScopeFactory, + ?ResourceInfo $resource = null, + ) { $this->loggerSharedState = new LoggerSharedState( $resource ?? ResourceInfoFactory::defaultResource(), (new LogRecordLimitsBuilder())->build(), $processor ); - $this->instrumentationScopeFactory = $instrumentationScopeFactory; } /** diff --git a/src/SDK/Logs/LoggerProviderBuilder.php b/src/SDK/Logs/LoggerProviderBuilder.php index 37c56245c..456f3f804 100644 --- a/src/SDK/Logs/LoggerProviderBuilder.php +++ b/src/SDK/Logs/LoggerProviderBuilder.php @@ -43,13 +43,10 @@ public function build(): LoggerProviderInterface private function buildProcessor(): LogRecordProcessorInterface { - switch (count($this->processors)) { - case 0: - return NoopLogRecordProcessor::getInstance(); - case 1: - return $this->processors[0]; - default: - return new MultiLogRecordProcessor($this->processors); - } + return match (count($this->processors)) { + 0 => NoopLogRecordProcessor::getInstance(), + 1 => $this->processors[0], + default => new MultiLogRecordProcessor($this->processors), + }; } } diff --git a/src/SDK/Logs/LoggerSharedState.php b/src/SDK/Logs/LoggerSharedState.php index aeeb45518..d6842fb11 100644 --- a/src/SDK/Logs/LoggerSharedState.php +++ b/src/SDK/Logs/LoggerSharedState.php @@ -9,20 +9,15 @@ class LoggerSharedState { - private ResourceInfo $resource; - private LogRecordProcessorInterface $processor; - private LogRecordLimits $limits; private ?bool $shutdownResult = null; public function __construct( - ResourceInfo $resource, - LogRecordLimits $limits, - LogRecordProcessorInterface $processor + private ResourceInfo $resource, + private LogRecordLimits $limits, + private LogRecordProcessorInterface $processor, ) { - $this->resource = $resource; - $this->limits = $limits; - $this->processor = $processor; } + public function hasShutdown(): bool { return null !== $this->shutdownResult; diff --git a/src/SDK/Logs/Processor/BatchLogRecordProcessor.php b/src/SDK/Logs/Processor/BatchLogRecordProcessor.php index fc6faca54..6ba5f9ebf 100644 --- a/src/SDK/Logs/Processor/BatchLogRecordProcessor.php +++ b/src/SDK/Logs/Processor/BatchLogRecordProcessor.php @@ -33,13 +33,9 @@ class BatchLogRecordProcessor implements LogRecordProcessorInterface private const ATTRIBUTES_PROCESSED = self::ATTRIBUTES_PROCESSOR + ['state' => 'processed']; private const ATTRIBUTES_DROPPED = self::ATTRIBUTES_PROCESSOR + ['state' => 'dropped']; private const ATTRIBUTES_FREE = self::ATTRIBUTES_PROCESSOR + ['state' => 'free']; - - private LogRecordExporterInterface $exporter; - private ClockInterface $clock; private int $maxQueueSize; private int $scheduledDelayNanos; private int $maxExportBatchSize; - private bool $autoFlush; private ContextInterface $exportContext; private ?int $nextScheduledRun = null; @@ -58,14 +54,14 @@ class BatchLogRecordProcessor implements LogRecordProcessorInterface private bool $closed = false; public function __construct( - LogRecordExporterInterface $exporter, - ClockInterface $clock, + private LogRecordExporterInterface $exporter, + private ClockInterface $clock, int $maxQueueSize = self::DEFAULT_MAX_QUEUE_SIZE, int $scheduledDelayMillis = self::DEFAULT_SCHEDULE_DELAY, int $exportTimeoutMillis = self::DEFAULT_EXPORT_TIMEOUT, int $maxExportBatchSize = self::DEFAULT_MAX_EXPORT_BATCH_SIZE, - bool $autoFlush = true, - ?MeterProviderInterface $meterProvider = null + private bool $autoFlush = true, + ?MeterProviderInterface $meterProvider = null, ) { if ($maxQueueSize <= 0) { throw new InvalidArgumentException(sprintf('Maximum queue size (%d) must be greater than zero', $maxQueueSize)); @@ -82,13 +78,9 @@ public function __construct( if ($maxExportBatchSize > $maxQueueSize) { throw new InvalidArgumentException(sprintf('Maximum export batch size (%d) must be less than or equal to maximum queue size (%d)', $maxExportBatchSize, $maxQueueSize)); } - - $this->exporter = $exporter; - $this->clock = $clock; $this->maxQueueSize = $maxQueueSize; $this->scheduledDelayNanos = $scheduledDelayMillis * 1_000_000; $this->maxExportBatchSize = $maxExportBatchSize; - $this->autoFlush = $autoFlush; $this->exportContext = Context::getCurrent(); $this->queue = new SplQueue(); diff --git a/src/SDK/Logs/Processor/SimpleLogRecordProcessor.php b/src/SDK/Logs/Processor/SimpleLogRecordProcessor.php index f26f6607c..d64340140 100644 --- a/src/SDK/Logs/Processor/SimpleLogRecordProcessor.php +++ b/src/SDK/Logs/Processor/SimpleLogRecordProcessor.php @@ -12,10 +12,8 @@ class SimpleLogRecordProcessor implements LogRecordProcessorInterface { - private LogRecordExporterInterface $exporter; - public function __construct(LogRecordExporterInterface $exporter) + public function __construct(private LogRecordExporterInterface $exporter) { - $this->exporter = $exporter; } /** diff --git a/src/SDK/Logs/ReadableLogRecord.php b/src/SDK/Logs/ReadableLogRecord.php index 5c6531477..5cf8da321 100644 --- a/src/SDK/Logs/ReadableLogRecord.php +++ b/src/SDK/Logs/ReadableLogRecord.php @@ -20,16 +20,14 @@ */ class ReadableLogRecord extends LogRecord { - private InstrumentationScopeInterface $scope; - private LoggerSharedState $loggerSharedState; protected AttributesInterface $convertedAttributes; protected SpanContextInterface $spanContext; - public function __construct(InstrumentationScopeInterface $scope, LoggerSharedState $loggerSharedState, LogRecord $logRecord) - { - $this->scope = $scope; - $this->loggerSharedState = $loggerSharedState; - + public function __construct( + private InstrumentationScopeInterface $scope, + private LoggerSharedState $loggerSharedState, + LogRecord $logRecord, + ) { parent::__construct($logRecord->body); $this->timestamp = $logRecord->timestamp; $this->observedTimestamp = $logRecord->observedTimestamp diff --git a/src/SDK/Logs/SimplePsrFileLogger.php b/src/SDK/Logs/SimplePsrFileLogger.php index 9d9d55de6..9b40d1e9e 100644 --- a/src/SDK/Logs/SimplePsrFileLogger.php +++ b/src/SDK/Logs/SimplePsrFileLogger.php @@ -19,17 +19,10 @@ class SimplePsrFileLogger implements LoggerInterface private static ?array $logLevels = null; - private string $filename; - - private string $loggerName ; - - /** - * @param string $filename - */ - public function __construct(string $filename, string $loggerName = self::DEFAULT_LOGGER_NAME) - { - $this->filename = $filename; - $this->loggerName = $loggerName; + public function __construct( + private string $filename, + private string $loggerName = self::DEFAULT_LOGGER_NAME, + ) { } /** @@ -49,9 +42,6 @@ public function log($level, $message, array $context = []): void } /** - * @param string $level - * @param string $message - * @param array $context * @return string */ private function formatLog(string $level, string $message, array $context = []): string diff --git a/src/SDK/Metrics/Aggregation/ExplicitBucketHistogramAggregation.php b/src/SDK/Metrics/Aggregation/ExplicitBucketHistogramAggregation.php index d68ecd830..703f80191 100644 --- a/src/SDK/Metrics/Aggregation/ExplicitBucketHistogramAggregation.php +++ b/src/SDK/Metrics/Aggregation/ExplicitBucketHistogramAggregation.php @@ -18,18 +18,13 @@ */ final class ExplicitBucketHistogramAggregation implements AggregationInterface { - /** - * @var list - * @readonly - */ - public array $boundaries; - /** * @param list $boundaries strictly ascending histogram bucket boundaries */ - public function __construct(array $boundaries) - { - $this->boundaries = $boundaries; + public function __construct( + /** @readonly */ + public array $boundaries, + ) { } public function initialize(): ExplicitBucketHistogramSummary @@ -115,7 +110,7 @@ public function toData( array $exemplars, int $startTimestamp, int $timestamp, - $temporality + $temporality, ): Data\Histogram { $dataPoints = []; foreach ($attributes as $key => $dataPointAttributes) { diff --git a/src/SDK/Metrics/Aggregation/ExplicitBucketHistogramSummary.php b/src/SDK/Metrics/Aggregation/ExplicitBucketHistogramSummary.php index 1878a34a0..beffd3bff 100644 --- a/src/SDK/Metrics/Aggregation/ExplicitBucketHistogramSummary.php +++ b/src/SDK/Metrics/Aggregation/ExplicitBucketHistogramSummary.php @@ -6,35 +6,15 @@ final class ExplicitBucketHistogramSummary { - public int $count; /** - * @var float|int - */ - public $sum; - /** - * @var float|int - */ - public $min; - /** - * @var float|int - */ - public $max; - /** - * @var int[] - */ - public array $buckets; - /** - * @param float|int $sum - * @param float|int $min - * @param float|int $max * @param int[] $buckets */ - public function __construct(int $count, $sum, $min, $max, array $buckets) - { - $this->count = $count; - $this->sum = $sum; - $this->min = $min; - $this->max = $max; - $this->buckets = $buckets; + public function __construct( + public int $count, + public float|int $sum, + public float|int $min, + public float|int $max, + public array $buckets, + ) { } } diff --git a/src/SDK/Metrics/Aggregation/LastValueAggregation.php b/src/SDK/Metrics/Aggregation/LastValueAggregation.php index aff04e315..e1eba78e8 100644 --- a/src/SDK/Metrics/Aggregation/LastValueAggregation.php +++ b/src/SDK/Metrics/Aggregation/LastValueAggregation.php @@ -57,7 +57,7 @@ public function toData( array $exemplars, int $startTimestamp, int $timestamp, - $temporality + $temporality, ): Data\Gauge { $dataPoints = []; foreach ($attributes as $key => $dataPointAttributes) { diff --git a/src/SDK/Metrics/Aggregation/LastValueSummary.php b/src/SDK/Metrics/Aggregation/LastValueSummary.php index 6cdb5ac9f..ef8cf4a75 100644 --- a/src/SDK/Metrics/Aggregation/LastValueSummary.php +++ b/src/SDK/Metrics/Aggregation/LastValueSummary.php @@ -6,17 +6,9 @@ final class LastValueSummary { - /** - * @var float|int|null - */ - public $value; - public int $timestamp; - /** - * @param float|int|null $value - */ - public function __construct($value, int $timestamp) - { - $this->value = $value; - $this->timestamp = $timestamp; + public function __construct( + public float|int|null $value, + public int $timestamp, + ) { } } diff --git a/src/SDK/Metrics/Aggregation/SumAggregation.php b/src/SDK/Metrics/Aggregation/SumAggregation.php index dc317ce73..dd4ff5d3a 100644 --- a/src/SDK/Metrics/Aggregation/SumAggregation.php +++ b/src/SDK/Metrics/Aggregation/SumAggregation.php @@ -14,11 +14,8 @@ */ final class SumAggregation implements AggregationInterface { - private bool $monotonic; - - public function __construct(bool $monotonic = false) + public function __construct(private bool $monotonic = false) { - $this->monotonic = $monotonic; } public function initialize(): SumSummary @@ -69,7 +66,7 @@ public function toData( array $exemplars, int $startTimestamp, int $timestamp, - $temporality + $temporality, ): Data\Sum { $dataPoints = []; foreach ($attributes as $key => $dataPointAttributes) { diff --git a/src/SDK/Metrics/Aggregation/SumSummary.php b/src/SDK/Metrics/Aggregation/SumSummary.php index 9b257193c..666ec4073 100644 --- a/src/SDK/Metrics/Aggregation/SumSummary.php +++ b/src/SDK/Metrics/Aggregation/SumSummary.php @@ -6,15 +6,7 @@ final class SumSummary { - /** - * @var float|int - */ - public $value; - /** - * @param float|int $value - */ - public function __construct($value) + public function __construct(public float|int $value) { - $this->value = $value; } } diff --git a/src/SDK/Metrics/AggregationInterface.php b/src/SDK/Metrics/AggregationInterface.php index 0a85207e0..7f2cb1e50 100644 --- a/src/SDK/Metrics/AggregationInterface.php +++ b/src/SDK/Metrics/AggregationInterface.php @@ -52,6 +52,6 @@ public function toData( array $exemplars, int $startTimestamp, int $timestamp, - $temporality + $temporality, ): DataInterface; } diff --git a/src/SDK/Metrics/AsynchronousInstruments.php b/src/SDK/Metrics/AsynchronousInstruments.php index 5e44d030e..48dbbdd85 100644 --- a/src/SDK/Metrics/AsynchronousInstruments.php +++ b/src/SDK/Metrics/AsynchronousInstruments.php @@ -24,7 +24,7 @@ public static function observe( ArrayAccess $destructors, callable $callback, array $instruments, - ReferenceCounterInterface $referenceCounter + ReferenceCounterInterface $referenceCounter, ): ObservableCallbackInterface { $target = null; $callback = weaken(closure($callback), $target); diff --git a/src/SDK/Metrics/AttributeProcessor/FilteredAttributeProcessor.php b/src/SDK/Metrics/AttributeProcessor/FilteredAttributeProcessor.php index c4df8e878..57f0c33a6 100644 --- a/src/SDK/Metrics/AttributeProcessor/FilteredAttributeProcessor.php +++ b/src/SDK/Metrics/AttributeProcessor/FilteredAttributeProcessor.php @@ -14,11 +14,8 @@ */ final class FilteredAttributeProcessor implements AttributeProcessorInterface { - private array $attributeKeys; - - public function __construct(array $attributeKeys) + public function __construct(private array $attributeKeys) { - $this->attributeKeys = $attributeKeys; } public function process(AttributesInterface $attributes, ContextInterface $context): AttributesInterface diff --git a/src/SDK/Metrics/Data/Exemplar.php b/src/SDK/Metrics/Data/Exemplar.php index bd2034f75..5d6be7380 100644 --- a/src/SDK/Metrics/Data/Exemplar.php +++ b/src/SDK/Metrics/Data/Exemplar.php @@ -8,45 +8,19 @@ final class Exemplar { - - /** - * @var int|string - */ - private $index; - /** - * @var float|int - * @readonly - */ - public $value; - /** - * @readonly - */ - public int $timestamp; - /** - * @readonly - */ - public AttributesInterface $attributes; - /** - * @readonly - */ - public ?string $traceId; - /** - * @readonly - */ - public ?string $spanId; - - /** - * @param int|string $index - * @param float|int $value - */ - public function __construct($index, $value, int $timestamp, AttributesInterface $attributes, ?string $traceId, ?string $spanId) - { - $this->index = $index; - $this->value = $value; - $this->timestamp = $timestamp; - $this->attributes = $attributes; - $this->traceId = $traceId; - $this->spanId = $spanId; + public function __construct( + private int|string $index, + /** @readonly */ + public float|int $value, + /** @readonly */ + public int $timestamp, + /** @readonly */ + public AttributesInterface $attributes, + /** @readonly */ + public ?string $traceId, + /** @readonly */ + public ?string $spanId, + ) { } /** diff --git a/src/SDK/Metrics/Data/Gauge.php b/src/SDK/Metrics/Data/Gauge.php index 00eb50939..732b0387d 100644 --- a/src/SDK/Metrics/Data/Gauge.php +++ b/src/SDK/Metrics/Data/Gauge.php @@ -7,16 +7,12 @@ final class Gauge implements DataInterface { - /** - * @var iterable - * @readonly - */ - public iterable $dataPoints; /** * @param iterable $dataPoints */ - public function __construct(iterable $dataPoints) - { - $this->dataPoints = $dataPoints; + public function __construct( + /** @readonly */ + public iterable $dataPoints, + ) { } } diff --git a/src/SDK/Metrics/Data/Histogram.php b/src/SDK/Metrics/Data/Histogram.php index 782698026..1f19254a3 100644 --- a/src/SDK/Metrics/Data/Histogram.php +++ b/src/SDK/Metrics/Data/Histogram.php @@ -6,24 +6,14 @@ final class Histogram implements DataInterface { - - /** - * @var iterable - * @readonly - */ - public iterable $dataPoints; - /** - * @var string|Temporality - * @readonly - */ - public $temporality; /** * @param iterable $dataPoints - * @param string|Temporality $temporality */ - public function __construct(iterable $dataPoints, $temporality) - { - $this->dataPoints = $dataPoints; - $this->temporality = $temporality; + public function __construct( + /** @readonly */ + public iterable $dataPoints, + /** @readonly */ + public string|Temporality $temporality, + ) { } } diff --git a/src/SDK/Metrics/Data/HistogramDataPoint.php b/src/SDK/Metrics/Data/HistogramDataPoint.php index 4c9df07b4..0af01746c 100644 --- a/src/SDK/Metrics/Data/HistogramDataPoint.php +++ b/src/SDK/Metrics/Data/HistogramDataPoint.php @@ -9,68 +9,30 @@ final class HistogramDataPoint { /** - * @readonly - */ - public int $count; - /** - * @var float|int - * @readonly - */ - public $sum; - /** - * @var float|int - * @readonly - */ - public $min; - /** - * @var float|int - * @readonly - */ - public $max; - /** - * @var int[] - * @readonly - */ - public array $bucketCounts; - /** - * @var list - * @readonly - */ - public array $explicitBounds; - /** - * @readonly - */ - public AttributesInterface $attributes; - /** - * @readonly - */ - public int $startTimestamp; - /** - * @readonly - */ - public int $timestamp; - /** - * @readonly - */ - public iterable $exemplars = []; - /** - * @param float|int $sum - * @param float|int $min - * @param float|int $max * @param int[] $bucketCounts * @param list $explicitBounds */ - public function __construct(int $count, $sum, $min, $max, array $bucketCounts, array $explicitBounds, AttributesInterface $attributes, int $startTimestamp, int $timestamp, iterable $exemplars = []) - { - $this->count = $count; - $this->sum = $sum; - $this->min = $min; - $this->max = $max; - $this->bucketCounts = $bucketCounts; - $this->explicitBounds = $explicitBounds; - $this->attributes = $attributes; - $this->startTimestamp = $startTimestamp; - $this->timestamp = $timestamp; - $this->exemplars = $exemplars; + public function __construct( + /** @readonly */ + public int $count, + /** @readonly */ + public float|int $sum, + /** @readonly */ + public float|int $min, + /** @readonly */ + public float|int $max, + /** @readonly */ + public array $bucketCounts, + /** @readonly */ + public array $explicitBounds, + /** @readonly */ + public AttributesInterface $attributes, + /** @readonly */ + public int $startTimestamp, + /** @readonly */ + public int $timestamp, + /** @readonly */ + public iterable $exemplars = [], + ) { } } diff --git a/src/SDK/Metrics/Data/Metric.php b/src/SDK/Metrics/Data/Metric.php index 41fcb52dd..3963c11a4 100644 --- a/src/SDK/Metrics/Data/Metric.php +++ b/src/SDK/Metrics/Data/Metric.php @@ -9,38 +9,19 @@ final class Metric { - /** - * @readonly - */ - public InstrumentationScopeInterface $instrumentationScope; - /** - * @readonly - */ - public ResourceInfo $resource; - /** - * @readonly - */ - public string $name; - /** - * @readonly - */ - public ?string $description; - /** - * @readonly - */ - public ?string $unit; - /** - * @readonly - */ - public DataInterface $data; - - public function __construct(InstrumentationScopeInterface $instrumentationScope, ResourceInfo $resource, string $name, ?string $unit, ?string $description, DataInterface $data) - { - $this->instrumentationScope = $instrumentationScope; - $this->resource = $resource; - $this->name = $name; - $this->description = $description; - $this->unit = $unit; - $this->data = $data; + public function __construct( + /** @readonly */ + public InstrumentationScopeInterface $instrumentationScope, + /** @readonly */ + public ResourceInfo $resource, + /** @readonly */ + public string $name, + /** @readonly */ + public ?string $unit, + /** @readonly */ + public ?string $description, + /** @readonly */ + public DataInterface $data, + ) { } } diff --git a/src/SDK/Metrics/Data/NumberDataPoint.php b/src/SDK/Metrics/Data/NumberDataPoint.php index 1d00e783a..7159fd600 100644 --- a/src/SDK/Metrics/Data/NumberDataPoint.php +++ b/src/SDK/Metrics/Data/NumberDataPoint.php @@ -8,36 +8,17 @@ final class NumberDataPoint { - /** - * @var float|int - * @readonly - */ - public $value; - /** - * @readonly - */ - public AttributesInterface $attributes; - /** - * @readonly - */ - public int $startTimestamp; - /** - * @readonly - */ - public int $timestamp; - /** - * @readonly - */ - public iterable $exemplars = []; - /** - * @param float|int $value - */ - public function __construct($value, AttributesInterface $attributes, int $startTimestamp, int $timestamp, iterable $exemplars = []) - { - $this->value = $value; - $this->attributes = $attributes; - $this->startTimestamp = $startTimestamp; - $this->timestamp = $timestamp; - $this->exemplars = $exemplars; + public function __construct( + /** @readonly */ + public float|int $value, + /** @readonly */ + public AttributesInterface $attributes, + /** @readonly */ + public int $startTimestamp, + /** @readonly */ + public int $timestamp, + /** @readonly */ + public iterable $exemplars = [], + ) { } } diff --git a/src/SDK/Metrics/Data/Sum.php b/src/SDK/Metrics/Data/Sum.php index 77c4c1021..56cdf91a4 100644 --- a/src/SDK/Metrics/Data/Sum.php +++ b/src/SDK/Metrics/Data/Sum.php @@ -6,29 +6,16 @@ final class Sum implements DataInterface { - - /** - * @var iterable - * @readonly - */ - public iterable $dataPoints; - /** - * @var string|Temporality - * @readonly - */ - public $temporality; - /** - * @readonly - */ - public bool $monotonic; /** * @param iterable $dataPoints - * @param string|Temporality $temporality */ - public function __construct(iterable $dataPoints, $temporality, bool $monotonic) - { - $this->dataPoints = $dataPoints; - $this->temporality = $temporality; - $this->monotonic = $monotonic; + public function __construct( + /** @readonly */ + public iterable $dataPoints, + /** @readonly */ + public string|Temporality $temporality, + /** @readonly */ + public bool $monotonic, + ) { } } diff --git a/src/SDK/Metrics/Data/Temporality.php b/src/SDK/Metrics/Data/Temporality.php index b6642ebd0..e51c557fd 100644 --- a/src/SDK/Metrics/Data/Temporality.php +++ b/src/SDK/Metrics/Data/Temporality.php @@ -8,6 +8,7 @@ * Metric aggregation temporality. * * Has to be type-hinted as `string|Temporality` to be forward compatible. + * @todo convert to enum (php >= 8.1) */ final class Temporality { diff --git a/src/SDK/Metrics/DefaultAggregationProviderTrait.php b/src/SDK/Metrics/DefaultAggregationProviderTrait.php index 737ec40dd..b3eb7dc0a 100644 --- a/src/SDK/Metrics/DefaultAggregationProviderTrait.php +++ b/src/SDK/Metrics/DefaultAggregationProviderTrait.php @@ -8,21 +8,13 @@ trait DefaultAggregationProviderTrait { public function defaultAggregation($instrumentType, array $advisory = []): ?AggregationInterface { - switch ($instrumentType) { - case InstrumentType::COUNTER: - case InstrumentType::ASYNCHRONOUS_COUNTER: - return new Aggregation\SumAggregation(true); - case InstrumentType::UP_DOWN_COUNTER: - case InstrumentType::ASYNCHRONOUS_UP_DOWN_COUNTER: - return new Aggregation\SumAggregation(); - case InstrumentType::HISTOGRAM: - return new Aggregation\ExplicitBucketHistogramAggregation($advisory['ExplicitBucketBoundaries'] ?? [0, 5, 10, 25, 50, 75, 100, 250, 500, 1000]); - case InstrumentType::ASYNCHRONOUS_GAUGE: - return new Aggregation\LastValueAggregation(); - } - - // @codeCoverageIgnoreStart - return null; + return match ($instrumentType) { + InstrumentType::COUNTER, InstrumentType::ASYNCHRONOUS_COUNTER => new Aggregation\SumAggregation(true), + InstrumentType::UP_DOWN_COUNTER, InstrumentType::ASYNCHRONOUS_UP_DOWN_COUNTER => new Aggregation\SumAggregation(), + InstrumentType::HISTOGRAM => new Aggregation\ExplicitBucketHistogramAggregation($advisory['ExplicitBucketBoundaries'] ?? [0, 5, 10, 25, 50, 75, 100, 250, 500, 1000]), + InstrumentType::ASYNCHRONOUS_GAUGE => new Aggregation\LastValueAggregation(), + default => null, + }; // @codeCoverageIgnoreEnd } } diff --git a/src/SDK/Metrics/Exemplar/FilteredReservoir.php b/src/SDK/Metrics/Exemplar/FilteredReservoir.php index 0e4f24357..5ef1baaac 100644 --- a/src/SDK/Metrics/Exemplar/FilteredReservoir.php +++ b/src/SDK/Metrics/Exemplar/FilteredReservoir.php @@ -13,13 +13,10 @@ */ final class FilteredReservoir implements ExemplarReservoirInterface { - private ExemplarReservoirInterface $reservoir; - private ExemplarFilterInterface $filter; - - public function __construct(ExemplarReservoirInterface $reservoir, ExemplarFilterInterface $filter) - { - $this->reservoir = $reservoir; - $this->filter = $filter; + public function __construct( + private ExemplarReservoirInterface $reservoir, + private ExemplarFilterInterface $filter, + ) { } public function offer($index, $value, AttributesInterface $attributes, ContextInterface $context, int $timestamp): void diff --git a/src/SDK/Metrics/Instrument.php b/src/SDK/Metrics/Instrument.php index b696a41e1..3a0019f39 100644 --- a/src/SDK/Metrics/Instrument.php +++ b/src/SDK/Metrics/Instrument.php @@ -6,37 +6,17 @@ final class Instrument { - /** - * @var string|InstrumentType - * @readonly - */ - public $type; - /** - * @readonly - */ - public string $name; - /** - * @readonly - */ - public ?string $unit; - /** - * @readonly - */ - public ?string $description; - /** - * @readonly - */ - public array $advisory; - - /** - * @param string|InstrumentType $type - */ - public function __construct($type, string $name, ?string $unit, ?string $description, array $advisory = []) - { - $this->type = $type; - $this->name = $name; - $this->unit = $unit; - $this->description = $description; - $this->advisory = $advisory; + public function __construct( + /** @readonly */ + public string|InstrumentType $type, + /** @readonly */ + public string $name, + /** @readonly */ + public ?string $unit, + /** @readonly */ + public ?string $description, + /** @readonly */ + public array $advisory = [], + ) { } } diff --git a/src/SDK/Metrics/Meter.php b/src/SDK/Metrics/Meter.php index 83c452427..5dcf0ff1a 100644 --- a/src/SDK/Metrics/Meter.php +++ b/src/SDK/Metrics/Meter.php @@ -37,21 +37,6 @@ final class Meter implements MeterInterface { use LogsMessagesTrait; - private MetricFactoryInterface $metricFactory; - private ResourceInfo $resource; - private ClockInterface $clock; - private StalenessHandlerFactoryInterface $stalenessHandlerFactory; - /** @var iterable */ - private iterable $metricRegistries; - private ViewRegistryInterface $viewRegistry; - private ?ExemplarFilterInterface $exemplarFilter; - private MeterInstruments $instruments; - private InstrumentationScopeInterface $instrumentationScope; - - private MetricRegistryInterface $registry; - private MetricWriterInterface $writer; - private ArrayAccess $destructors; - private ?string $instrumentationScopeId = null; /** @@ -59,31 +44,19 @@ final class Meter implements MeterInterface * @param ArrayAccess $destructors */ public function __construct( - MetricFactoryInterface $metricFactory, - ResourceInfo $resource, - ClockInterface $clock, - StalenessHandlerFactoryInterface $stalenessHandlerFactory, - iterable $metricRegistries, - ViewRegistryInterface $viewRegistry, - ?ExemplarFilterInterface $exemplarFilter, - MeterInstruments $instruments, - InstrumentationScopeInterface $instrumentationScope, - MetricRegistryInterface $registry, - MetricWriterInterface $writer, - ArrayAccess $destructors + private MetricFactoryInterface $metricFactory, + private ResourceInfo $resource, + private ClockInterface $clock, + private StalenessHandlerFactoryInterface $stalenessHandlerFactory, + private iterable $metricRegistries, + private ViewRegistryInterface $viewRegistry, + private ?ExemplarFilterInterface $exemplarFilter, + private MeterInstruments $instruments, + private InstrumentationScopeInterface $instrumentationScope, + private MetricRegistryInterface $registry, + private MetricWriterInterface $writer, + private ArrayAccess $destructors, ) { - $this->metricFactory = $metricFactory; - $this->resource = $resource; - $this->clock = $clock; - $this->stalenessHandlerFactory = $stalenessHandlerFactory; - $this->metricRegistries = $metricRegistries; - $this->viewRegistry = $viewRegistry; - $this->exemplarFilter = $exemplarFilter; - $this->instruments = $instruments; - $this->instrumentationScope = $instrumentationScope; - $this->registry = $registry; - $this->writer = $writer; - $this->destructors = $destructors; } private static function dummyInstrument(): Instrument @@ -254,10 +227,9 @@ private function getAsynchronousInstrument(Instrument $instrument, Instrumentati } /** - * @param string|InstrumentType $instrumentType * @return array{Instrument, ReferenceCounterInterface} */ - private function createSynchronousWriter($instrumentType, string $name, ?string $unit, ?string $description, array $advisory = []): array + private function createSynchronousWriter(string|InstrumentType $instrumentType, string $name, ?string $unit, ?string $description, array $advisory = []): array { $instrument = new Instrument($instrumentType, $name, $unit, $description, $advisory); @@ -301,10 +273,9 @@ private function createSynchronousWriter($instrumentType, string $name, ?string } /** - * @param string|InstrumentType $instrumentType * @return array{Instrument, ReferenceCounterInterface} */ - private function createAsynchronousObserver($instrumentType, string $name, ?string $unit, ?string $description, array $advisory): array + private function createAsynchronousObserver(string|InstrumentType $instrumentType, string $name, ?string $unit, ?string $description, array $advisory): array { $instrument = new Instrument($instrumentType, $name, $unit, $description, $advisory); diff --git a/src/SDK/Metrics/MeterProvider.php b/src/SDK/Metrics/MeterProvider.php index 40d61e973..942d07570 100644 --- a/src/SDK/Metrics/MeterProvider.php +++ b/src/SDK/Metrics/MeterProvider.php @@ -11,7 +11,6 @@ use OpenTelemetry\SDK\Common\Attribute\AttributesFactoryInterface; use OpenTelemetry\SDK\Common\Instrumentation\InstrumentationScopeFactoryInterface; use OpenTelemetry\SDK\Common\Time\ClockInterface; -use OpenTelemetry\SDK\Common\Util\WeakMap; use OpenTelemetry\SDK\Metrics\Exemplar\ExemplarFilterInterface; use OpenTelemetry\SDK\Metrics\MetricFactory\StreamFactory; use OpenTelemetry\SDK\Metrics\MetricRegistry\MetricRegistry; @@ -19,17 +18,11 @@ use OpenTelemetry\SDK\Metrics\MetricRegistry\MetricWriterInterface; use OpenTelemetry\SDK\Resource\ResourceInfo; use OpenTelemetry\SDK\Sdk; +use WeakMap; final class MeterProvider implements MeterProviderInterface { private MetricFactoryInterface $metricFactory; - private ResourceInfo $resource; - private ClockInterface $clock; - private InstrumentationScopeFactoryInterface $instrumentationScopeFactory; - private iterable $metricReaders; - private ViewRegistryInterface $viewRegistry; - private ?ExemplarFilterInterface $exemplarFilter; - private StalenessHandlerFactoryInterface $stalenessHandlerFactory; private MeterInstruments $instruments; private MetricRegistryInterface $registry; private MetricWriterInterface $writer; @@ -42,37 +35,30 @@ final class MeterProvider implements MeterProviderInterface */ public function __construct( ?ContextStorageInterface $contextStorage, - ResourceInfo $resource, - ClockInterface $clock, + private ResourceInfo $resource, + private ClockInterface $clock, AttributesFactoryInterface $attributesFactory, - InstrumentationScopeFactoryInterface $instrumentationScopeFactory, - iterable $metricReaders, - ViewRegistryInterface $viewRegistry, - ?ExemplarFilterInterface $exemplarFilter, - StalenessHandlerFactoryInterface $stalenessHandlerFactory, - MetricFactoryInterface $metricFactory = null + private InstrumentationScopeFactoryInterface $instrumentationScopeFactory, + private iterable $metricReaders, + private ViewRegistryInterface $viewRegistry, + private ?ExemplarFilterInterface $exemplarFilter, + private StalenessHandlerFactoryInterface $stalenessHandlerFactory, + MetricFactoryInterface $metricFactory = null, ) { $this->metricFactory = $metricFactory ?? new StreamFactory(); - $this->resource = $resource; - $this->clock = $clock; - $this->instrumentationScopeFactory = $instrumentationScopeFactory; - $this->metricReaders = $metricReaders; - $this->viewRegistry = $viewRegistry; - $this->exemplarFilter = $exemplarFilter; - $this->stalenessHandlerFactory = $stalenessHandlerFactory; $this->instruments = new MeterInstruments(); $registry = new MetricRegistry($contextStorage, $attributesFactory, $clock); $this->registry = $registry; $this->writer = $registry; - $this->destructors = WeakMap::create(); + $this->destructors = new WeakMap(); } public function getMeter( string $name, ?string $version = null, ?string $schemaUrl = null, - iterable $attributes = [] + iterable $attributes = [], ): MeterInterface { if ($this->closed || Sdk::isDisabled()) { //@todo create meter provider from factory, and move Sdk::isDisabled() there return new NoopMeter(); diff --git a/src/SDK/Metrics/MetricExporter/ConsoleMetricExporter.php b/src/SDK/Metrics/MetricExporter/ConsoleMetricExporter.php index ea181435f..0a2493a05 100644 --- a/src/SDK/Metrics/MetricExporter/ConsoleMetricExporter.php +++ b/src/SDK/Metrics/MetricExporter/ConsoleMetricExporter.php @@ -18,17 +18,11 @@ */ class ConsoleMetricExporter implements PushMetricExporterInterface, AggregationTemporalitySelectorInterface { - /** - * @var string|Temporality|null - */ - private $temporality; - /** * @param string|Temporality|null $temporality */ - public function __construct($temporality = null) + public function __construct(private $temporality = null) { - $this->temporality = $temporality; } /** * @inheritDoc diff --git a/src/SDK/Metrics/MetricExporter/InMemoryExporter.php b/src/SDK/Metrics/MetricExporter/InMemoryExporter.php index 6bbab8b79..ce250cd17 100644 --- a/src/SDK/Metrics/MetricExporter/InMemoryExporter.php +++ b/src/SDK/Metrics/MetricExporter/InMemoryExporter.php @@ -20,22 +20,14 @@ final class InMemoryExporter implements MetricExporterInterface, AggregationTemp * @var list */ private array $metrics = []; - /** - * @var string|Temporality|null - */ - private $temporality; private bool $closed = false; - /** - * @param string|Temporality|null $temporality - */ - public function __construct($temporality = null) + public function __construct(private string|Temporality|null $temporality = null) { - $this->temporality = $temporality; } - public function temporality(MetricMetadataInterface $metric) + public function temporality(MetricMetadataInterface $metric): string|Temporality|null { return $this->temporality ?? $metric->temporality(); } diff --git a/src/SDK/Metrics/MetricFactory/StreamFactory.php b/src/SDK/Metrics/MetricFactory/StreamFactory.php index 2c3af4c06..b5b944275 100644 --- a/src/SDK/Metrics/MetricFactory/StreamFactory.php +++ b/src/SDK/Metrics/MetricFactory/StreamFactory.php @@ -42,7 +42,7 @@ public function createAsynchronousObserver( InstrumentationScopeInterface $instrumentationScope, Instrument $instrument, int $timestamp, - iterable $views + iterable $views, ): array { $streams = []; $dedup = []; @@ -85,7 +85,7 @@ public function createSynchronousWriter( Instrument $instrument, int $timestamp, iterable $views, - ?ExemplarFilterInterface $exemplarFilter = null + ?ExemplarFilterInterface $exemplarFilter = null, ): array { $streams = []; $dedup = []; @@ -123,7 +123,7 @@ public function createSynchronousWriter( } private function attributeProcessor( - ?array $attributeKeys + ?array $attributeKeys, ): ?AttributeProcessorInterface { return $attributeKeys !== null ? new FilteredAttributeProcessor($attributeKeys) @@ -132,7 +132,7 @@ private function attributeProcessor( private function createExemplarReservoir( AggregationInterface $aggregation, - ?ExemplarFilterInterface $exemplarFilter + ?ExemplarFilterInterface $exemplarFilter, ): ?ExemplarReservoirInterface { if (!$exemplarFilter) { return null; @@ -155,7 +155,7 @@ private function registerSource( MetricStreamInterface $stream, MetricCollectorInterface $metricCollector, MetricRegistrationInterface $metricRegistration, - int $streamId + int $streamId, ): void { $provider = new StreamMetricSourceProvider( $view, @@ -179,7 +179,7 @@ private function trySerialize(object $object) { try { return serialize($object); - } catch (Throwable $e) { + } catch (Throwable) { } return spl_object_id($object); diff --git a/src/SDK/Metrics/MetricFactory/StreamMetricSource.php b/src/SDK/Metrics/MetricFactory/StreamMetricSource.php index 4939a5341..d8bb9a8b4 100644 --- a/src/SDK/Metrics/MetricFactory/StreamMetricSource.php +++ b/src/SDK/Metrics/MetricFactory/StreamMetricSource.php @@ -12,12 +12,10 @@ */ final class StreamMetricSource implements MetricSourceInterface { - private StreamMetricSourceProvider $provider; - private int $reader; - public function __construct(StreamMetricSourceProvider $provider, int $reader) - { - $this->provider = $provider; - $this->reader = $reader; + public function __construct( + private StreamMetricSourceProvider $provider, + private int $reader, + ) { } public function collectionTimestamp(): int diff --git a/src/SDK/Metrics/MetricFactory/StreamMetricSourceProvider.php b/src/SDK/Metrics/MetricFactory/StreamMetricSourceProvider.php index 657c3ce62..5d20be5ab 100644 --- a/src/SDK/Metrics/MetricFactory/StreamMetricSourceProvider.php +++ b/src/SDK/Metrics/MetricFactory/StreamMetricSourceProvider.php @@ -19,51 +19,22 @@ */ final class StreamMetricSourceProvider implements MetricSourceProviderInterface, MetricMetadataInterface { - /** - * @readonly - */ - public ViewProjection $view; - /** - * @readonly - */ - public Instrument $instrument; - /** - * @readonly - */ - public InstrumentationScopeInterface $instrumentationLibrary; - /** - * @readonly - */ - public ResourceInfo $resource; - /** - * @readonly - */ - public MetricStreamInterface $stream; - /** - * @readonly - */ - public MetricCollectorInterface $metricCollector; - /** - * @readonly - */ - public int $streamId; - public function __construct( - ViewProjection $view, - Instrument $instrument, - InstrumentationScopeInterface $instrumentationLibrary, - ResourceInfo $resource, - MetricStreamInterface $stream, - MetricCollectorInterface $metricCollector, - int $streamId + /** @readonly */ + public ViewProjection $view, + /** @readonly */ + public Instrument $instrument, + /** @readonly */ + public InstrumentationScopeInterface $instrumentationLibrary, + /** @readonly */ + public ResourceInfo $resource, + /** @readonly */ + public MetricStreamInterface $stream, + /** @readonly */ + public MetricCollectorInterface $metricCollector, + /** @readonly */ + public int $streamId, ) { - $this->view = $view; - $this->instrument = $instrument; - $this->instrumentationLibrary = $instrumentationLibrary; - $this->resource = $resource; - $this->stream = $stream; - $this->metricCollector = $metricCollector; - $this->streamId = $streamId; } public function create($temporality): MetricSourceInterface diff --git a/src/SDK/Metrics/MetricFactoryInterface.php b/src/SDK/Metrics/MetricFactoryInterface.php index a1e228eef..2bc30e45d 100644 --- a/src/SDK/Metrics/MetricFactoryInterface.php +++ b/src/SDK/Metrics/MetricFactoryInterface.php @@ -23,7 +23,7 @@ public function createAsynchronousObserver( InstrumentationScopeInterface $instrumentationScope, Instrument $instrument, int $timestamp, - iterable $views + iterable $views, ): array; /** @@ -36,6 +36,6 @@ public function createSynchronousWriter( Instrument $instrument, int $timestamp, iterable $views, - ?ExemplarFilterInterface $exemplarFilter = null + ?ExemplarFilterInterface $exemplarFilter = null, ): array; } diff --git a/src/SDK/Metrics/MetricReader/ExportingReader.php b/src/SDK/Metrics/MetricReader/ExportingReader.php index 3d5e8f1e7..49b0b0f00 100644 --- a/src/SDK/Metrics/MetricReader/ExportingReader.php +++ b/src/SDK/Metrics/MetricReader/ExportingReader.php @@ -24,8 +24,6 @@ final class ExportingReader implements MetricReaderInterface, MetricSourceRegistryInterface, DefaultAggregationProviderInterface { use DefaultAggregationProviderTrait { defaultAggregation as private _defaultAggregation; } - - private MetricExporterInterface $exporter; /** @var array */ private array $sources = []; @@ -36,9 +34,8 @@ final class ExportingReader implements MetricReaderInterface, MetricSourceRegist private bool $closed = false; - public function __construct(MetricExporterInterface $exporter) + public function __construct(private MetricExporterInterface $exporter) { - $this->exporter = $exporter; } public function defaultAggregation($instrumentType, array $advisory = []): ?AggregationInterface diff --git a/src/SDK/Metrics/MetricRegistration/MultiRegistryRegistration.php b/src/SDK/Metrics/MetricRegistration/MultiRegistryRegistration.php index 2472c096f..8ec89b1ad 100644 --- a/src/SDK/Metrics/MetricRegistration/MultiRegistryRegistration.php +++ b/src/SDK/Metrics/MetricRegistration/MultiRegistryRegistration.php @@ -15,16 +15,13 @@ */ final class MultiRegistryRegistration implements MetricRegistrationInterface { - private iterable $registries; - private StalenessHandlerInterface $stalenessHandler; - /** * @param iterable $registries */ - public function __construct(iterable $registries, StalenessHandlerInterface $stalenessHandler) - { - $this->registries = $registries; - $this->stalenessHandler = $stalenessHandler; + public function __construct( + private iterable $registries, + private StalenessHandlerInterface $stalenessHandler, + ) { } public function register(MetricSourceProviderInterface $provider, MetricMetadataInterface $metadata): void diff --git a/src/SDK/Metrics/MetricRegistration/RegistryRegistration.php b/src/SDK/Metrics/MetricRegistration/RegistryRegistration.php index 3c1108902..58e06867e 100644 --- a/src/SDK/Metrics/MetricRegistration/RegistryRegistration.php +++ b/src/SDK/Metrics/MetricRegistration/RegistryRegistration.php @@ -15,13 +15,10 @@ */ final class RegistryRegistration implements MetricRegistrationInterface { - private MetricSourceRegistryInterface $registry; - private StalenessHandlerInterface $stalenessHandler; - - public function __construct(MetricSourceRegistryInterface $registry, StalenessHandlerInterface $stalenessHandler) - { - $this->registry = $registry; - $this->stalenessHandler = $stalenessHandler; + public function __construct( + private MetricSourceRegistryInterface $registry, + private StalenessHandlerInterface $stalenessHandler, + ) { } public function register(MetricSourceProviderInterface $provider, MetricMetadataInterface $metadata): void diff --git a/src/SDK/Metrics/MetricRegistry/MetricRegistry.php b/src/SDK/Metrics/MetricRegistry/MetricRegistry.php index 12b844a88..9b44a5dd1 100644 --- a/src/SDK/Metrics/MetricRegistry/MetricRegistry.php +++ b/src/SDK/Metrics/MetricRegistry/MetricRegistry.php @@ -21,10 +21,6 @@ */ final class MetricRegistry implements MetricRegistryInterface, MetricWriterInterface { - private ?ContextStorageInterface $contextStorage; - private AttributesFactoryInterface $attributesFactory; - private ClockInterface $clock; - /** @var array */ private array $streams = []; /** @var array */ @@ -44,13 +40,10 @@ final class MetricRegistry implements MetricRegistryInterface, MetricWriterInter private array $asynchronousCallbackArguments = []; public function __construct( - ?ContextStorageInterface $contextStorage, - AttributesFactoryInterface $attributesFactory, - ClockInterface $clock + private ?ContextStorageInterface $contextStorage, + private AttributesFactoryInterface $attributesFactory, + private ClockInterface $clock, ) { - $this->contextStorage = $contextStorage; - $this->attributesFactory = $attributesFactory; - $this->clock = $clock; } public function registerSynchronousStream(Instrument $instrument, MetricStreamInterface $stream, MetricAggregatorInterface $aggregator): int diff --git a/src/SDK/Metrics/MetricRegistry/MultiObserver.php b/src/SDK/Metrics/MetricRegistry/MultiObserver.php index f36f74a2a..6c474cacd 100644 --- a/src/SDK/Metrics/MetricRegistry/MultiObserver.php +++ b/src/SDK/Metrics/MetricRegistry/MultiObserver.php @@ -14,16 +14,13 @@ */ final class MultiObserver implements ObserverInterface { - private AttributesFactoryInterface $attributesFactory; - private int $timestamp; - /** @var list */ public array $writers = []; - public function __construct(AttributesFactoryInterface $attributesFactory, int $timestamp) - { - $this->attributesFactory = $attributesFactory; - $this->timestamp = $timestamp; + public function __construct( + private AttributesFactoryInterface $attributesFactory, + private int $timestamp, + ) { } public function observe($amount, iterable $attributes = []): void diff --git a/src/SDK/Metrics/ObservableCallback.php b/src/SDK/Metrics/ObservableCallback.php index bc694894e..260405f75 100644 --- a/src/SDK/Metrics/ObservableCallback.php +++ b/src/SDK/Metrics/ObservableCallback.php @@ -13,19 +13,13 @@ */ final class ObservableCallback implements ObservableCallbackInterface { - private MetricWriterInterface $writer; - private ReferenceCounterInterface $referenceCounter; - private ?int $callbackId; - private ?ObservableCallbackDestructor $callbackDestructor; - private ?object $target; - - public function __construct(MetricWriterInterface $writer, ReferenceCounterInterface $referenceCounter, int $callbackId, ?ObservableCallbackDestructor $callbackDestructor, ?object $target) - { - $this->writer = $writer; - $this->referenceCounter = $referenceCounter; - $this->callbackId = $callbackId; - $this->callbackDestructor = $callbackDestructor; - $this->target = $target; + public function __construct( + private MetricWriterInterface $writer, + private ReferenceCounterInterface $referenceCounter, + private ?int $callbackId, + private ?ObservableCallbackDestructor $callbackDestructor, + private ?object $target, + ) { } public function detach(): void diff --git a/src/SDK/Metrics/ObservableCallbackDestructor.php b/src/SDK/Metrics/ObservableCallbackDestructor.php index 95612222c..49cbe6f11 100644 --- a/src/SDK/Metrics/ObservableCallbackDestructor.php +++ b/src/SDK/Metrics/ObservableCallbackDestructor.php @@ -12,18 +12,16 @@ */ final class ObservableCallbackDestructor { - public ArrayAccess $destructors; /** @var array */ public array $callbackIds = []; - private MetricWriterInterface $writer; /** * @param ArrayAccess $destructors */ - public function __construct(ArrayAccess $destructors, MetricWriterInterface $writer) - { - $this->destructors = $destructors; - $this->writer = $writer; + public function __construct( + public ArrayAccess $destructors, + private MetricWriterInterface $writer, + ) { } public function __destruct() diff --git a/src/SDK/Metrics/ObservableInstrumentTrait.php b/src/SDK/Metrics/ObservableInstrumentTrait.php index 86b45a3d1..6b9ea9be8 100644 --- a/src/SDK/Metrics/ObservableInstrumentTrait.php +++ b/src/SDK/Metrics/ObservableInstrumentTrait.php @@ -24,7 +24,7 @@ public function __construct( MetricWriterInterface $writer, Instrument $instrument, ReferenceCounterInterface $referenceCounter, - ArrayAccess $destructors + ArrayAccess $destructors, ) { assert($this instanceof InstrumentHandle); diff --git a/src/SDK/Metrics/StalenessHandler/DelayedStalenessHandler.php b/src/SDK/Metrics/StalenessHandler/DelayedStalenessHandler.php index 66b271018..a3fab42fa 100644 --- a/src/SDK/Metrics/StalenessHandler/DelayedStalenessHandler.php +++ b/src/SDK/Metrics/StalenessHandler/DelayedStalenessHandler.php @@ -14,17 +14,14 @@ */ final class DelayedStalenessHandler implements StalenessHandlerInterface, ReferenceCounterInterface { - private Closure $stale; - private Closure $freshen; - /** @var Closure[]|null */ private ?array $onStale = []; private int $count = 0; - public function __construct(Closure $stale, Closure $freshen) - { - $this->stale = $stale; - $this->freshen = $freshen; + public function __construct( + private Closure $stale, + private Closure $freshen, + ) { } public function acquire(bool $persistent = false): void diff --git a/src/SDK/Metrics/StalenessHandler/DelayedStalenessHandlerFactory.php b/src/SDK/Metrics/StalenessHandler/DelayedStalenessHandlerFactory.php index 0d719c74f..4e79f696e 100644 --- a/src/SDK/Metrics/StalenessHandler/DelayedStalenessHandlerFactory.php +++ b/src/SDK/Metrics/StalenessHandler/DelayedStalenessHandlerFactory.php @@ -4,31 +4,30 @@ namespace OpenTelemetry\SDK\Metrics\StalenessHandler; -use ArrayAccess; use Closure; use OpenTelemetry\SDK\Common\Time\ClockInterface; -use OpenTelemetry\SDK\Common\Util\WeakMap; use OpenTelemetry\SDK\Metrics\StalenessHandlerFactoryInterface; use OpenTelemetry\SDK\Metrics\StalenessHandlerInterface; -use Traversable; +use WeakMap; final class DelayedStalenessHandlerFactory implements StalenessHandlerFactoryInterface { - private ClockInterface $clock; private int $nanoDelay; private Closure $stale; private Closure $freshen; - /** @var ArrayAccess&Traversable */ - private $staleHandlers; + /** @var WeakMap */ + private WeakMap $staleHandlers; /** * @param float $delay delay in seconds + * @psalm-suppress PropertyTypeCoercion */ - public function __construct(ClockInterface $clock, float $delay) - { - $this->clock = $clock; + public function __construct( + private ClockInterface $clock, + float $delay, + ) { $this->nanoDelay = (int) ($delay * 1e9); $this->stale = function (DelayedStalenessHandler $handler): void { @@ -38,7 +37,7 @@ public function __construct(ClockInterface $clock, float $delay) unset($this->staleHandlers[$handler]); }; - $this->staleHandlers = WeakMap::create(); + $this->staleHandlers = new WeakMap(); } public function create(): StalenessHandlerInterface diff --git a/src/SDK/Metrics/StalenessHandler/MultiReferenceCounter.php b/src/SDK/Metrics/StalenessHandler/MultiReferenceCounter.php index 125057583..f5ae90f1b 100644 --- a/src/SDK/Metrics/StalenessHandler/MultiReferenceCounter.php +++ b/src/SDK/Metrics/StalenessHandler/MultiReferenceCounter.php @@ -11,14 +11,11 @@ */ final class MultiReferenceCounter implements ReferenceCounterInterface { - private array $referenceCounters; - /** * @param list $referenceCounters */ - public function __construct(array $referenceCounters) + public function __construct(private array $referenceCounters) { - $this->referenceCounters = $referenceCounters; } public function acquire(bool $persistent = false): void diff --git a/src/SDK/Metrics/Stream/AsynchronousMetricStream.php b/src/SDK/Metrics/Stream/AsynchronousMetricStream.php index cb32f94df..7d812925e 100644 --- a/src/SDK/Metrics/Stream/AsynchronousMetricStream.php +++ b/src/SDK/Metrics/Stream/AsynchronousMetricStream.php @@ -16,18 +16,15 @@ */ final class AsynchronousMetricStream implements MetricStreamInterface { - private AggregationInterface $aggregation; - - private int $startTimestamp; private Metric $metric; /** @var array */ private array $lastReads = []; - public function __construct(AggregationInterface $aggregation, int $startTimestamp) - { - $this->aggregation = $aggregation; - $this->startTimestamp = $startTimestamp; + public function __construct( + private AggregationInterface $aggregation, + private int $startTimestamp, + ) { $this->metric = new Metric([], [], $startTimestamp); } diff --git a/src/SDK/Metrics/Stream/Delta.php b/src/SDK/Metrics/Stream/Delta.php index a4ff56d71..1a94540b3 100644 --- a/src/SDK/Metrics/Stream/Delta.php +++ b/src/SDK/Metrics/Stream/Delta.php @@ -8,26 +8,14 @@ /** * @internal + * @phan-file-suppress PhanUndeclaredTypeParameter, PhanUndeclaredTypeProperty */ final class Delta { - public Metric $metric; - /** - * @psalm-suppress UndefinedDocblockClass - * @phan-suppress PhanUndeclaredTypeProperty - * @var int|GMP - */ - public $readers; - public ?self $prev; - /** - * @psalm-suppress UndefinedDocblockClass - * @phan-suppress PhanUndeclaredTypeParameter - * @param int|GMP $readers - */ - public function __construct(Metric $metric, $readers, ?self $prev = null) - { - $this->metric = $metric; - $this->readers = $readers; - $this->prev = $prev; + public function __construct( + public Metric $metric, + public int|GMP $readers, + public ?self $prev = null, + ) { } } diff --git a/src/SDK/Metrics/Stream/DeltaStorage.php b/src/SDK/Metrics/Stream/DeltaStorage.php index bf0073a70..005d4e0ff 100644 --- a/src/SDK/Metrics/Stream/DeltaStorage.php +++ b/src/SDK/Metrics/Stream/DeltaStorage.php @@ -10,27 +10,21 @@ /** * @internal + * @phan-file-suppress PhanUndeclaredTypeParameter, PhanUndeclaredTypeProperty */ final class DeltaStorage { - private AggregationInterface $aggregation; private Delta $head; - public function __construct(AggregationInterface $aggregation) + public function __construct(private AggregationInterface $aggregation) { - $this->aggregation = $aggregation; $this->head = new Delta(new Metric([], [], 0), 0); /** @phan-suppress-next-line PhanTypeObjectUnsetDeclaredProperty */ unset($this->head->metric); } - /** - * @psalm-suppress UndefinedDocblockClass - * @phan-suppress PhanUndeclaredTypeParameter - * @param int|GMP $readers - */ - public function add(Metric $metric, $readers): void + public function add(Metric $metric, int|GMP $readers): void { /** @phpstan-ignore-next-line */ if ($readers == 0) { @@ -87,11 +81,11 @@ private function tryUnlink(Delta $n): void } for ($c = $n->prev->prev; - $c && ($n->prev->readers & $c->readers) == 0; - $c = $c->prev) { + $c && ($n->prev->readers & $c->readers) == 0; + $c = $c->prev) { } - if ($c && $n->prev->readers == $c->readers) { + if ($c && $n->prev->readers === $c->readers) { $this->mergeInto($c->metric, $n->prev->metric); $n->prev = $n->prev->prev; } diff --git a/src/SDK/Metrics/Stream/Metric.php b/src/SDK/Metrics/Stream/Metric.php index 6b1db9eef..5c099ae25 100644 --- a/src/SDK/Metrics/Stream/Metric.php +++ b/src/SDK/Metrics/Stream/Metric.php @@ -14,31 +14,16 @@ */ final class Metric { - - /** - * @var array - */ - public array $attributes; - /** - * @var array - */ - public array $summaries; - public int $timestamp; - /** - * @var array - */ - public array $exemplars; - /** * @param array $attributes * @param array $summaries * @param array $exemplars */ - public function __construct(array $attributes, array $summaries, int $timestamp, array $exemplars = []) - { - $this->attributes = $attributes; - $this->summaries = $summaries; - $this->timestamp = $timestamp; - $this->exemplars = $exemplars; + public function __construct( + public array $attributes, + public array $summaries, + public int $timestamp, + public array $exemplars = [], + ) { } } diff --git a/src/SDK/Metrics/Stream/MetricAggregator.php b/src/SDK/Metrics/Stream/MetricAggregator.php index b1328eb07..17fd69712 100644 --- a/src/SDK/Metrics/Stream/MetricAggregator.php +++ b/src/SDK/Metrics/Stream/MetricAggregator.php @@ -16,22 +16,15 @@ */ final class MetricAggregator implements MetricAggregatorInterface { - private ?AttributeProcessorInterface $attributeProcessor; - private AggregationInterface $aggregation; - private ?ExemplarReservoirInterface $exemplarReservoir; - /** @var array */ private array $attributes = []; private array $summaries = []; public function __construct( - ?AttributeProcessorInterface $attributeProcessor, - AggregationInterface $aggregation, - ?ExemplarReservoirInterface $exemplarReservoir = null + private ?AttributeProcessorInterface $attributeProcessor, + private AggregationInterface $aggregation, + private ?ExemplarReservoirInterface $exemplarReservoir = null, ) { - $this->attributeProcessor = $attributeProcessor; - $this->aggregation = $aggregation; - $this->exemplarReservoir = $exemplarReservoir; } /** diff --git a/src/SDK/Metrics/Stream/MetricAggregatorFactory.php b/src/SDK/Metrics/Stream/MetricAggregatorFactory.php index 5866a72b7..44d8fddd0 100644 --- a/src/SDK/Metrics/Stream/MetricAggregatorFactory.php +++ b/src/SDK/Metrics/Stream/MetricAggregatorFactory.php @@ -12,13 +12,10 @@ */ final class MetricAggregatorFactory implements MetricAggregatorFactoryInterface { - private ?AttributeProcessorInterface $attributeProcessor; - private AggregationInterface $aggregation; - - public function __construct(?AttributeProcessorInterface $attributeProcessor, AggregationInterface $aggregation) - { - $this->attributeProcessor = $attributeProcessor; - $this->aggregation = $aggregation; + public function __construct( + private ?AttributeProcessorInterface $attributeProcessor, + private AggregationInterface $aggregation, + ) { } public function create(): MetricAggregatorInterface diff --git a/src/SDK/Metrics/Stream/SynchronousMetricStream.php b/src/SDK/Metrics/Stream/SynchronousMetricStream.php index 52645504c..1a7c49783 100644 --- a/src/SDK/Metrics/Stream/SynchronousMetricStream.php +++ b/src/SDK/Metrics/Stream/SynchronousMetricStream.php @@ -20,32 +20,19 @@ /** * @internal + * @phan-file-suppress PhanUndeclaredTypeParameter, PhanUndeclaredTypeProperty */ final class SynchronousMetricStream implements MetricStreamInterface { - private AggregationInterface $aggregation; - - private int $timestamp; - private DeltaStorage $delta; - /** - * @psalm-suppress UndefinedDocblockClass - * @phan-suppress PhanUndeclaredTypeProperty - * @var int|GMP - */ - private $readers = 0; - /** - * @psalm-suppress UndefinedDocblockClass - * @phan-suppress PhanUndeclaredTypeProperty - * @var int|GMP - */ - private $cumulative = 0; - - public function __construct(AggregationInterface $aggregation, int $startTimestamp) - { - $this->aggregation = $aggregation; - $this->timestamp = $startTimestamp; - $this->delta = new DeltaStorage($aggregation); + private int|GMP $readers = 0; + private int|GMP $cumulative = 0; + + public function __construct( + private AggregationInterface $aggregation, + private int $timestamp, + ) { + $this->delta = new DeltaStorage($this->aggregation); } public function temporality() diff --git a/src/SDK/Metrics/View/SelectionCriteria/AllCriteria.php b/src/SDK/Metrics/View/SelectionCriteria/AllCriteria.php index 438297324..11bada130 100644 --- a/src/SDK/Metrics/View/SelectionCriteria/AllCriteria.php +++ b/src/SDK/Metrics/View/SelectionCriteria/AllCriteria.php @@ -10,14 +10,11 @@ final class AllCriteria implements SelectionCriteriaInterface { - private iterable $criteria; - /** * @param iterable $criteria */ - public function __construct(iterable $criteria) + public function __construct(private iterable $criteria) { - $this->criteria = $criteria; } public function accepts(Instrument $instrument, InstrumentationScopeInterface $instrumentationScope): bool diff --git a/src/SDK/Metrics/View/SelectionCriteria/InstrumentationScopeNameCriteria.php b/src/SDK/Metrics/View/SelectionCriteria/InstrumentationScopeNameCriteria.php index 201d1a7b2..7823e6eb5 100644 --- a/src/SDK/Metrics/View/SelectionCriteria/InstrumentationScopeNameCriteria.php +++ b/src/SDK/Metrics/View/SelectionCriteria/InstrumentationScopeNameCriteria.php @@ -10,11 +10,8 @@ final class InstrumentationScopeNameCriteria implements SelectionCriteriaInterface { - private string $name; - - public function __construct(string $name) + public function __construct(private string $name) { - $this->name = $name; } public function accepts(Instrument $instrument, InstrumentationScopeInterface $instrumentationScope): bool diff --git a/src/SDK/Metrics/View/SelectionCriteria/InstrumentationScopeSchemaUrlCriteria.php b/src/SDK/Metrics/View/SelectionCriteria/InstrumentationScopeSchemaUrlCriteria.php index a11a1d589..08cb28668 100644 --- a/src/SDK/Metrics/View/SelectionCriteria/InstrumentationScopeSchemaUrlCriteria.php +++ b/src/SDK/Metrics/View/SelectionCriteria/InstrumentationScopeSchemaUrlCriteria.php @@ -10,11 +10,8 @@ final class InstrumentationScopeSchemaUrlCriteria implements SelectionCriteriaInterface { - private ?string $schemaUrl; - - public function __construct(?string $schemaUrl) + public function __construct(private ?string $schemaUrl) { - $this->schemaUrl = $schemaUrl; } public function accepts(Instrument $instrument, InstrumentationScopeInterface $instrumentationScope): bool diff --git a/src/SDK/Metrics/View/SelectionCriteria/InstrumentationScopeVersionCriteria.php b/src/SDK/Metrics/View/SelectionCriteria/InstrumentationScopeVersionCriteria.php index 37d180f99..d9e399d2d 100644 --- a/src/SDK/Metrics/View/SelectionCriteria/InstrumentationScopeVersionCriteria.php +++ b/src/SDK/Metrics/View/SelectionCriteria/InstrumentationScopeVersionCriteria.php @@ -10,11 +10,8 @@ final class InstrumentationScopeVersionCriteria implements SelectionCriteriaInterface { - private ?string $version; - - public function __construct(?string $version) + public function __construct(private ?string $version) { - $this->version = $version; } public function accepts(Instrument $instrument, InstrumentationScopeInterface $instrumentationScope): bool diff --git a/src/SDK/Metrics/ViewProjection.php b/src/SDK/Metrics/ViewProjection.php index 046bd6bb1..9d8e2001a 100644 --- a/src/SDK/Metrics/ViewProjection.php +++ b/src/SDK/Metrics/ViewProjection.php @@ -6,42 +6,20 @@ final class ViewProjection { - /** - * @readonly - */ - public string $name; - /** - * @readonly - */ - public ?string $unit; - /** - * @readonly - */ - public ?string $description; - /** - * @readonly - * @var list|null - */ - public ?array $attributeKeys; - /** - * @readonly - */ - public ?AggregationInterface $aggregation; - /** * @param list|null $attributeKeys */ public function __construct( - string $name, - ?string $unit, - ?string $description, - ?array $attributeKeys, - ?AggregationInterface $aggregation + /** @readonly */ + public string $name, + /** @readonly */ + public ?string $unit, + /** @readonly */ + public ?string $description, + /** @readonly */ + public ?array $attributeKeys, + /** @readonly */ + public ?AggregationInterface $aggregation, ) { - $this->name = $name; - $this->unit = $unit; - $this->description = $description; - $this->attributeKeys = $attributeKeys; - $this->aggregation = $aggregation; } } diff --git a/src/SDK/Propagation/PropagatorFactory.php b/src/SDK/Propagation/PropagatorFactory.php index 2dc349dfb..4b3970420 100644 --- a/src/SDK/Propagation/PropagatorFactory.php +++ b/src/SDK/Propagation/PropagatorFactory.php @@ -19,14 +19,12 @@ class PropagatorFactory public function create(): TextMapPropagatorInterface { $propagators = Configuration::getList(Variables::OTEL_PROPAGATORS); - switch (count($propagators)) { - case 0: - return new NoopTextMapPropagator(); - case 1: - return $this->buildPropagator($propagators[0]); - default: - return new MultiTextMapPropagator($this->buildPropagators($propagators)); - } + + return match (count($propagators)) { + 0 => new NoopTextMapPropagator(), + 1 => $this->buildPropagator($propagators[0]), + default => new MultiTextMapPropagator($this->buildPropagators($propagators)), + }; } /** diff --git a/src/SDK/Registry.php b/src/SDK/Registry.php index 2f0a20263..d04b700ad 100644 --- a/src/SDK/Registry.php +++ b/src/SDK/Registry.php @@ -11,6 +11,7 @@ use OpenTelemetry\SDK\Resource\ResourceDetectorInterface; use OpenTelemetry\SDK\Trace\SpanExporter\SpanExporterFactoryInterface; use RuntimeException; +use TypeError; /** * A registry to enable central registration of components that the SDK requires but which may be provided @@ -27,69 +28,63 @@ class Registry /** * @param TransportFactoryInterface|class-string $factory + * @throws TypeError */ - public static function registerTransportFactory(string $protocol, $factory, bool $clobber = false): void + public static function registerTransportFactory(string $protocol, TransportFactoryInterface|string $factory, bool $clobber = false): void { if (!$clobber && array_key_exists($protocol, self::$transportFactories)) { return; } if (!is_subclass_of($factory, TransportFactoryInterface::class)) { - trigger_error( + throw new TypeError( sprintf( 'Cannot register transport factory: %s must exist and implement %s', - is_string($factory) ? $factory : get_class($factory), + is_string($factory) ? $factory : $factory::class, TransportFactoryInterface::class - ), - E_USER_WARNING + ) ); - - return; } self::$transportFactories[$protocol] = $factory; } /** * @param SpanExporterFactoryInterface|class-string $factory + * @throws TypeError */ - public static function registerSpanExporterFactory(string $exporter, $factory, bool $clobber = false): void + public static function registerSpanExporterFactory(string $exporter, SpanExporterFactoryInterface|string $factory, bool $clobber = false): void { if (!$clobber && array_key_exists($exporter, self::$spanExporterFactories)) { return; } if (!is_subclass_of($factory, SpanExporterFactoryInterface::class)) { - trigger_error( + throw new TypeError( sprintf( 'Cannot register span exporter factory: %s must exist and implement %s', - is_string($factory) ? $factory : get_class($factory), + is_string($factory) ? $factory : $factory::class, SpanExporterFactoryInterface::class - ), - E_USER_WARNING + ) ); - - return; } self::$spanExporterFactories[$exporter] = $factory; } /** * @param MetricExporterFactoryInterface|class-string $factory + * @throws TypeError */ - public static function registerMetricExporterFactory(string $exporter, $factory, bool $clobber = false): void + public static function registerMetricExporterFactory(string $exporter, MetricExporterFactoryInterface|string $factory, bool $clobber = false): void { if (!$clobber && array_key_exists($exporter, self::$metricExporterFactories)) { return; } if (!is_subclass_of($factory, MetricExporterFactoryInterface::class)) { - trigger_error( + throw new TypeError( sprintf( 'Cannot register metric factory: %s must exist and implement %s', - is_string($factory) ? $factory : get_class($factory), + is_string($factory) ? $factory : $factory::class, MetricExporterFactoryInterface::class - ), - E_USER_WARNING + ) ); - - return; } self::$metricExporterFactories[$exporter] = $factory; } @@ -103,7 +98,7 @@ public static function registerLogRecordExporterFactory(string $exporter, $facto trigger_error( sprintf( 'Cannot register LogRecord exporter factory: %s must exist and implement %s', - is_string($factory) ? $factory : get_class($factory), + is_string($factory) ? $factory : $factory::class, LogRecordExporterFactoryInterface::class ), E_USER_WARNING diff --git a/src/SDK/Resource/Detectors/Composite.php b/src/SDK/Resource/Detectors/Composite.php index 9da267743..d3edd2e7b 100644 --- a/src/SDK/Resource/Detectors/Composite.php +++ b/src/SDK/Resource/Detectors/Composite.php @@ -10,14 +10,11 @@ final class Composite implements ResourceDetectorInterface { - private iterable $resourceDetectors; - /** * @param iterable $resourceDetectors */ - public function __construct(iterable $resourceDetectors) + public function __construct(private iterable $resourceDetectors) { - $this->resourceDetectors = $resourceDetectors; } public function getResource(): ResourceInfo diff --git a/src/SDK/Resource/Detectors/Constant.php b/src/SDK/Resource/Detectors/Constant.php index 7ff9d19eb..0ebe98134 100644 --- a/src/SDK/Resource/Detectors/Constant.php +++ b/src/SDK/Resource/Detectors/Constant.php @@ -9,11 +9,8 @@ final class Constant implements ResourceDetectorInterface { - private ResourceInfo $resourceInfo; - - public function __construct(ResourceInfo $resourceInfo) + public function __construct(private ResourceInfo $resourceInfo) { - $this->resourceInfo = $resourceInfo; } public function getResource(): ResourceInfo diff --git a/src/SDK/Resource/ResourceInfo.php b/src/SDK/Resource/ResourceInfo.php index da43e820e..8713c28d0 100644 --- a/src/SDK/Resource/ResourceInfo.php +++ b/src/SDK/Resource/ResourceInfo.php @@ -21,13 +21,10 @@ class ResourceInfo { use LogsMessagesTrait; - private AttributesInterface $attributes; - private ?string $schemaUrl; - - private function __construct(AttributesInterface $attributes, ?string $schemaUrl = null) - { - $this->attributes = $attributes; - $this->schemaUrl = $schemaUrl; + private function __construct( + private AttributesInterface $attributes, + private ?string $schemaUrl = null, + ) { } public static function create(AttributesInterface $attributes, ?string $schemaUrl = null): self diff --git a/src/SDK/Sdk.php b/src/SDK/Sdk.php index d9dfcf96d..ac82c6052 100644 --- a/src/SDK/Sdk.php +++ b/src/SDK/Sdk.php @@ -15,21 +15,12 @@ class Sdk { private const OTEL_PHP_DISABLED_INSTRUMENTATIONS_ALL = 'all'; - private TracerProviderInterface $tracerProvider; - private MeterProviderInterface $meterProvider; - private LoggerProviderInterface $loggerProvider; - private TextMapPropagatorInterface $propagator; - public function __construct( - TracerProviderInterface $tracerProvider, - MeterProviderInterface $meterProvider, - LoggerProviderInterface $loggerProvider, - TextMapPropagatorInterface $propagator + private TracerProviderInterface $tracerProvider, + private MeterProviderInterface $meterProvider, + private LoggerProviderInterface $loggerProvider, + private TextMapPropagatorInterface $propagator, ) { - $this->tracerProvider = $tracerProvider; - $this->meterProvider = $meterProvider; - $this->loggerProvider = $loggerProvider; - $this->propagator = $propagator; } public static function isDisabled(): bool diff --git a/src/SDK/SdkAutoloader.php b/src/SDK/SdkAutoloader.php index 341666a60..db288fe94 100644 --- a/src/SDK/SdkAutoloader.php +++ b/src/SDK/SdkAutoloader.php @@ -55,7 +55,7 @@ public static function autoload(): bool ->withMeterProvider($meterProvider) ->withLoggerProvider($loggerProvider) ->withPropagator($propagator) - ; + ; }); return true; @@ -92,7 +92,7 @@ public static function isEnabled(): bool { try { $enabled = Configuration::getBoolean(Variables::OTEL_PHP_AUTOLOAD_ENABLED); - } catch (InvalidArgumentException $e) { + } catch (InvalidArgumentException) { //invalid setting, assume false return false; } diff --git a/src/SDK/SdkBuilder.php b/src/SDK/SdkBuilder.php index 2090c4731..0baeb95fb 100644 --- a/src/SDK/SdkBuilder.php +++ b/src/SDK/SdkBuilder.php @@ -20,7 +20,7 @@ class SdkBuilder { private ?TracerProviderInterface $tracerProvider = null; - private ?MeterProviderInterface $meterProvider = null; + private ?MeterProviderInterface $meterProvider = null; private ?LoggerProviderInterface $loggerProvider = null; private ?TextMapPropagatorInterface $propagator = null; private bool $autoShutdown = false; diff --git a/src/SDK/Trace/Behavior/LoggerAwareTrait.php b/src/SDK/Trace/Behavior/LoggerAwareTrait.php index 24f5e56a8..8f22ad2df 100644 --- a/src/SDK/Trace/Behavior/LoggerAwareTrait.php +++ b/src/SDK/Trace/Behavior/LoggerAwareTrait.php @@ -15,19 +15,11 @@ trait LoggerAwareTrait private string $defaultLogLevel = LogLevel::INFO; - /** - * @param string $logLevel - */ public function setDefaultLogLevel(string $logLevel): void { $this->defaultLogLevel = $logLevel; } - /** - * @param string $message - * @param array $context - * @param string|null $level - */ protected function log(string $message, array $context = [], ?string $level = null): void { $this->getLogger()->log( diff --git a/src/SDK/Trace/Behavior/UsesSpanConverterTrait.php b/src/SDK/Trace/Behavior/UsesSpanConverterTrait.php index 4802cd15b..0dbe84b67 100644 --- a/src/SDK/Trace/Behavior/UsesSpanConverterTrait.php +++ b/src/SDK/Trace/Behavior/UsesSpanConverterTrait.php @@ -12,9 +12,6 @@ trait UsesSpanConverterTrait { private ?SpanConverterInterface $converter = null; - /** - * @param SpanConverterInterface $converter - */ protected function setSpanConverter(SpanConverterInterface $converter): void { $this->converter = $converter; @@ -30,7 +27,6 @@ public function getSpanConverter(): SpanConverterInterface } /** - * @param SpanDataInterface $span * @return array * @psalm-suppress PossiblyNullReference */ diff --git a/src/SDK/Trace/Event.php b/src/SDK/Trace/Event.php index 28cb39bb1..468451fce 100644 --- a/src/SDK/Trace/Event.php +++ b/src/SDK/Trace/Event.php @@ -9,15 +9,11 @@ final class Event implements EventInterface { - private string $name; - private int $timestamp; - private AttributesInterface $attributes; - - public function __construct(string $name, int $timestamp, AttributesInterface $attributes) - { - $this->name = $name; - $this->timestamp = $timestamp; - $this->attributes = $attributes; + public function __construct( + private string $name, + private int $timestamp, + private AttributesInterface $attributes, + ) { } public function getAttributes(): AttributesInterface diff --git a/src/SDK/Trace/ImmutableSpan.php b/src/SDK/Trace/ImmutableSpan.php index 57836d4c3..77e29cb3e 100644 --- a/src/SDK/Trace/ImmutableSpan.php +++ b/src/SDK/Trace/ImmutableSpan.php @@ -15,48 +15,22 @@ */ final class ImmutableSpan implements SpanDataInterface { - private Span $span; - - /** @var non-empty-string */ - private string $name; - - /** @var list */ - private array $events; - - /** @var list */ - private array $links; - - private AttributesInterface $attributes; - private int $totalRecordedEvents; - private StatusDataInterface $status; - private int $endEpochNanos; - private bool $hasEnded; - /** * @param non-empty-string $name * @param list $links * @param list $events */ public function __construct( - Span $span, - string $name, - array $links, - array $events, - AttributesInterface $attributes, - int $totalRecordedEvents, - StatusDataInterface $status, - int $endEpochNanos, - bool $hasEnded + private Span $span, + private string $name, + private array $links, + private array $events, + private AttributesInterface $attributes, + private int $totalRecordedEvents, + private StatusDataInterface $status, + private int $endEpochNanos, + private bool $hasEnded, ) { - $this->span = $span; - $this->name = $name; - $this->links = $links; - $this->events = $events; - $this->attributes = $attributes; - $this->totalRecordedEvents = $totalRecordedEvents; - $this->status = $status; - $this->endEpochNanos = $endEpochNanos; - $this->hasEnded = $hasEnded; } public function getKind(): int diff --git a/src/SDK/Trace/Link.php b/src/SDK/Trace/Link.php index 9927839e7..75f622bd8 100644 --- a/src/SDK/Trace/Link.php +++ b/src/SDK/Trace/Link.php @@ -9,13 +9,10 @@ final class Link implements LinkInterface { - private AttributesInterface $attributes; - private API\SpanContextInterface $context; - - public function __construct(API\SpanContextInterface $context, AttributesInterface $attributes) - { - $this->context = $context; - $this->attributes = $attributes; + public function __construct( + private API\SpanContextInterface $context, + private AttributesInterface $attributes, + ) { } public function getSpanContext(): API\SpanContextInterface diff --git a/src/SDK/Trace/RandomIdGenerator.php b/src/SDK/Trace/RandomIdGenerator.php index 39767fb0f..0024a1a64 100644 --- a/src/SDK/Trace/RandomIdGenerator.php +++ b/src/SDK/Trace/RandomIdGenerator.php @@ -37,7 +37,7 @@ private function randomHex(int $hexLength): string { try { return bin2hex(random_bytes(intdiv($hexLength, 2))); - } catch (Throwable $e) { + } catch (Throwable) { return $this->fallbackAlgorithm($hexLength); } } diff --git a/src/SDK/Trace/Sampler/AlwaysOffSampler.php b/src/SDK/Trace/Sampler/AlwaysOffSampler.php index ee7e70a56..3ee5dcc8e 100644 --- a/src/SDK/Trace/Sampler/AlwaysOffSampler.php +++ b/src/SDK/Trace/Sampler/AlwaysOffSampler.php @@ -30,7 +30,7 @@ public function shouldSample( string $spanName, int $spanKind, AttributesInterface $attributes, - array $links + array $links, ): SamplingResult { $parentSpan = Span::fromContext($parentContext); $parentSpanContext = $parentSpan->getContext(); diff --git a/src/SDK/Trace/Sampler/AlwaysOnSampler.php b/src/SDK/Trace/Sampler/AlwaysOnSampler.php index df61d1aee..29a45a35f 100644 --- a/src/SDK/Trace/Sampler/AlwaysOnSampler.php +++ b/src/SDK/Trace/Sampler/AlwaysOnSampler.php @@ -30,7 +30,7 @@ public function shouldSample( string $spanName, int $spanKind, AttributesInterface $attributes, - array $links + array $links, ): SamplingResult { $parentSpan = Span::fromContext($parentContext); $parentSpanContext = $parentSpan->getContext(); diff --git a/src/SDK/Trace/Sampler/ParentBased.php b/src/SDK/Trace/Sampler/ParentBased.php index db801d3d8..0b26102c1 100644 --- a/src/SDK/Trace/Sampler/ParentBased.php +++ b/src/SDK/Trace/Sampler/ParentBased.php @@ -29,8 +29,6 @@ */ class ParentBased implements SamplerInterface { - private SamplerInterface $root; - private SamplerInterface $remoteParentSampler; private SamplerInterface $remoteParentNotSampler; @@ -49,13 +47,12 @@ class ParentBased implements SamplerInterface * @param SamplerInterface|null $localParentNotSampler Sampler called for the span with the local not sampled parent. When null, `AlwaysOffSampler` is used. */ public function __construct( - SamplerInterface $root, + private SamplerInterface $root, ?SamplerInterface $remoteParentSampler = null, ?SamplerInterface $remoteParentNotSampler = null, ?SamplerInterface $localParentSampler = null, - ?SamplerInterface $localParentNotSampler = null + ?SamplerInterface $localParentNotSampler = null, ) { - $this->root = $root; $this->remoteParentSampler = $remoteParentSampler ?? new AlwaysOnSampler(); $this->remoteParentNotSampler = $remoteParentNotSampler ?? new AlwaysOffSampler(); $this->localParentSampler = $localParentSampler ?? new AlwaysOnSampler(); @@ -72,7 +69,7 @@ public function shouldSample( string $spanName, int $spanKind, AttributesInterface $attributes, - array $links + array $links, ): SamplingResult { $parentSpan = Span::fromContext($parentContext); $parentSpanContext = $parentSpan->getContext(); diff --git a/src/SDK/Trace/Sampler/TraceIdRatioBasedSampler.php b/src/SDK/Trace/Sampler/TraceIdRatioBasedSampler.php index c11a90d5d..0b26087d4 100644 --- a/src/SDK/Trace/Sampler/TraceIdRatioBasedSampler.php +++ b/src/SDK/Trace/Sampler/TraceIdRatioBasedSampler.php @@ -24,7 +24,6 @@ class TraceIdRatioBasedSampler implements SamplerInterface private float $probability; /** - * TraceIdRatioBasedSampler constructor. * @param float $probability Probability float value between 0.0 and 1.0. */ public function __construct(float $probability) @@ -45,7 +44,7 @@ public function shouldSample( string $spanName, int $spanKind, AttributesInterface $attributes, - array $links + array $links, ): SamplingResult { // TODO: Add config to adjust which spans get sampled (only default from specification is implemented) $parentSpan = Span::fromContext($parentContext); diff --git a/src/SDK/Trace/SamplerFactory.php b/src/SDK/Trace/SamplerFactory.php index f99674d79..09efbfc81 100644 --- a/src/SDK/Trace/SamplerFactory.php +++ b/src/SDK/Trace/SamplerFactory.php @@ -21,7 +21,7 @@ public function create(): SamplerInterface { $name = Configuration::getString(Env::OTEL_TRACES_SAMPLER); - if (strpos($name, self::TRACEIDRATIO_PREFIX) !== false) { + if (str_contains($name, self::TRACEIDRATIO_PREFIX)) { $arg = Configuration::getRatio(Env::OTEL_TRACES_SAMPLER_ARG); switch ($name) { @@ -32,17 +32,12 @@ public function create(): SamplerInterface } } - switch ($name) { - case Values::VALUE_ALWAYS_ON: - return new AlwaysOnSampler(); - case Values::VALUE_ALWAYS_OFF: - return new AlwaysOffSampler(); - case Values::VALUE_PARENT_BASED_ALWAYS_ON: - return new ParentBased(new AlwaysOnSampler()); - case Values::VALUE_PARENT_BASED_ALWAYS_OFF: - return new ParentBased(new AlwaysOffSampler()); - default: - throw new InvalidArgumentException(sprintf('Unknown sampler: %s', $name)); - } + return match ($name) { + Values::VALUE_ALWAYS_ON => new AlwaysOnSampler(), + Values::VALUE_ALWAYS_OFF => new AlwaysOffSampler(), + Values::VALUE_PARENT_BASED_ALWAYS_ON => new ParentBased(new AlwaysOnSampler()), + Values::VALUE_PARENT_BASED_ALWAYS_OFF => new ParentBased(new AlwaysOffSampler()), + default => throw new InvalidArgumentException(sprintf('Unknown sampler: %s', $name)), + }; } } diff --git a/src/SDK/Trace/SamplerInterface.php b/src/SDK/Trace/SamplerInterface.php index de1147fa6..ad72b7392 100644 --- a/src/SDK/Trace/SamplerInterface.php +++ b/src/SDK/Trace/SamplerInterface.php @@ -34,7 +34,7 @@ public function shouldSample( string $spanName, int $spanKind, AttributesInterface $attributes, - array $links + array $links, ): SamplingResult; /** diff --git a/src/SDK/Trace/SamplingResult.php b/src/SDK/Trace/SamplingResult.php index 5701b7bc6..d78bca8ab 100644 --- a/src/SDK/Trace/SamplingResult.php +++ b/src/SDK/Trace/SamplingResult.php @@ -24,25 +24,13 @@ final class SamplingResult public const RECORD_AND_SAMPLE = 2; /** - * @var int A sampling Decision. + * @param ?API\TraceStateInterface $traceState A Tracestate that will be associated with the Span through the new SpanContext. */ - private int $decision; - - /** - * @var iterable A set of span Attributes that will also be added to the Span. - */ - private iterable $attributes; - - /** - * @var ?API\TraceStateInterface A Tracestate that will be associated with the Span through the new SpanContext. - */ - private ?API\TraceStateInterface $traceState; - - public function __construct(int $decision, iterable $attributes = [], ?API\TraceStateInterface $traceState = null) - { - $this->decision = $decision; - $this->attributes = $attributes; - $this->traceState = $traceState; + public function __construct( + private int $decision, + private iterable $attributes = [], + private ?API\TraceStateInterface $traceState = null, + ) { } /** diff --git a/src/SDK/Trace/Span.php b/src/SDK/Trace/Span.php index f72ec1bd7..6e55f6e72 100644 --- a/src/SDK/Trace/Span.php +++ b/src/SDK/Trace/Span.php @@ -4,7 +4,6 @@ namespace OpenTelemetry\SDK\Trace; -use function get_class; use OpenTelemetry\API\Trace as API; use OpenTelemetry\Context\ContextInterface; use OpenTelemetry\SDK\Common\Attribute\AttributesBuilderInterface; @@ -18,47 +17,8 @@ final class Span extends API\Span implements ReadWriteSpanInterface { - /** @readonly */ - private API\SpanContextInterface $context; - - /** @readonly */ - private API\SpanContextInterface $parentSpanContext; - - /** @readonly */ - private SpanLimits $spanLimits; - - /** @readonly */ - private SpanProcessorInterface $spanProcessor; - - /** - * @readonly - * - * @var list - */ - private array $links; - - /** @readonly */ - private int $totalRecordedLinks; - - /** @readonly */ - private int $kind; - - /** @readonly */ - private ResourceInfo $resource; - - /** @readonly */ - private InstrumentationScopeInterface $instrumentationScope; - - /** @readonly */ - private int $startEpochNanos; - - /** @var non-empty-string */ - private string $name; - /** @var list */ private array $events = []; - - private AttributesBuilderInterface $attributesBuilder; private int $totalRecordedEvents = 0; private StatusDataInterface $status; private int $endEpochNanos = 0; @@ -69,32 +29,30 @@ final class Span extends API\Span implements ReadWriteSpanInterface * @param list $links */ private function __construct( - string $name, - API\SpanContextInterface $context, - InstrumentationScopeInterface $instrumentationScope, - int $kind, - API\SpanContextInterface $parentSpanContext, - SpanLimits $spanLimits, - SpanProcessorInterface $spanProcessor, - ResourceInfo $resource, - AttributesBuilderInterface $attributesBuilder, - array $links, - int $totalRecordedLinks, - int $startEpochNanos + private string $name, + /** @readonly */ + private API\SpanContextInterface $context, + /** @readonly */ + private InstrumentationScopeInterface $instrumentationScope, + /** @readonly */ + private int $kind, + /** @readonly */ + private API\SpanContextInterface $parentSpanContext, + /** @readonly */ + private SpanLimits $spanLimits, + /** @readonly */ + private SpanProcessorInterface $spanProcessor, + /** @readonly */ + private ResourceInfo $resource, + private AttributesBuilderInterface $attributesBuilder, + /** @readonly */ + private array $links, + /** @readonly */ + private int $totalRecordedLinks, + /** @readonly */ + private int $startEpochNanos, ) { - $this->context = $context; - $this->instrumentationScope = $instrumentationScope; - $this->parentSpanContext = $parentSpanContext; - $this->links = $links; - $this->totalRecordedLinks = $totalRecordedLinks; - $this->name = $name; - $this->kind = $kind; - $this->spanProcessor = $spanProcessor; - $this->resource = $resource; - $this->startEpochNanos = $startEpochNanos; - $this->attributesBuilder = $attributesBuilder; $this->status = StatusData::unset(); - $this->spanLimits = $spanLimits; } /** @@ -121,7 +79,7 @@ public static function startSpan( AttributesBuilderInterface $attributesBuilder, array $links, int $totalRecordedLinks, - int $startEpochNanos + int $startEpochNanos, ): self { $span = new self( $name, @@ -224,7 +182,7 @@ public function recordException(Throwable $exception, iterable $attributes = [], $timestamp ??= ClockFactory::getDefault()->now(); $eventAttributesBuilder = $this->spanLimits->getEventAttributesFactory()->builder([ - 'exception.type' => get_class($exception), + 'exception.type' => $exception::class, 'exception.message' => $exception->getMessage(), 'exception.stacktrace' => StackTraceFormatter::format($exception), ]); diff --git a/src/SDK/Trace/SpanBuilder.php b/src/SDK/Trace/SpanBuilder.php index 2867c01c8..2d3320512 100644 --- a/src/SDK/Trace/SpanBuilder.php +++ b/src/SDK/Trace/SpanBuilder.php @@ -13,20 +13,7 @@ final class SpanBuilder implements API\SpanBuilderInterface { - /** - * @var non-empty-string - * @readonly - */ - private string $spanName; - - /** @readonly */ - private InstrumentationScopeInterface $instrumentationScope; - - /** @readonly */ - private TracerSharedState $tracerSharedState; - - /** @var ContextInterface|false|null */ - private $parentContext = null; + private ContextInterface|false|null $parentContext = null; /** * @psalm-var API\SpanKind::KIND_* @@ -42,18 +29,18 @@ final class SpanBuilder implements API\SpanBuilderInterface /** @param non-empty-string $spanName */ public function __construct( - string $spanName, - InstrumentationScopeInterface $instrumentationScope, - TracerSharedState $tracerSharedState + /** @readonly */ + private string $spanName, + /** @readonly */ + private InstrumentationScopeInterface $instrumentationScope, + /** @readonly */ + private TracerSharedState $tracerSharedState, ) { - $this->spanName = $spanName; - $this->instrumentationScope = $instrumentationScope; - $this->tracerSharedState = $tracerSharedState; - $this->attributesBuilder = $tracerSharedState->getSpanLimits()->getAttributesFactory()->builder(); + $this->attributesBuilder = $this->tracerSharedState->getSpanLimits()->getAttributesFactory()->builder(); } /** @inheritDoc */ - public function setParent($context): API\SpanBuilderInterface + public function setParent(ContextInterface|false|null $context): API\SpanBuilderInterface { $this->parentContext = $context; @@ -86,7 +73,7 @@ public function addLink(API\SpanContextInterface $context, iterable $attributes } /** @inheritDoc */ - public function setAttribute(string $key, $value): API\SpanBuilderInterface + public function setAttribute(string $key, mixed $value): API\SpanBuilderInterface { $this->attributesBuilder[$key] = $value; diff --git a/src/SDK/Trace/SpanExporter/ConsoleSpanExporter.php b/src/SDK/Trace/SpanExporter/ConsoleSpanExporter.php index 482d122cc..96bbec6af 100644 --- a/src/SDK/Trace/SpanExporter/ConsoleSpanExporter.php +++ b/src/SDK/Trace/SpanExporter/ConsoleSpanExporter.php @@ -18,11 +18,10 @@ class ConsoleSpanExporter implements SpanExporterInterface use UsesSpanConverterTrait; use LogsMessagesTrait; - private TransportInterface $transport; - - public function __construct(TransportInterface $transport, ?SpanConverterInterface $converter = null) - { - $this->transport = $transport; + public function __construct( + private TransportInterface $transport, + ?SpanConverterInterface $converter = null, + ) { $this->setSpanConverter($converter ?? new FriendlySpanConverter()); } diff --git a/src/SDK/Trace/SpanExporter/FriendlySpanConverter.php b/src/SDK/Trace/SpanExporter/FriendlySpanConverter.php index f18893298..a76ffa245 100644 --- a/src/SDK/Trace/SpanExporter/FriendlySpanConverter.php +++ b/src/SDK/Trace/SpanExporter/FriendlySpanConverter.php @@ -47,10 +47,7 @@ public function convert(iterable $spans): array } /** - * friendlySpan does the heavy lifting converting a span into an array - * - * @param SpanDataInterface $span - * @return array + * convertSpan does the heavy lifting converting a span into an array */ private function convertSpan(SpanDataInterface $span): array { @@ -69,10 +66,6 @@ private function convertSpan(SpanDataInterface $span): array ]; } - /** - * @param SpanContextInterface $context - * @return array - */ private function convertContext(SpanContextInterface $context): array { return [ @@ -83,19 +76,11 @@ private function convertContext(SpanContextInterface $context): array ]; } - /** - * @param ResourceInfo $resource - * @return array - */ private function convertResource(ResourceInfo $resource): array { return $resource->getAttributes()->toArray(); } - /** - * @param SpanContextInterface $context - * @return string - */ private function covertParentContext(SpanContextInterface $context): string { return $context->isValid() ? $context->getSpanId() : ''; @@ -103,9 +88,6 @@ private function covertParentContext(SpanContextInterface $context): string /** * Translates SpanKind from its integer representation to a more human friendly string. - * - * @param int $kind - * @return string */ private function convertKind(int $kind): string { @@ -115,19 +97,11 @@ private function convertKind(int $kind): string )[$kind]; } - /** - * @param \OpenTelemetry\SDK\Common\Attribute\AttributesInterface $attributes - * @return array - */ private function convertAttributes(AttributesInterface $attributes): array { return $attributes->toArray(); } - /** - * @param StatusDataInterface $status - * @return array - */ private function covertStatus(StatusDataInterface $status): array { return [ @@ -138,7 +112,6 @@ private function covertStatus(StatusDataInterface $status): array /** * @param array $events - * @return array */ private function convertEvents(array $events): array { @@ -157,7 +130,6 @@ private function convertEvents(array $events): array /** * @param array $links - * @return array */ private function convertLinks(array $links): array { diff --git a/src/SDK/Trace/SpanExporter/LoggerDecorator.php b/src/SDK/Trace/SpanExporter/LoggerDecorator.php index b7cf511a5..f50740467 100644 --- a/src/SDK/Trace/SpanExporter/LoggerDecorator.php +++ b/src/SDK/Trace/SpanExporter/LoggerDecorator.php @@ -23,7 +23,7 @@ class LoggerDecorator implements SpanExporterInterface, LoggerAwareInterface public function __construct( SpanExporterInterface $decorated, ?LoggerInterface $logger = null, - ?SpanConverterInterface $converter = null + ?SpanConverterInterface $converter = null, ) { $this->setDecorated($decorated); $this->setLogger($logger ?? new NullLogger()); @@ -35,10 +35,6 @@ protected function beforeExport(iterable $spans): iterable return $spans; } - /** - * @param iterable $spans - * @param bool $exportSuccess - */ protected function afterExport(iterable $spans, bool $exportSuccess): void { if ($exportSuccess) { diff --git a/src/SDK/Trace/SpanExporter/LoggerExporter.php b/src/SDK/Trace/SpanExporter/LoggerExporter.php index 1969a5426..5e2ca59ce 100644 --- a/src/SDK/Trace/SpanExporter/LoggerExporter.php +++ b/src/SDK/Trace/SpanExporter/LoggerExporter.php @@ -27,19 +27,12 @@ class LoggerExporter implements SpanExporterInterface, LoggerAwareInterface private string $serviceName; private int $granularity = self::GRANULARITY_AGGREGATE; - /** - * @param string $serviceName - * @param LoggerInterface|null $logger - * @param string|null $defaultLogLevel - * @param SpanConverterInterface|null $converter - * @param int $granularity - */ public function __construct( string $serviceName, ?LoggerInterface $logger = null, ?string $defaultLogLevel = LogLevel::DEBUG, ?SpanConverterInterface $converter = null, - int $granularity = 1 + int $granularity = 1, ) { $this->setServiceName($serviceName); $this->setLogger($logger ?? new NullLogger()); @@ -53,24 +46,18 @@ public function doExport(iterable $spans): bool { try { $this->doLog($spans); - } catch (Throwable $t) { + } catch (Throwable) { return false; } return true; } - /** - * @param string $serviceName - */ private function setServiceName(string $serviceName): void { $this->serviceName = $serviceName; } - /** - * @param int $granularity - */ public function setGranularity(int $granularity): void { $this->granularity = $granularity === self::GRANULARITY_SPAN @@ -78,9 +65,6 @@ public function setGranularity(int $granularity): void : self::GRANULARITY_AGGREGATE; } - /** - * @param iterable $spans - */ private function doLog(iterable $spans): void { if ($this->granularity === self::GRANULARITY_AGGREGATE) { diff --git a/src/SDK/Trace/SpanLimits.php b/src/SDK/Trace/SpanLimits.php index 4b07649fc..f383ca0eb 100644 --- a/src/SDK/Trace/SpanLimits.php +++ b/src/SDK/Trace/SpanLimits.php @@ -15,12 +15,6 @@ final class SpanLimits public const DEFAULT_EVENT_ATTRIBUTE_COUNT_LIMIT = 128; public const DEFAULT_LINK_ATTRIBUTE_COUNT_LIMIT = 128; - private AttributesFactoryInterface $attributesFactory; - private AttributesFactoryInterface $eventAttributesFactory; - private AttributesFactoryInterface $linkAttributesFactory; - private int $eventCountLimit; - private int $linkCountLimit; - public function getAttributesFactory(): AttributesFactoryInterface { return $this->attributesFactory; @@ -52,16 +46,11 @@ public function getLinkCountLimit(): int * @internal Use {@see SpanLimitsBuilder} to create {@see SpanLimits} instance. */ public function __construct( - AttributesFactoryInterface $attributesFactory, - AttributesFactoryInterface $eventAttributesFactory, - AttributesFactoryInterface $linkAttributesFactory, - int $eventCountLimit, - int $linkCountLimit + private AttributesFactoryInterface $attributesFactory, + private AttributesFactoryInterface $eventAttributesFactory, + private AttributesFactoryInterface $linkAttributesFactory, + private int $eventCountLimit, + private int $linkCountLimit, ) { - $this->attributesFactory = $attributesFactory; - $this->eventAttributesFactory = $eventAttributesFactory; - $this->linkAttributesFactory = $linkAttributesFactory; - $this->eventCountLimit = $eventCountLimit; - $this->linkCountLimit = $linkCountLimit; } } diff --git a/src/SDK/Trace/SpanProcessor/BatchSpanProcessor.php b/src/SDK/Trace/SpanProcessor/BatchSpanProcessor.php index 58032749e..d59ab8d48 100644 --- a/src/SDK/Trace/SpanProcessor/BatchSpanProcessor.php +++ b/src/SDK/Trace/SpanProcessor/BatchSpanProcessor.php @@ -38,13 +38,9 @@ class BatchSpanProcessor implements SpanProcessorInterface private const ATTRIBUTES_PROCESSED = self::ATTRIBUTES_PROCESSOR + ['state' => 'processed']; private const ATTRIBUTES_DROPPED = self::ATTRIBUTES_PROCESSOR + ['state' => 'dropped']; private const ATTRIBUTES_FREE = self::ATTRIBUTES_PROCESSOR + ['state' => 'free']; - - private SpanExporterInterface $exporter; - private ClockInterface $clock; private int $maxQueueSize; private int $scheduledDelayNanos; private int $maxExportBatchSize; - private bool $autoFlush; private ContextInterface $exportContext; private ?int $nextScheduledRun = null; @@ -63,14 +59,14 @@ class BatchSpanProcessor implements SpanProcessorInterface private bool $closed = false; public function __construct( - SpanExporterInterface $exporter, - ClockInterface $clock, + private SpanExporterInterface $exporter, + private ClockInterface $clock, int $maxQueueSize = self::DEFAULT_MAX_QUEUE_SIZE, int $scheduledDelayMillis = self::DEFAULT_SCHEDULE_DELAY, int $exportTimeoutMillis = self::DEFAULT_EXPORT_TIMEOUT, int $maxExportBatchSize = self::DEFAULT_MAX_EXPORT_BATCH_SIZE, - bool $autoFlush = true, - ?MeterProviderInterface $meterProvider = null + private bool $autoFlush = true, + ?MeterProviderInterface $meterProvider = null, ) { if ($maxQueueSize <= 0) { throw new InvalidArgumentException(sprintf('Maximum queue size (%d) must be greater than zero', $maxQueueSize)); @@ -87,13 +83,9 @@ public function __construct( if ($maxExportBatchSize > $maxQueueSize) { throw new InvalidArgumentException(sprintf('Maximum export batch size (%d) must be less than or equal to maximum queue size (%d)', $maxExportBatchSize, $maxQueueSize)); } - - $this->exporter = $exporter; - $this->clock = $clock; $this->maxQueueSize = $maxQueueSize; $this->scheduledDelayNanos = $scheduledDelayMillis * 1_000_000; $this->maxExportBatchSize = $maxExportBatchSize; - $this->autoFlush = $autoFlush; $this->exportContext = Context::getCurrent(); $this->queue = new SplQueue(); diff --git a/src/SDK/Trace/SpanProcessor/BatchSpanProcessorBuilder.php b/src/SDK/Trace/SpanProcessor/BatchSpanProcessorBuilder.php index 8e81e7dd6..88a826f3a 100644 --- a/src/SDK/Trace/SpanProcessor/BatchSpanProcessorBuilder.php +++ b/src/SDK/Trace/SpanProcessor/BatchSpanProcessorBuilder.php @@ -10,12 +10,10 @@ class BatchSpanProcessorBuilder { - private SpanExporterInterface $exporter; private ?MeterProviderInterface $meterProvider = null; - public function __construct(SpanExporterInterface $exporter) + public function __construct(private SpanExporterInterface $exporter) { - $this->exporter = $exporter; } public function setMeterProvider(MeterProviderInterface $meterProvider): self diff --git a/src/SDK/Trace/SpanProcessor/SimpleSpanProcessor.php b/src/SDK/Trace/SpanProcessor/SimpleSpanProcessor.php index 4e86e79ab..246345fa9 100644 --- a/src/SDK/Trace/SpanProcessor/SimpleSpanProcessor.php +++ b/src/SDK/Trace/SpanProcessor/SimpleSpanProcessor.php @@ -20,8 +20,6 @@ class SimpleSpanProcessor implements SpanProcessorInterface { use LogsMessagesTrait; - - private SpanExporterInterface $exporter; private ContextInterface $exportContext; private bool $running = false; @@ -30,10 +28,8 @@ class SimpleSpanProcessor implements SpanProcessorInterface private bool $closed = false; - public function __construct(SpanExporterInterface $exporter) + public function __construct(private SpanExporterInterface $exporter) { - $this->exporter = $exporter; - $this->exportContext = Context::getCurrent(); $this->queue = new SplQueue(); } diff --git a/src/SDK/Trace/SpanProcessorFactory.php b/src/SDK/Trace/SpanProcessorFactory.php index 39144cdf6..3279c56ee 100644 --- a/src/SDK/Trace/SpanProcessorFactory.php +++ b/src/SDK/Trace/SpanProcessorFactory.php @@ -24,25 +24,21 @@ public function create(?SpanExporterInterface $exporter = null, ?MeterProviderIn } $name = Configuration::getEnum(Env::OTEL_PHP_TRACES_PROCESSOR); - switch ($name) { - case Values::VALUE_BATCH: - return new BatchSpanProcessor( - $exporter, - ClockFactory::getDefault(), - Configuration::getInt(Env::OTEL_BSP_MAX_QUEUE_SIZE, BatchSpanProcessor::DEFAULT_MAX_QUEUE_SIZE), - Configuration::getInt(Env::OTEL_BSP_SCHEDULE_DELAY, BatchSpanProcessor::DEFAULT_SCHEDULE_DELAY), - Configuration::getInt(Env::OTEL_BSP_EXPORT_TIMEOUT, BatchSpanProcessor::DEFAULT_EXPORT_TIMEOUT), - Configuration::getInt(Env::OTEL_BSP_MAX_EXPORT_BATCH_SIZE, BatchSpanProcessor::DEFAULT_MAX_EXPORT_BATCH_SIZE), - true, //autoflush - $meterProvider ?? new NoopMeterProvider(), - ); - case Values::VALUE_SIMPLE: - return new SimpleSpanProcessor($exporter); - case Values::VALUE_NOOP: - case Values::VALUE_NONE: - return NoopSpanProcessor::getInstance(); - default: - throw new InvalidArgumentException('Unknown processor: ' . $name); - } + + return match ($name) { + Values::VALUE_BATCH => new BatchSpanProcessor( + $exporter, + ClockFactory::getDefault(), + Configuration::getInt(Env::OTEL_BSP_MAX_QUEUE_SIZE, BatchSpanProcessor::DEFAULT_MAX_QUEUE_SIZE), + Configuration::getInt(Env::OTEL_BSP_SCHEDULE_DELAY, BatchSpanProcessor::DEFAULT_SCHEDULE_DELAY), + Configuration::getInt(Env::OTEL_BSP_EXPORT_TIMEOUT, BatchSpanProcessor::DEFAULT_EXPORT_TIMEOUT), + Configuration::getInt(Env::OTEL_BSP_MAX_EXPORT_BATCH_SIZE, BatchSpanProcessor::DEFAULT_MAX_EXPORT_BATCH_SIZE), + true, //autoflush + $meterProvider ?? new NoopMeterProvider(), + ), + Values::VALUE_SIMPLE => new SimpleSpanProcessor($exporter), + Values::VALUE_NOOP, Values::VALUE_NONE => NoopSpanProcessor::getInstance(), + default => throw new InvalidArgumentException('Unknown processor: ' . $name), + }; } } diff --git a/src/SDK/Trace/StatusData.php b/src/SDK/Trace/StatusData.php index c28ea22ab..c53cda0a4 100644 --- a/src/SDK/Trace/StatusData.php +++ b/src/SDK/Trace/StatusData.php @@ -11,16 +11,12 @@ final class StatusData implements StatusDataInterface private static ?self $ok = null; private static ?self $unset = null; private static ?self $error = null; - private string $code; - private string $description; /** @psalm-param API\StatusCode::STATUS_* $code */ public function __construct( - string $code, - string $description + private string $code, + private string $description, ) { - $this->code = $code; - $this->description = $description; } /** @psalm-param API\StatusCode::STATUS_* $code */ diff --git a/src/SDK/Trace/Tracer.php b/src/SDK/Trace/Tracer.php index 913773f60..baf7a049c 100644 --- a/src/SDK/Trace/Tracer.php +++ b/src/SDK/Trace/Tracer.php @@ -13,18 +13,12 @@ class Tracer implements API\TracerInterface { public const FALLBACK_SPAN_NAME = 'empty'; - /** @readonly */ - private TracerSharedState $tracerSharedState; - - /** @readonly */ - private InstrumentationScopeInterface $instrumentationScope; - public function __construct( - TracerSharedState $tracerSharedState, - InstrumentationScopeInterface $instrumentationScope + /** @readonly */ + private TracerSharedState $tracerSharedState, + /** @readonly */ + private InstrumentationScopeInterface $instrumentationScope, ) { - $this->tracerSharedState = $tracerSharedState; - $this->instrumentationScope = $instrumentationScope; } /** @inheritDoc */ diff --git a/src/SDK/Trace/TracerProvider.php b/src/SDK/Trace/TracerProvider.php index fdae4aea2..40cf81919 100644 --- a/src/SDK/Trace/TracerProvider.php +++ b/src/SDK/Trace/TracerProvider.php @@ -29,7 +29,7 @@ public function __construct( ResourceInfo $resource = null, SpanLimits $spanLimits = null, IdGeneratorInterface $idGenerator = null, - ?InstrumentationScopeFactoryInterface $instrumentationScopeFactory = null + ?InstrumentationScopeFactoryInterface $instrumentationScopeFactory = null, ) { if (null === $spanProcessors) { $spanProcessors = []; @@ -63,7 +63,7 @@ public function getTracer( string $name, ?string $version = null, ?string $schemaUrl = null, - iterable $attributes = [] + iterable $attributes = [], ): API\TracerInterface { if ($this->tracerSharedState->hasShutdown()) { return NoopTracer::getInstance(); diff --git a/src/SDK/Trace/TracerProviderFactory.php b/src/SDK/Trace/TracerProviderFactory.php index a545319b6..b12136e7e 100644 --- a/src/SDK/Trace/TracerProviderFactory.php +++ b/src/SDK/Trace/TracerProviderFactory.php @@ -18,7 +18,7 @@ final class TracerProviderFactory public function __construct( ?ExporterFactory $exporterFactory = null, ?SamplerFactory $samplerFactory = null, - ?SpanProcessorFactory $spanProcessorFactory = null + ?SpanProcessorFactory $spanProcessorFactory = null, ) { $this->exporterFactory = $exporterFactory ?: new ExporterFactory(); $this->samplerFactory = $samplerFactory ?: new SamplerFactory(); diff --git a/src/SDK/Trace/TracerSharedState.php b/src/SDK/Trace/TracerSharedState.php index d0540cc1f..bcc5aa83e 100644 --- a/src/SDK/Trace/TracerSharedState.php +++ b/src/SDK/Trace/TracerSharedState.php @@ -15,49 +15,27 @@ */ final class TracerSharedState { - /** @readonly */ - private IdGeneratorInterface $idGenerator; - - /** @readonly */ - private ResourceInfo $resource; - - /** @readonly */ - private SpanLimits $spanLimits; - - /** @readonly */ - private SamplerInterface $sampler; - /** @readonly */ private SpanProcessorInterface $spanProcessor; private ?bool $shutdownResult = null; public function __construct( - IdGeneratorInterface $idGenerator, - ResourceInfo $resource, - SpanLimits $spanLimits, - SamplerInterface $sampler, - array $spanProcessors + /** @readonly */ + private IdGeneratorInterface $idGenerator, + /** @readonly */ + private ResourceInfo $resource, + /** @readonly */ + private SpanLimits $spanLimits, + /** @readonly */ + private SamplerInterface $sampler, + array $spanProcessors, ) { - $this->idGenerator = $idGenerator; - $this->resource = $resource; - $this->spanLimits = $spanLimits; - $this->sampler = $sampler; - - switch (count($spanProcessors)) { - case 0: - $this->spanProcessor = NoopSpanProcessor::getInstance(); - - break; - case 1: - $this->spanProcessor = $spanProcessors[0]; - - break; - default: - $this->spanProcessor = new MultiSpanProcessor(...$spanProcessors); - - break; - } + $this->spanProcessor = match (count($spanProcessors)) { + 0 => NoopSpanProcessor::getInstance(), + 1 => $spanProcessors[0], + default => new MultiSpanProcessor(...$spanProcessors), + }; } public function hasShutdown(): bool diff --git a/src/SDK/composer.json b/src/SDK/composer.json index 4497c9400..cfff80c24 100644 --- a/src/SDK/composer.json +++ b/src/SDK/composer.json @@ -17,7 +17,7 @@ } ], "require": { - "php": "^7.4 || ^8.0", + "php": "^8.0", "ext-json": "*", "open-telemetry/api": "^1.0", "open-telemetry/context": "^1.0", @@ -29,7 +29,6 @@ "psr/http-message": "^1.0.1|^2.0", "psr/log": "^1.1|^2.0|^3.0", "symfony/polyfill-mbstring": "^1.23", - "symfony/polyfill-php80": "^1.26", "symfony/polyfill-php81": "^1.26", "symfony/polyfill-php82": "^1.26" }, diff --git a/src/SemConv/composer.json b/src/SemConv/composer.json index a601ca5dc..110b7277a 100644 --- a/src/SemConv/composer.json +++ b/src/SemConv/composer.json @@ -17,7 +17,7 @@ } ], "require": { - "php": "^7.4 || ^8.0" + "php": "^8.0" }, "autoload": { "psr-4": { diff --git a/tests/Integration/SDK/ParentBasedTest.php b/tests/Integration/SDK/ParentBasedTest.php index 42c6df2c6..8f83c9b41 100644 --- a/tests/Integration/SDK/ParentBasedTest.php +++ b/tests/Integration/SDK/ParentBasedTest.php @@ -44,7 +44,7 @@ public function test_parent_based( ?SamplerInterface $remoteParentNotSampled = null, ?SamplerInterface $localParentSampled = null, ?SamplerInterface $localParentNotSampled = null, - ?int $expectedDecision = null + ?int $expectedDecision = null, ): void { $rootSampler = $this->createMockSamplerNeverInvoked(); diff --git a/tests/Integration/SDK/SpanBuilderTest.php b/tests/Integration/SDK/SpanBuilderTest.php index b32fbae0b..abcbb91b8 100644 --- a/tests/Integration/SDK/SpanBuilderTest.php +++ b/tests/Integration/SDK/SpanBuilderTest.php @@ -343,7 +343,7 @@ public function shouldSample( string $spanName, int $spanKind, AttributesInterface $attributes, - array $links + array $links, ): SamplingResult { return new SamplingResult(SamplingResult::RECORD_AND_SAMPLE, ['cat' => 'meow']); } diff --git a/tests/Unit/API/Trace/NoopSpanBuilderTest.php b/tests/Unit/API/Trace/NoopSpanBuilderTest.php index d3a04cfea..f5c15dc66 100644 --- a/tests/Unit/API/Trace/NoopSpanBuilderTest.php +++ b/tests/Unit/API/Trace/NoopSpanBuilderTest.php @@ -26,7 +26,7 @@ public function test_set_parent(): void $this->assertInstanceOf( NoopSpanBuilder::class, (new NoopSpanBuilder($contextStorage))->setParent( - // @todo: Create a interface for Context to allow it to be mocked + // @todo: Create a interface for Context to allow it to be mocked Context::getRoot() ) ); diff --git a/tests/Unit/Extension/Propagator/Jaeger/JaegerPropagatorTest.php b/tests/Unit/Extension/Propagator/Jaeger/JaegerPropagatorTest.php index c7c5238ea..54ff57dce 100644 --- a/tests/Unit/Extension/Propagator/Jaeger/JaegerPropagatorTest.php +++ b/tests/Unit/Extension/Propagator/Jaeger/JaegerPropagatorTest.php @@ -38,7 +38,7 @@ private function withSpanContext(SpanContextInterface $spanContext, ContextInter private function generateTraceIdHeaderValue( string $traceId, string $spanId, - string $flag + string $flag, ): string { return sprintf( '%s:%s:0:%s', diff --git a/tests/Unit/SDK/FactoryRegistryTest.php b/tests/Unit/SDK/FactoryRegistryTest.php index 20bbd284c..c42d9cf45 100644 --- a/tests/Unit/SDK/FactoryRegistryTest.php +++ b/tests/Unit/SDK/FactoryRegistryTest.php @@ -12,6 +12,7 @@ use OpenTelemetry\SDK\Trace\SpanExporter\SpanExporterFactoryInterface; use PHPUnit\Framework\Exception as PHPUnitFrameworkException; use PHPUnit\Framework\TestCase; +use TypeError; /** * @covers \OpenTelemetry\SDK\Registry @@ -121,7 +122,7 @@ public static function textMapPropagator(): array */ public function test_register_invalid_transport_factory($factory): void { - $this->expectException(PHPUnitFrameworkException::class); + $this->expectException(TypeError::class); Registry::registerTransportFactory('http', $factory, true); } @@ -130,7 +131,7 @@ public function test_register_invalid_transport_factory($factory): void */ public function test_register_invalid_span_exporter_factory($factory): void { - $this->expectException(PHPUnitFrameworkException::class); + $this->expectException(TypeError::class); Registry::registerSpanExporterFactory('foo', $factory, true); } @@ -139,7 +140,7 @@ public function test_register_invalid_span_exporter_factory($factory): void */ public function test_register_invalid_metric_exporter_factory($factory): void { - $this->expectException(PHPUnitFrameworkException::class); + $this->expectException(TypeError::class); Registry::registerMetricExporterFactory('foo', $factory, true); } diff --git a/tests/Unit/SDK/Logs/Processor/BatchLogRecordProcessorTest.php b/tests/Unit/SDK/Logs/Processor/BatchLogRecordProcessorTest.php index 2dd6732bd..075847be3 100644 --- a/tests/Unit/SDK/Logs/Processor/BatchLogRecordProcessorTest.php +++ b/tests/Unit/SDK/Logs/Processor/BatchLogRecordProcessorTest.php @@ -400,9 +400,6 @@ public function test_throwing_exporter_flush_rethrows_in_original_caller(): void $processor->forceFlush(); } - /** - * @requires PHP >= 8.0 - */ public function test_self_diagnostics(): void { $clock = new TestClock(); diff --git a/tests/Unit/SDK/Metrics/InstrumentTest.php b/tests/Unit/SDK/Metrics/InstrumentTest.php index f4ce660a5..37ecb3806 100644 --- a/tests/Unit/SDK/Metrics/InstrumentTest.php +++ b/tests/Unit/SDK/Metrics/InstrumentTest.php @@ -6,7 +6,6 @@ use OpenTelemetry\API\Metrics\ObserverInterface; use OpenTelemetry\SDK\Common\Attribute\Attributes; -use OpenTelemetry\SDK\Common\Util\WeakMap; use OpenTelemetry\SDK\Metrics\Aggregation\ExplicitBucketHistogramAggregation; use OpenTelemetry\SDK\Metrics\Aggregation\SumAggregation; use OpenTelemetry\SDK\Metrics\Counter; @@ -29,6 +28,7 @@ use OpenTelemetry\Tests\Unit\SDK\Util\TestClock; use PHPUnit\Framework\TestCase; use stdClass; +use WeakMap; final class InstrumentTest extends TestCase { @@ -77,7 +77,7 @@ public function test_asynchronous_counter(): void $n = $w->registerAsynchronousStream($i, $s, $a); $r = $s->register(Temporality::CUMULATIVE); - $c = new ObservableCounter($w, $i, new NoopStalenessHandler(), WeakMap::create()); + $c = new ObservableCounter($w, $i, new NoopStalenessHandler(), new WeakMap()); $c->observe(static function (ObserverInterface $observer): void { $observer->observe(5); }); @@ -116,7 +116,7 @@ public function __invoke(ObserverInterface $observer) } }; - $c = new ObservableCounter($w, $i, new NoopStalenessHandler(), WeakMap::create()); + $c = new ObservableCounter($w, $i, new NoopStalenessHandler(), new WeakMap()); $c->observe($instance); $instance = null; @@ -222,7 +222,7 @@ public function test_observable_callback_removes_callback_destructor_token_on_de $writer = $this->createMock(MetricWriterInterface::class); $referenceCounter = $this->createMock(ReferenceCounterInterface::class); - $callbackDestructor = new ObservableCallbackDestructor(WeakMap::create(), $writer); + $callbackDestructor = new ObservableCallbackDestructor(new WeakMap(), $writer); $callbackDestructor->callbackIds[1] = $referenceCounter; $callback = new ObservableCallback($writer, $referenceCounter, 1, $callbackDestructor, new stdClass()); @@ -254,7 +254,7 @@ public function test_observable_callback_does_not_acquire_persistent_on_destruct $referenceCounter = $this->createMock(ReferenceCounterInterface::class); $referenceCounter->expects($this->never())->method('acquire')->with(true); - $callbackDestructor = new ObservableCallbackDestructor(WeakMap::create(), $writer); + $callbackDestructor = new ObservableCallbackDestructor(new WeakMap(), $writer); $callbackDestructor->callbackIds[1] = $referenceCounter; /** @noinspection PhpExpressionResultUnusedInspection */ diff --git a/tests/Unit/SDK/Trace/Sampler/ParentBasedTest.php b/tests/Unit/SDK/Trace/Sampler/ParentBasedTest.php index 622b96140..71dee07f9 100644 --- a/tests/Unit/SDK/Trace/Sampler/ParentBasedTest.php +++ b/tests/Unit/SDK/Trace/Sampler/ParentBasedTest.php @@ -70,7 +70,7 @@ public function test_should_sample_parent_based( ?SamplerInterface $remoteParentNotSampled = null, ?SamplerInterface $localParentSampled = null, ?SamplerInterface $localParentNotSampled = null, - ?int $expectedDecision = null + ?int $expectedDecision = null, ): void { $rootSampler = $this->createMockSamplerNeverInvoked(); diff --git a/tests/Unit/SDK/Trace/SpanTest.php b/tests/Unit/SDK/Trace/SpanTest.php index 81f0555be..27cd1ddce 100644 --- a/tests/Unit/SDK/Trace/SpanTest.php +++ b/tests/Unit/SDK/Trace/SpanTest.php @@ -108,7 +108,7 @@ protected function tearDown(): void { ClockFactory::setDefault(null); Logging::reset(); -// LoggerHolder::unset(); + // LoggerHolder::unset(); } // region API @@ -860,7 +860,7 @@ private function createTestSpan( SpanLimits $spanLimits = null, string $parentSpanId = null, iterable $attributes = [], - array $links = [] + array $links = [], ): Span { $parentSpanId = $parentSpanId ?? $this->parentSpanId; $spanLimits = $spanLimits ?? (new SpanLimitsBuilder())->build(); @@ -924,7 +924,7 @@ private function assertEvent( EventInterface $event, string $expectedName, AttributesInterface $expectedAttributes, - int $expectedEpochNanos + int $expectedEpochNanos, ): void { $this->assertSame($expectedName, $event->getName()); $this->assertEquals($expectedAttributes, $event->getAttributes()); @@ -945,7 +945,7 @@ private function assertSpanData( int $startEpochNanos, int $endEpochNanos, string $status, - bool $hasEnded + bool $hasEnded, ): void { $this->assertSame($spanName, $spanData->getName()); $this->assertSame($this->traceId, $spanData->getTraceId());