diff --git a/.circleci/config.yml b/.circleci/config.yml index 93be32844..89e38c3d9 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -60,7 +60,7 @@ unit-config: &unit-config - run: name: PHP Code Style - command: vendor/bin/phpcs --standard=./phpcs-ruleset.xml + command: vendor/bin/phpcs --standard=./phpcs.xml - run: name: PHP unit tests diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 73369e132..232535697 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -63,7 +63,7 @@ You can check your code against these rules by running PHPCS with the proper ruleset, like this: ```sh -$ vendor/bin/phpcs --standard=phpcs-ruleset +$ vendor/bin/phpcs --standard=phpcs.xml ``` -Coding style checks are run along with the other test suites. \ No newline at end of file +Coding style checks are run along with the other test suites. diff --git a/composer.json b/composer.json index 328ce4531..4c9a33001 100644 --- a/composer.json +++ b/composer.json @@ -32,6 +32,7 @@ "ext-opencensus": "< 0.1.0" }, "suggest": { + "ext-json": "For using LoggerExporter", "opencensus/opencensus-exporter-jaeger": "Export data to Jaeger", "opencensus/opencensus-exporter-stackdriver": "Export data to Stackdriver", "opencensus/opencensus-exporter-zipkin": "Export data to Zipkin", diff --git a/phpcs-ruleset.xml b/phpcs.xml similarity index 100% rename from phpcs-ruleset.xml rename to phpcs.xml diff --git a/scripts/run_local_tests.sh b/scripts/run_local_tests.sh index c33539540..deb56a721 100755 --- a/scripts/run_local_tests.sh +++ b/scripts/run_local_tests.sh @@ -23,4 +23,4 @@ DIRNAME=$(dirname $0) $DIRNAME/../vendor/bin/phpunit # Run code style tests -$DIRNAME/../vendor/bin/phpcs --standard=$DIRNAME/../phpcs-ruleset.xml -p \ No newline at end of file +$DIRNAME/../vendor/bin/phpcs --standard=$DIRNAME/../phpcs.xml -p diff --git a/src/Core/Context.php b/src/Core/Context.php index 7661e4e0a..72277b709 100644 --- a/src/Core/Context.php +++ b/src/Core/Context.php @@ -63,7 +63,7 @@ public function __construct($initialValues = []) * @param mixed $value * @return Context */ - public function withValue($key, $value) + public function withValue($key, $value): Context { $copy = $this->values; $copy[$key] = $value; @@ -76,7 +76,7 @@ public function withValue($key, $value) * @param array $data * @return Context */ - public function withValues($data) + public function withValues($data): Context { $copy = $this->values; foreach ($data as $key => $value) { @@ -105,7 +105,7 @@ public function value($key, $default = null) * * @return array */ - public function values() + public function values(): array { return $this->values; } @@ -116,7 +116,7 @@ public function values() * * @return Context */ - public function attach() + public function attach(): Context { $current = self::current(); self::$current = $this; @@ -129,7 +129,7 @@ public function attach() * * @param Context $toAttach */ - public function detach(Context $toAttach) + public function detach(Context $toAttach): void { if (self::current() !== $this) { trigger_error('Unexpected context to detach.', E_USER_WARNING); @@ -144,7 +144,7 @@ public function detach(Context $toAttach) * * @return Context */ - public static function current() + public static function current(): Context { if (!self::$current) { self::$current = self::background(); @@ -158,7 +158,7 @@ public static function current() * * @return Context */ - public static function background() + public static function background(): Context { return new Context(); } @@ -169,7 +169,7 @@ public static function background() * * @internal */ - public static function reset() + public static function reset(): void { self::$current = null; } diff --git a/src/Core/DaemonClient.php b/src/Core/DaemonClient.php index a4f18a50b..e3d64c872 100755 --- a/src/Core/DaemonClient.php +++ b/src/Core/DaemonClient.php @@ -186,7 +186,7 @@ public static function init(array $options = []): DaemonClient return self::$instance = new DaemonClient($sock, $maxSendTime); } - public static function createMeasure(Measure $measure): bool + public function createMeasure(Measure $measure): bool { $msg = ''; switch (true) { @@ -206,7 +206,7 @@ public static function createMeasure(Measure $measure): bool return self::$instance->send(self::MSG_MEASURE_CREATE, $msg); } - public static function setReportingPeriod(float $interval): bool + public function setReportingPeriod(float $interval): bool { if ($interval < 1.0) { return false; @@ -215,7 +215,7 @@ public static function setReportingPeriod(float $interval): bool return self::$instance->send(self::MSG_VIEW_REPORTING_PERIOD, $msg); } - public static function registerView(View ...$views): bool + public function registerView(View ...$views): bool { // bail out if we don't have views if (count($views) === 0) { @@ -247,7 +247,7 @@ public static function registerView(View ...$views): bool return self::$instance->send(self::MSG_VIEW_REGISTER, $msg); } - public static function unregisterView(View ...$views): bool + public function unregisterView(View ...$views): bool { // bail out if we don't have views if (count($views) === 0) { @@ -262,7 +262,7 @@ public static function unregisterView(View ...$views): bool return self::$instance->send(self::MSG_VIEW_UNREGISTER, $msg); } - public static function recordStats(TagContext $tagContext, array $attachments, Measurement ...$ms): bool + public function recordStats(TagContext $tagContext, array $attachments, Measurement ...$ms): bool { // bail out if we don't have measurements if (count($ms) === 0) { @@ -298,7 +298,7 @@ public static function recordStats(TagContext $tagContext, array $attachments, M return self::$instance->send(self::MSG_STATS_RECORD, $msg); } - public function export(array $spans) + public function export(array $spans): bool { $spanData = json_encode(array_map(function (SpanData $span) { return [ diff --git a/src/Stats/Exporter/ExporterInterface.php b/src/Stats/Exporter/ExporterInterface.php index 96884aa20..8a0fa16cc 100644 --- a/src/Stats/Exporter/ExporterInterface.php +++ b/src/Stats/Exporter/ExporterInterface.php @@ -33,7 +33,7 @@ interface ExporterInterface * @param Measure $measure The measure to register. * @return bool Returns true on successful send operation. */ - public static function createMeasure(Measure $measure): bool; + public function createMeasure(Measure $measure): bool; /** * Adjust the stats reporting period of the Daemom. @@ -41,7 +41,7 @@ public static function createMeasure(Measure $measure): bool; * @param float $interval Reporting interval of the daemon in seconds. * @return bool Returns true on successful send operation. */ - public static function setReportingPeriod(float $interval): bool; + public function setReportingPeriod(float $interval): bool; /** * Register views. @@ -49,7 +49,7 @@ public static function setReportingPeriod(float $interval): bool; * @param View ...$views One or more Views to register. * @return bool Returns true on successful send operation. */ - public static function registerView(View ...$views): bool; + public function registerView(View ...$views): bool; /** * Unregister views. @@ -57,7 +57,7 @@ public static function registerView(View ...$views): bool; * @param View ...$views Views to unregister. * @return bool Returns true on successful send operation. */ - public static function unregisterView(View ...$views): bool; + public function unregisterView(View ...$views): bool; /** * Record the provided Measurements, Attachments and Tags. @@ -67,5 +67,5 @@ public static function unregisterView(View ...$views): bool; * @param Measurement ...$ms One or more measurements to record. * @return bool Returns true on successful send operation. */ - public static function recordStats(TagContext $tagContext, array $attachments, Measurement ...$ms): bool; + public function recordStats(TagContext $tagContext, array $attachments, Measurement ...$ms): bool; } diff --git a/src/Stats/Exporter/NoopExporter.php b/src/Stats/Exporter/NoopExporter.php index f28c423d2..953b3a87a 100644 --- a/src/Stats/Exporter/NoopExporter.php +++ b/src/Stats/Exporter/NoopExporter.php @@ -24,27 +24,27 @@ class NoopExporter implements ExporterInterface { - public static function createMeasure(Measure $measure): bool + public function createMeasure(Measure $measure): bool { return true; } - public static function setReportingPeriod(float $interval): bool + public function setReportingPeriod(float $interval): bool { return true; } - public static function registerView(View ...$views): bool + public function registerView(View ...$views): bool { return true; } - public static function unregisterView(View ...$views): bool + public function unregisterView(View ...$views): bool { return true; } - public static function recordStats(TagContext $tags, array $attachments, Measurement ...$ms): bool + public function recordStats(TagContext $tags, array $attachments, Measurement ...$ms): bool { return true; } diff --git a/src/Stats/FloatMeasure.php b/src/Stats/FloatMeasure.php index b66bbc2da..d4472164d 100644 --- a/src/Stats/FloatMeasure.php +++ b/src/Stats/FloatMeasure.php @@ -43,7 +43,7 @@ final protected function __construct(string $name, string $description, string $ * Constructs a new FloatMeasure. * * @param string $name Unique name of the Measure. - * @param string $description Human readable discription of the Measure. + * @param string $description Human readable description of the Measure. * @param string $unit Unit of the Measure. See * Unified Code for Units of Measure * @return FloatMeasure @@ -51,7 +51,7 @@ final protected function __construct(string $name, string $description, string $ */ final public static function create( string $name, - string $description = "", + string $description = '', string $unit = Measure::DIMENSIONLESS ): FloatMeasure { return self::registerMeasureHandle($name, $description, $unit); @@ -74,7 +74,7 @@ final public function m(float $value): Measurement * @param float $value The value of this Measurement. */ - public function __construct(Measure &$measure, float $value) + public function __construct(Measure $measure, float $value) { parent::__construct($measure, $value); } diff --git a/src/Stats/IntMeasure.php b/src/Stats/IntMeasure.php index ef2fddb62..208f36e00 100644 --- a/src/Stats/IntMeasure.php +++ b/src/Stats/IntMeasure.php @@ -42,7 +42,7 @@ final protected function __construct(string $name, string $description, string $ * Constructs a new IntMeasure. * * @param string $name Unique name of the Measure. - * @param string $description Human readable discription of the Measure. + * @param string $description Human readable description of the Measure. * @param string $unit Unit of the Measure. See * Unified Code for Units of Measure * @return IntMeasure @@ -50,7 +50,7 @@ final protected function __construct(string $name, string $description, string $ */ final public static function create( string $name, - string $description = "", + string $description = '', string $unit = Measure::DIMENSIONLESS ): IntMeasure { return self::registerMeasureHandle($name, $description, $unit); @@ -72,7 +72,7 @@ final public function m(int $value): Measurement * @param Measure $measure The Measure. * @param int $value The Measurement value. */ - public function __construct(Measure &$measure, int $value) + public function __construct(Measure $measure, int $value) { parent::__construct($measure, $value); } diff --git a/src/Stats/Measure.php b/src/Stats/Measure.php index d741004e8..66147af90 100644 --- a/src/Stats/Measure.php +++ b/src/Stats/Measure.php @@ -31,22 +31,22 @@ abstract class Measure use \OpenCensus\Utils\PrintableTrait; /** measurement is dimensionless */ - public const DIMENSIONLESS = "1"; + public const DIMENSIONLESS = '1'; /** measurement in bytes */ - public const BYTES = "By"; + public const BYTES = 'By'; /** measurement in milliseconds */ - public const MILLISECONDS = "ms"; + public const MILLISECONDS = 'ms'; protected const NAME_MAX_LENGTH = 255; - protected const EX_NAME_EXISTS = "Different Measure Type with same name already exists."; - protected const EX_INVALID_NAME = "Name should be a ASCII string with a length " . - "no greater than " . self::NAME_MAX_LENGTH . " characters."; + protected const EX_NAME_EXISTS = 'Different Measure Type with same name already exists.'; + protected const EX_INVALID_NAME = 'Name should be an ASCII string with a length no greater than ' . + self::NAME_MAX_LENGTH . ' characters.'; /** - * Contains our initialized Measure's + * Contains our initialized Measures * @var array $map */ - protected static $map = array(); + protected static $map = []; /** * Holds our Measure's name. * @var string $name diff --git a/src/Stats/MeasureHandleTrait.php b/src/Stats/MeasureHandleTrait.php index 404461ab9..db12921b7 100644 --- a/src/Stats/MeasureHandleTrait.php +++ b/src/Stats/MeasureHandleTrait.php @@ -39,8 +39,10 @@ private static function registerMeasureHandle(string $name, string $description, $description = $name; } + /** @var Measure $m */ $m = new self($name, $description, $unit); - Stats::getInstance()->getExporter()->createMeasure($m); + Stats::getExporter()->createMeasure($m); + return parent::$map[$name] = $m; } } diff --git a/src/Stats/Measurement.php b/src/Stats/Measurement.php index 34b4bbd70..929ce0109 100644 --- a/src/Stats/Measurement.php +++ b/src/Stats/Measurement.php @@ -39,7 +39,7 @@ abstract class Measurement * @param Measure $measure The measure this measurement belongs to. * @param mixed $value The value of the measurement. */ - protected function __construct(Measure &$measure, $value) + protected function __construct(Measure $measure, $value) { $this->m = $measure; $this->v = $value; diff --git a/src/Stats/Stats.php b/src/Stats/Stats.php index 0eb679000..b0c6899bd 100644 --- a/src/Stats/Stats.php +++ b/src/Stats/Stats.php @@ -71,42 +71,21 @@ * }); * ``` */ -class Stats +final class Stats { - /** @var Stats $instance */ - private static $instance; - - /** @var ExporterInterface $exporter */ - private $exporter; - - private function __construct() - { - } - /** - * Retrieve Stats instance. - * - * @return Stats - */ - public static function getInstance(): Stats - { - if (self::$instance instanceof Stats) { - return self::$instance; - } - self::$instance = new Stats(); - self::$instance->exporter = new NoopExporter(); - - return self::$instance; - } + * @var ExporterInterface + */ + private static $exporter; /** * Set the ExporterInterface to use by the Stats components. * * @param ExporterInterface $exporter */ - public static function setExporter(ExporterInterface $exporter) + public static function setExporter(ExporterInterface $exporter): void { - self::getInstance()->exporter = $exporter; + self::$exporter = $exporter; } /** @@ -116,7 +95,7 @@ public static function setExporter(ExporterInterface $exporter) */ public static function getExporter(): ExporterInterface { - return self::getInstance()->exporter; + return self::$exporter ?? new NoopExporter(); } /** @@ -136,9 +115,10 @@ public static function newTagContext(): TagContext */ public static function newMeasurementMap(): MeasurementInterface { - if (self::getInstance()->exporter instanceof NoopExporter) { + if (self::getExporter() instanceof NoopExporter) { return new NoopMeasurementMap(); } + return new MeasurementMap(); } @@ -150,7 +130,7 @@ public static function newMeasurementMap(): MeasurementInterface */ public static function registerView(View ...$views): bool { - return self::getInstance()->exporter->registerView(...$views); + return self::getExporter()->registerView(...$views); } /** @@ -161,6 +141,6 @@ public static function registerView(View ...$views): bool */ public static function unregisterView(View ...$views): bool { - return self::getInstance()->exporter->unregisterView(...$views); + return self::getExporter()->unregisterView(...$views); } } diff --git a/src/Stats/View/Aggregation.php b/src/Stats/View/Aggregation.php index 9fa2fd826..b641256da 100644 --- a/src/Stats/View/Aggregation.php +++ b/src/Stats/View/Aggregation.php @@ -25,18 +25,18 @@ class Aggregation { /** No or unknown Aggregation type. */ - const NONE = 0; + public const NONE = 0; /** Count Aggregation type. */ - const COUNT = 1; + public const COUNT = 1; /** Sum Aggregation type. */ - const SUM = 2; + public const SUM = 2; /** Distribution Aggregation type. */ - const DISTRIBUTION = 3; + public const DISTRIBUTION = 3; /** LastValue Aggregation type. */ - const LAST_VALUE = 4; + public const LAST_VALUE = 4; - /** @var int $type Aggragation type */ - private $type = 0; + /** @var int $type Aggregation type */ + private $type; /** * @var float[] $bounds Bucket boundaries if this Aggregation represents a @@ -93,11 +93,11 @@ final public static function count(): Aggregation */ final public static function distribution(array $bounds): Aggregation { - foreach ($bounds as &$value) { - if (!is_float($value) && !is_integer($value)) { - throw new \Exception("provided bucket boundaries need to be of type float"); + foreach ($bounds as $index => $value) { + if (!is_float($value) && !is_int($value)) { + throw new \RuntimeException('Provided bucket boundaries need to be of type float.'); } - $value = (float) $value; + $bounds[$index] = (float) $value; } sort($bounds); diff --git a/src/Stats/View/View.php b/src/Stats/View/View.php index 82ebfd771..345a5c65a 100644 --- a/src/Stats/View/View.php +++ b/src/Stats/View/View.php @@ -30,14 +30,14 @@ class View use \OpenCensus\Utils\PrintableTrait; /** @var array $views map of views to make sure view names are unique. */ - private static $views = array(); + private static $views = []; /** @var string $name */ private $name; /** @var string $description */ private $description; /** @var TagKey[] $tagKeys */ - private $tagKeys = array(); + private $tagKeys; /** @var Measure $measure */ private $measure; /** @var Aggregation $aggregation */ @@ -59,7 +59,6 @@ final public function __construct( Aggregation $aggregation, TagKey ...$tagKeys ) { - if ($name === '') { $name = $measure->getName(); } diff --git a/src/Tags/TagValue.php b/src/Tags/TagValue.php index b1a44a63f..5df003811 100644 --- a/src/Tags/TagValue.php +++ b/src/Tags/TagValue.php @@ -28,7 +28,7 @@ class TagValue use \OpenCensus\Utils\PrintableTrait; /** The maximum length for a tag value. */ - const MAX_LENGTH = 255; + private const MAX_LENGTH = 255; /** @var string TagValue payload */ private $value; @@ -54,7 +54,7 @@ final private function __construct(string $value) public static function create(string $value): TagValue { if (strlen($value) > self::MAX_LENGTH || !self::isPrintable($value)) { - throw new \Exception("Invalid TagValue: $value"); + throw new \RuntimeException("Invalid TagValue: $value"); } return new self($value); } diff --git a/src/Trace/Annotation.php b/src/Trace/Annotation.php index 606c498d5..1fe8746be 100644 --- a/src/Trace/Annotation.php +++ b/src/Trace/Annotation.php @@ -52,7 +52,7 @@ public function __construct($description, $options = []) * * @return string */ - public function description() + public function description(): string { return $this->description; } diff --git a/src/Trace/AttributeTrait.php b/src/Trace/AttributeTrait.php index 57315088d..c5809ce48 100644 --- a/src/Trace/AttributeTrait.php +++ b/src/Trace/AttributeTrait.php @@ -20,7 +20,7 @@ trait AttributeTrait { /** - * @var array A set of attributes, each in the format `[KEY]:[VALUE]`. + * @var string[] A set of attributes. */ private $attributes = []; @@ -29,7 +29,7 @@ trait AttributeTrait * * @param array $attributes Attributes in the form of $attribute => $value */ - public function addAttributes(array $attributes) + public function addAttributes(array $attributes): void { foreach ($attributes as $attribute => $value) { $this->addAttribute($attribute, $value); @@ -39,20 +39,20 @@ public function addAttributes(array $attributes) /** * Attach a single attribute to this object. * - * @param string $attribute The name of the attribute. - * @param mixed $value The value of the attribute. Will be cast to a string + * @param string $name The name of the attribute. + * @param string $value The value of the attribute. Will be cast to a string */ - public function addAttribute($attribute, $value) + public function addAttribute(string $name, string $value): void { - $this->attributes[$attribute] = (string) $value; + $this->attributes[$name] = $value; } /** * Return the list of attributes for this object. * - * @return array + * @return string[] */ - public function attributes() + public function attributes(): array { return $this->attributes; } diff --git a/src/Trace/DateFormatTrait.php b/src/Trace/DateFormatTrait.php index 32524554e..11e1c9294 100644 --- a/src/Trace/DateFormatTrait.php +++ b/src/Trace/DateFormatTrait.php @@ -27,10 +27,10 @@ trait DateFormatTrait * * @param \DateTimeInterface|int|float $when [optional] The end time of this span. * **Defaults to** now. If provided as an int or float, it is expected to be a Unix timestamp. - * @return \DateTimeInterface + * @return \DateTime * @throws \InvalidArgumentException */ - private function formatDate($when = null) + private function formatDate($when = null): \DateTime { if (!$when) { // now @@ -41,6 +41,7 @@ private function formatDate($when = null) throw new \InvalidArgumentException('Invalid date format. Must be a \DateTimeInterface or numeric.'); } $when->setTimezone(new \DateTimeZone('UTC')); + return $when; } @@ -48,9 +49,9 @@ private function formatDate($when = null) * Converts a float timestamp into a \DateTimeInterface object. * * @param float $when The Unix timestamp to be converted. - * @return \DateTimeInterface + * @return \DateTime */ - private function formatFloatTimeToDate($when) + private function formatFloatTimeToDate($when): \DateTime { return \DateTime::createFromFormat('U.u', number_format($when, 6, '.', '')); } diff --git a/src/Trace/EventHandler/NullEventHandler.php b/src/Trace/EventHandler/NullEventHandler.php index 21884130c..de3c3c460 100644 --- a/src/Trace/EventHandler/NullEventHandler.php +++ b/src/Trace/EventHandler/NullEventHandler.php @@ -20,7 +20,7 @@ class NullEventHandler implements SpanEventHandlerInterface * @param string $attribute The name of the attribute added * @param string $value The attribute value */ - public function attributeAdded(Span $span, $attribute, $value) + public function attributeAdded(Span $span, string $attribute, string $value): void { } @@ -30,7 +30,7 @@ public function attributeAdded(Span $span, $attribute, $value) * @param Span $span The span the link was added to * @param Link $link The link added to the span */ - public function linkAdded(Span $span, Link $link) + public function linkAdded(Span $span, Link $link): void { } @@ -40,7 +40,7 @@ public function linkAdded(Span $span, Link $link) * @param Span $span The span the time event was added to * @param TimeEvent $timeEvent The time event added to the span */ - public function timeEventAdded(Span $span, TimeEvent $timeEvent) + public function timeEventAdded(Span $span, TimeEvent $timeEvent): void { } } diff --git a/src/Trace/EventHandler/SpanEventHandlerInterface.php b/src/Trace/EventHandler/SpanEventHandlerInterface.php index 5a32ecf52..084e74994 100644 --- a/src/Trace/EventHandler/SpanEventHandlerInterface.php +++ b/src/Trace/EventHandler/SpanEventHandlerInterface.php @@ -18,7 +18,7 @@ interface SpanEventHandlerInterface * @param string $attribute The name of the attribute added * @param string $value The attribute value */ - public function attributeAdded(Span $span, $attribute, $value); + public function attributeAdded(Span $span, string $attribute, string $value): void; /** * Triggers when a link is added to a span. @@ -26,7 +26,7 @@ public function attributeAdded(Span $span, $attribute, $value); * @param Span $span The span the link was added to * @param Link $link The link added to the span */ - public function linkAdded(Span $span, Link $link); + public function linkAdded(Span $span, Link $link): void; /** * Triggers when a time event is added to a span. @@ -34,5 +34,5 @@ public function linkAdded(Span $span, Link $link); * @param Span $span The span the time event was added to * @param TimeEvent $timeEvent The time event added to the span */ - public function timeEventAdded(Span $span, TimeEvent $timeEvent); + public function timeEventAdded(Span $span, TimeEvent $timeEvent): void; } diff --git a/src/Trace/Exporter/EchoExporter.php b/src/Trace/Exporter/EchoExporter.php index 47e6db01d..2654f03c7 100644 --- a/src/Trace/Exporter/EchoExporter.php +++ b/src/Trace/Exporter/EchoExporter.php @@ -17,8 +17,6 @@ namespace OpenCensus\Trace\Exporter; -use OpenCensus\Trace\SpanData; - /** * This implementation of the ExporterInterface uses `print_r` to output * the trace's representation to stdout. @@ -34,13 +32,7 @@ */ class EchoExporter implements ExporterInterface { - /** - * Report the provided Trace to a backend. - * - * @param SpanData[] $spans - * @return bool - */ - public function export(array $spans) + public function export(array $spans): bool { print_r($spans); return true; diff --git a/src/Trace/Exporter/ExporterInterface.php b/src/Trace/Exporter/ExporterInterface.php index f80264391..73015233c 100644 --- a/src/Trace/Exporter/ExporterInterface.php +++ b/src/Trace/Exporter/ExporterInterface.php @@ -28,7 +28,7 @@ interface ExporterInterface * Export the provided SpanData to a backend. * * @param SpanData[] $spans - * @return bool + * @return bool Success of export */ - public function export(array $spans); + public function export(array $spans): bool; } diff --git a/src/Trace/Exporter/FileExporter.php b/src/Trace/Exporter/FileExporter.php index 71ba2bdc8..b4bc727af 100644 --- a/src/Trace/Exporter/FileExporter.php +++ b/src/Trace/Exporter/FileExporter.php @@ -50,13 +50,7 @@ public function __construct($filename) $this->filename = $filename; } - /** - * Report the provided SpanData to a file in json format. - * - * @param SpanData[] $spans - * @return bool - */ - public function export(array $spans) + public function export(array $spans): bool { $spans = $this->convertSpans($spans); return file_put_contents($this->filename, json_encode($spans) . PHP_EOL, FILE_APPEND) !== false; diff --git a/src/Trace/Exporter/LoggerExporter.php b/src/Trace/Exporter/LoggerExporter.php index 8d9113a5f..1cb6516dc 100644 --- a/src/Trace/Exporter/LoggerExporter.php +++ b/src/Trace/Exporter/LoggerExporter.php @@ -62,13 +62,7 @@ public function __construct(LoggerInterface $logger, $level = self::DEFAULT_LOG_ $this->level = $level; } - /** - * Report the provided Trace to a backend. - * - * @param SpanData[] $spans - * @return bool - */ - public function export(array $spans) + public function export(array $spans): bool { try { $this->logger->log($this->level, json_encode($spans)); diff --git a/src/Trace/Exporter/NullExporter.php b/src/Trace/Exporter/NullExporter.php index 58d9b065b..8ffaecb59 100644 --- a/src/Trace/Exporter/NullExporter.php +++ b/src/Trace/Exporter/NullExporter.php @@ -17,8 +17,6 @@ namespace OpenCensus\Trace\Exporter; -use OpenCensus\Trace\Tracer\TracerInterface; - /** * This implementation of the ExporterInterface does nothing. * @@ -33,13 +31,7 @@ */ class NullExporter implements ExporterInterface { - /** - * Does nothing. - * - * @param SpanData[] $spans - * @return bool - */ - public function export(array $spans) + public function export(array $spans): bool { return true; } diff --git a/src/Trace/Exporter/OneLineEchoExporter.php b/src/Trace/Exporter/OneLineEchoExporter.php index 40be0bf23..02384e9b2 100644 --- a/src/Trace/Exporter/OneLineEchoExporter.php +++ b/src/Trace/Exporter/OneLineEchoExporter.php @@ -17,18 +17,9 @@ namespace OpenCensus\Trace\Exporter; -use OpenCensus\Trace\SpanData; - class OneLineEchoExporter implements ExporterInterface { - - /** - * Report the provided Trace to a backend. - * - * @param SpanData[] $spans - * @return bool - */ - public function export(array $spans) + public function export(array $spans): bool { foreach ($spans as $span) { $time = (float) ($span->endTime()->format('U.u')) - (float) ($span->startTime()->format('U.u')); diff --git a/src/Trace/Link.php b/src/Trace/Link.php index e37dc8100..48c8d1835 100644 --- a/src/Trace/Link.php +++ b/src/Trace/Link.php @@ -24,9 +24,9 @@ class Link { use AttributeTrait; - const TYPE_UNSPECIFIED = 'TYPE_UNSPECIFIED'; - const TYPE_CHILD_LINKED_SPAN = 'CHILD_LINKED_SPAN'; - const TYPE_PARENT_LINKED_SPAN = 'PARENT_LINKED_SPAN'; + public const TYPE_UNSPECIFIED = 'TYPE_UNSPECIFIED'; + public const TYPE_CHILD_LINKED_SPAN = 'CHILD_LINKED_SPAN'; + public const TYPE_PARENT_LINKED_SPAN = 'PARENT_LINKED_SPAN'; /** * @var string `TRACE_ID` a unique identifier for a trace. @@ -74,7 +74,7 @@ public function __construct($traceId, $spanId, $options = []) * * @return string */ - public function traceId() + public function traceId(): string { return $this->traceId; } @@ -84,7 +84,7 @@ public function traceId() * * @return string */ - public function spanId() + public function spanId(): string { return $this->spanId; } @@ -94,7 +94,7 @@ public function spanId() * * @return string */ - public function type() + public function type(): string { return $this->type; } diff --git a/src/Trace/MessageEvent.php b/src/Trace/MessageEvent.php index 6604cc225..fbed39b1c 100644 --- a/src/Trace/MessageEvent.php +++ b/src/Trace/MessageEvent.php @@ -22,9 +22,9 @@ */ class MessageEvent extends TimeEvent { - const TYPE_UNSPECIFIED = 'TYPE_UNSPECIFIED'; - const TYPE_SENT = 'SENT'; - const TYPE_RECEIVED = 'RECEIVED'; + public const TYPE_UNSPECIFIED = 'TYPE_UNSPECIFIED'; + public const TYPE_SENT = 'SENT'; + public const TYPE_RECEIVED = 'RECEIVED'; /** * @var string Type of MessageEvent. Indicates whether the message was sent @@ -87,7 +87,7 @@ public function __construct($type, $id, $options = []) * * @return string */ - public function type() + public function type(): string { return $this->type; } @@ -97,7 +97,7 @@ public function type() * * @return string */ - public function id() + public function id(): string { return $this->id; } @@ -107,7 +107,7 @@ public function id() * * @return int */ - public function uncompressedSize() + public function uncompressedSize(): int { return $this->uncompressedSize; } @@ -117,7 +117,7 @@ public function uncompressedSize() * * @return int */ - public function compressedSize() + public function compressedSize(): int { return $this->compressedSize; } diff --git a/src/Trace/RequestHandler.php b/src/Trace/RequestHandler.php index 19ff3dd77..36e9b53ce 100644 --- a/src/Trace/RequestHandler.php +++ b/src/Trace/RequestHandler.php @@ -105,9 +105,13 @@ public function __construct( $propagator->inject($spanContext, $this->headers); } - $this->tracer = $spanContext->enabled() - ? extension_loaded('opencensus') ? new ExtensionTracer($spanContext) : new ContextTracer($spanContext) - : new NullTracer(); + if ($spanContext->enabled()) { + $this->tracer = extension_loaded('opencensus') ? + new ExtensionTracer($spanContext) : + new ContextTracer($spanContext); + } else { + $this->tracer = new NullTracer(); + } $spanOptions = $options + [ 'startTime' => $this->startTimeFromHeaders($this->headers->toArray()), diff --git a/src/Trace/Sampler/AlwaysSampleSampler.php b/src/Trace/Sampler/AlwaysSampleSampler.php index aaee45426..63ce6cc66 100644 --- a/src/Trace/Sampler/AlwaysSampleSampler.php +++ b/src/Trace/Sampler/AlwaysSampleSampler.php @@ -30,12 +30,7 @@ */ class AlwaysSampleSampler implements SamplerInterface { - /** - * Returns true because we always want to sample. - * - * @return bool - */ - public function shouldSample() + public function shouldSample(): bool { return true; } diff --git a/src/Trace/Sampler/MultiSampler.php b/src/Trace/Sampler/MultiSampler.php index ace28c3a0..831784a19 100644 --- a/src/Trace/Sampler/MultiSampler.php +++ b/src/Trace/Sampler/MultiSampler.php @@ -50,19 +50,14 @@ public function __construct(array $samplers = []) $this->samplers = $samplers; } - /** - * Returns false if any provided sampler chooses not to sample this - * request. - * - * @return bool - */ - public function shouldSample() + public function shouldSample(): bool { foreach ($this->samplers as $sampler) { if ($sampler->shouldSample() === false) { return false; } } + return true; } } diff --git a/src/Trace/Sampler/NeverSampleSampler.php b/src/Trace/Sampler/NeverSampleSampler.php index 4d62e7e93..8f9330a7e 100644 --- a/src/Trace/Sampler/NeverSampleSampler.php +++ b/src/Trace/Sampler/NeverSampleSampler.php @@ -30,12 +30,7 @@ */ class NeverSampleSampler implements SamplerInterface { - /** - * Returns false because we never want to sample. - * - * @return bool - */ - public function shouldSample() + public function shouldSample(): bool { return false; } diff --git a/src/Trace/Sampler/ProbabilitySampler.php b/src/Trace/Sampler/ProbabilitySampler.php index ca8d4f1d9..3db3c7fe4 100644 --- a/src/Trace/Sampler/ProbabilitySampler.php +++ b/src/Trace/Sampler/ProbabilitySampler.php @@ -17,6 +17,8 @@ namespace OpenCensus\Trace\Sampler; +use InvalidArgumentException; + /** * This implementation of the SamplerInterface uses a pseudo-random number generator * to sample a percentage of requests. @@ -39,23 +41,18 @@ class ProbabilitySampler implements SamplerInterface /** * Creates the ProbabilitySampler * - * @param float $percentage The percentage of requests to sample. Must be between 0 and 1. + * @param float $rate The percentage of requests to sample. Must be between 0 and 1. */ - public function __construct($rate) + public function __construct(float $rate) { if ($rate > 1 || $rate < 0) { - throw new \InvalidArgumentException('Percentage must be between 0 and 1'); + throw new InvalidArgumentException('Percentage must be between 0 and 1'); } $this->rate = $rate; } - /** - * Uses a pseudo-random number generator to decide if we should sample the request. - * - * @return bool - */ - public function shouldSample() + public function shouldSample(): bool { return lcg_value() <= $this->rate; } diff --git a/src/Trace/Sampler/QpsSampler.php b/src/Trace/Sampler/QpsSampler.php index 5771cc7fd..c5ef6a071 100644 --- a/src/Trace/Sampler/QpsSampler.php +++ b/src/Trace/Sampler/QpsSampler.php @@ -113,12 +113,7 @@ public function __construct(CacheItemPoolInterface $cache = null, $options = []) } } - /** - * Returns whether or not the request should be sampled. - * - * @return bool - */ - public function shouldSample() + public function shouldSample(): bool { // We will store the microtime timestamp in the cache because some // cache implementations will not let you use expiry for anything less diff --git a/src/Trace/Sampler/SamplerInterface.php b/src/Trace/Sampler/SamplerInterface.php index 600d6b7f8..ed9e0cb5a 100644 --- a/src/Trace/Sampler/SamplerInterface.php +++ b/src/Trace/Sampler/SamplerInterface.php @@ -23,9 +23,9 @@ interface SamplerInterface { /** - * Returns true if we whould sample the request + * Returns true if we should sample the request * * @return bool */ - public function shouldSample(); + public function shouldSample(): bool; } diff --git a/src/Trace/Span.php b/src/Trace/Span.php index beb7abb41..ed83ae266 100644 --- a/src/Trace/Span.php +++ b/src/Trace/Span.php @@ -34,17 +34,17 @@ class Span use DateFormatTrait; // See https://github.com/census-instrumentation/opencensus-specs/blob/master/trace/HTTP.md#attributes - const ATTRIBUTE_HOST = 'http.host'; - const ATTRIBUTE_PORT = 'http.port'; - const ATTRIBUTE_METHOD = 'http.method'; - const ATTRIBUTE_PATH = 'http.path'; - const ATTRIBUTE_ROUTE = 'http.route'; - const ATTRIBUTE_USER_AGENT = 'http.user_agent'; - const ATTRIBUTE_STATUS_CODE = 'http.status_code'; - - const KIND_UNSPECIFIED = 'SPAN_KIND_UNSPECIFIED'; - const KIND_SERVER = 'SERVER'; - const KIND_CLIENT = 'CLIENT'; + public const ATTRIBUTE_HOST = 'http.host'; + public const ATTRIBUTE_PORT = 'http.port'; + public const ATTRIBUTE_METHOD = 'http.method'; + public const ATTRIBUTE_PATH = 'http.path'; + public const ATTRIBUTE_ROUTE = 'http.route'; + public const ATTRIBUTE_USER_AGENT = 'http.user_agent'; + public const ATTRIBUTE_STATUS_CODE = 'http.status_code'; + + public const KIND_UNSPECIFIED = 'SPAN_KIND_UNSPECIFIED'; + public const KIND_SERVER = 'SERVER'; + public const KIND_CLIENT = 'CLIENT'; /** * Unique identifier for a trace. All spans from the same Trace share the @@ -198,10 +198,8 @@ public function __construct($options = []) 'eventHandler' => null ]; - $this->traceId = $options['traceId']; - $this->eventHandler = $options['eventHandler'] - ? $options['eventHandler'] - : new NullEventHandler(); + $this->traceId = $options['traceId'] ?? IdGenerator::hex(8); + $this->eventHandler = $options['eventHandler'] ?: new NullEventHandler(); if (array_key_exists('startTime', $options)) { $this->setStartTime($options['startTime']); @@ -246,7 +244,7 @@ public function __construct($options = []) * this span. **Defaults to** now. If provided as an int or float, * it is expected to be a Unix timestamp. */ - public function setStartTime($when = null) + public function setStartTime($when = null): void { $this->startTime = $this->formatDate($when); } @@ -258,7 +256,7 @@ public function setStartTime($when = null) * this span. **Defaults to** now. If provided as an int or float, * it is expected to be a Unix timestamp. */ - public function setEndTime($when = null) + public function setEndTime($when = null): void { $this->endTime = $this->formatDate($when); } @@ -268,7 +266,7 @@ public function setEndTime($when = null) * * @return string */ - public function spanId() + public function spanId(): string { return $this->spanId; } @@ -278,7 +276,7 @@ public function spanId() * * @return SpanData */ - public function spanData() + public function spanData(): SpanData { return new SpanData( $this->name, @@ -302,7 +300,7 @@ public function spanData() /** * Mark this span as attached. */ - public function attach() + public function attach(): void { $this->attached = true; } @@ -312,7 +310,7 @@ public function attach() * * @return bool */ - public function attached() + public function attached(): bool { return $this->attached; } @@ -320,13 +318,13 @@ public function attached() /** * Add an attribute to this span. * - * @param string $attribute The name of the attribute to add + * @param string $name The name of the attribute to add * @param string $value The attribute value */ - public function addAttribute($attribute, $value) + public function addAttribute(string $name, string $value): void { - $this->attributes[$attribute] = (string) $value; - $this->eventHandler->attributeAdded($this, $attribute, $value); + $this->attributes[$name] = $value; + $this->eventHandler->attributeAdded($this, $name, $value); } /** @@ -334,7 +332,7 @@ public function addAttribute($attribute, $value) * * @param TimeEvent[] $timeEvents */ - public function addTimeEvents(array $timeEvents) + public function addTimeEvents(array $timeEvents): void { foreach ($timeEvents as $timeEvent) { $this->addTimeEvent($timeEvent); @@ -346,7 +344,7 @@ public function addTimeEvents(array $timeEvents) * * @param TimeEvent $timeEvent */ - public function addTimeEvent(TimeEvent $timeEvent) + public function addTimeEvent(TimeEvent $timeEvent): void { $this->timeEvents[] = $timeEvent; $this->eventHandler->timeEventAdded($this, $timeEvent); @@ -357,7 +355,7 @@ public function addTimeEvent(TimeEvent $timeEvent) * * @param Link[] $links */ - public function addLinks(array $links) + public function addLinks(array $links): void { foreach ($links as $link) { $this->addLink($link); @@ -369,7 +367,7 @@ public function addLinks(array $links) * * @param Link $link */ - public function addLink(Link $link) + public function addLink(Link $link): void { $this->links[] = $link; $this->eventHandler->linkAdded($this, $link); @@ -381,7 +379,7 @@ public function addLink(Link $link) * @param int $code The status code * @param string $message A developer-facing error message */ - public function setStatus($code, $message) + public function setStatus($code, $message): void { $this->status = new Status($code, $message); } @@ -395,8 +393,8 @@ public function setStatus($code, $message) private function filterStackTrace(array $stackTrace): array { return array_values( - array_filter($stackTrace, function ($st) { - return !array_key_exists('class', $st) || substr($st['class'], 0, 16) != 'OpenCensus\Trace'; + array_filter($stackTrace, static function ($st) { + return !array_key_exists('class', $st) || strpos($st['class'], 'OpenCensus\Trace') !== 0; }) ); } @@ -414,12 +412,14 @@ private function generateSpanName(): string $st += ['line' => null]; if (!array_key_exists('class', $st)) { return implode('/', array_filter(['app', basename($st['file']), $st['function'], $st['line']])); - } elseif (substr($st['class'], 0, 18) != 'OpenCensus\Trace') { + } + + if (strpos($st['class'], 'OpenCensus\Trace') !== 0) { return implode('/', array_filter(['app', $st['class'], $st['function'], $st['line']])); } } // We couldn't find a suitable stackTrace entry - generate a random one - return uniqid('span'); + return uniqid('span', true); } } diff --git a/src/Trace/SpanContext.php b/src/Trace/SpanContext.php index c3569e929..e287ce873 100644 --- a/src/Trace/SpanContext.php +++ b/src/Trace/SpanContext.php @@ -82,7 +82,7 @@ public function __construct( * * @return string */ - public function traceId() + public function traceId(): string { return $this->traceId; } @@ -90,9 +90,9 @@ public function traceId() /** * Fetch the current spanId. * - * @return string + * @return string|null */ - public function spanId() + public function spanId(): ?string { return $this->spanId; } @@ -100,9 +100,9 @@ public function spanId() /** * Set the current spanId. * - * @param string|null $spanId The spanId to set. + * @param string $spanId The spanId to set. */ - public function setSpanId($spanId) + public function setSpanId(string $spanId): void { $this->spanId = $spanId; } @@ -112,7 +112,7 @@ public function setSpanId($spanId) * * @return bool|null */ - public function enabled() + public function enabled(): ?bool { return $this->enabled; } @@ -122,7 +122,7 @@ public function enabled() * * @param bool|null $enabled */ - public function setEnabled($enabled) + public function setEnabled($enabled): void { $this->enabled = $enabled; } @@ -132,7 +132,7 @@ public function setEnabled($enabled) * * @return bool */ - public function fromHeader() + public function fromHeader(): bool { return $this->fromHeader; } diff --git a/src/Trace/SpanData.php b/src/Trace/SpanData.php index 2f9e9f6d9..964ead961 100644 --- a/src/Trace/SpanData.php +++ b/src/Trace/SpanData.php @@ -17,6 +17,8 @@ namespace OpenCensus\Trace; +use DateTimeInterface; + /** * This plain PHP class represents a read-only version of a single timed event * within a Trace. Spans can be nested and form a trace tree. Often, a trace @@ -46,7 +48,7 @@ class SpanData * The `spanId` of this span's parent span. If this is a root span, then * this field must be empty. 8-byte value encoded as a hex string. * - * @var string + * @var string|null */ private $parentSpanId; @@ -65,7 +67,7 @@ class SpanData /** * @var array A set of attributes, each in the format `[KEY]:[VALUE]`. */ - private $attributes = []; + private $attributes; /** * The start time of the span. On the client side, this is the time kept by @@ -92,7 +94,7 @@ class SpanData * * @var array */ - private $stackTrace = []; + private $stackTrace; /** * A collection of `TimeEvent`s. A `TimeEvent` is a time-stamped annotation @@ -101,7 +103,7 @@ class SpanData * * @var TimeEvent[] */ - private $timeEvents = []; + private $timeEvents; /** * A collection of links, which are references from this span to a span @@ -109,12 +111,12 @@ class SpanData * * @var Link[] */ - private $links = []; + private $links; /** * An optional final status for this span. * - * @var Status + * @var Status|null */ private $status; @@ -204,9 +206,9 @@ public function __construct( /** * Retrieve the start time for this span. * - * @return \DateTimeInterface + * @return DateTimeInterface */ - public function startTime() + public function startTime(): ?DateTimeInterface { return $this->startTime; } @@ -214,9 +216,9 @@ public function startTime() /** * Retrieve the end time for this span. * - * @return \DateTimeInterface + * @return DateTimeInterface */ - public function endTime() + public function endTime(): ?DateTimeInterface { return $this->endTime; } @@ -226,7 +228,7 @@ public function endTime() * * @return string */ - public function traceId() + public function traceId(): string { return $this->traceId; } @@ -236,7 +238,7 @@ public function traceId() * * @return string */ - public function spanId() + public function spanId(): string { return $this->spanId; } @@ -244,9 +246,9 @@ public function spanId() /** * Retrieve the ID of this span's parent if it exists. * - * @return string + * @return string|null */ - public function parentSpanId() + public function parentSpanId(): ?string { return $this->parentSpanId; } @@ -256,7 +258,7 @@ public function parentSpanId() * * @return string */ - public function name() + public function name(): string { return $this->name; } @@ -266,7 +268,7 @@ public function name() * * @return array */ - public function attributes() + public function attributes(): array { return $this->attributes; } @@ -276,7 +278,7 @@ public function attributes() * * @return TimeEvent[] */ - public function timeEvents() + public function timeEvents(): array { return $this->timeEvents; } @@ -286,7 +288,7 @@ public function timeEvents() * * @return Link[] */ - public function links() + public function links(): array { return $this->links; } @@ -296,7 +298,7 @@ public function links() * * @return Status */ - public function status() + public function status(): ?Status { return $this->status; } @@ -306,7 +308,7 @@ public function status() * * @return array */ - public function stackTrace() + public function stackTrace(): array { return $this->stackTrace; } @@ -316,7 +318,7 @@ public function stackTrace() * * @return string */ - public function stackTraceHashId() + public function stackTraceHashId(): string { if (!isset($this->stackTraceHashId)) { // take the lower 16 digits of the md5 @@ -331,7 +333,7 @@ public function stackTraceHashId() * * @return bool */ - public function sameProcessAsParentSpan() + public function sameProcessAsParentSpan(): bool { return $this->sameProcessAsParentSpan; } @@ -341,7 +343,7 @@ public function sameProcessAsParentSpan() * * @return string */ - public function kind() + public function kind(): string { return $this->kind; } diff --git a/src/Trace/Status.php b/src/Trace/Status.php index d3bf47c47..0648845ca 100644 --- a/src/Trace/Status.php +++ b/src/Trace/Status.php @@ -73,7 +73,7 @@ public function __construct($code, $message) * * @return int */ - public function code() + public function code(): int { return $this->code; } @@ -83,7 +83,7 @@ public function code() * * @return string */ - public function message() + public function message(): string { return $this->message; } @@ -105,10 +105,10 @@ public static function fromHTTPStatus(int $httpStatus) : self return new self(self::INVALID_ARGUMENT, 'The client specified an invalid argument'); case 401: return new self(self::UNAUTHENTICATED, - "The requester doesn’t have valid authentication credentials for the operation"); + 'The requester does not have valid authentication credentials for the operation'); case 403: return new self(self::PERMISSION_DENIED, - "The caller doesn’t have permission to execute the specified operation"); + 'The caller does not have permission to execute the specified operation'); case 404: return new self(self::NOT_FOUND, 'Content was not found or request was denied for an entire class of users'); @@ -121,7 +121,7 @@ public static function fromHTTPStatus(int $httpStatus) : self return new self(self::CANCELLED, 'The operation was cancelled, typically by the caller'); case 500: return new self(self::UNKNOWN, - "An unknown error raised by APIs that don’t return enough error information"); + 'An unknown error raised by APIs that do not return enough error information'); case 501: return new self(self::UNIMPLEMENTED, 'The operation is not implemented or is not supported/enabled for this operation'); diff --git a/src/Trace/TimeEvent.php b/src/Trace/TimeEvent.php index 3c38ca69f..05bc3bd95 100644 --- a/src/Trace/TimeEvent.php +++ b/src/Trace/TimeEvent.php @@ -49,7 +49,7 @@ public function __construct($options = []) * * @return \DateTimeInterface */ - public function time() + public function time(): \DateTimeInterface { return $this->time; } @@ -59,7 +59,7 @@ public function time() * * @param \DateTimeInterface|int|float $time The time of this event. */ - public function setTime($time = null) + public function setTime($time = null): void { $this->time = $this->formatDate($time); } diff --git a/src/Trace/Tracer/ExtensionTracer.php b/src/Trace/Tracer/ExtensionTracer.php index 3808b3b9c..2919b607d 100644 --- a/src/Trace/Tracer/ExtensionTracer.php +++ b/src/Trace/Tracer/ExtensionTracer.php @@ -79,9 +79,7 @@ public function startSpan(array $spanOptions): Span public function withSpan(Span $span): Scope { $spanData = $span->spanData(); - $startTime = $spanData->startTime() - ? (float)($spanData->startTime()->format('U.u')) - : microtime(true); + $startTime = $spanData->startTime() ? (float)$spanData->startTime()->format('U.u') : microtime(true); $info = [ 'traceId' => $spanData->traceId(), 'spanId' => $spanData->spanId(), @@ -163,7 +161,7 @@ public function enabled() return $this->spanContext()->enabled(); } - public function attributeAdded(Span $span, $attribute, $value) + public function attributeAdded(Span $span, string $attribute, string $value): void { // If the span is already attached (managed by the extension), then // tell the extension to add the attribute. @@ -174,7 +172,7 @@ public function attributeAdded(Span $span, $attribute, $value) } } - public function linkAdded(Span $span, Link $link) + public function linkAdded(Span $span, Link $link): void { // If the span is already attached (managed by the extension), then // tell the extension to add the link. @@ -187,7 +185,7 @@ public function linkAdded(Span $span, Link $link) } } - public function timeEventAdded(Span $span, TimeEvent $timeEvent) + public function timeEventAdded(Span $span, TimeEvent $timeEvent): void { if ($span->attached()) { if ($timeEvent instanceof Annotation) { diff --git a/src/Utils/PrintableTrait.php b/src/Utils/PrintableTrait.php index 56dc14105..918efa86d 100644 --- a/src/Utils/PrintableTrait.php +++ b/src/Utils/PrintableTrait.php @@ -28,13 +28,15 @@ trait PrintableTrait * @param string $str string to test. * @return bool returns true if string is printable. */ - private static function isPrintable($str) + private static function isPrintable(string $str): bool { - for ($i = 0; $i < strlen($str); $i++) { + $length = strlen($str); + for ($i = 0; $i < $length; $i++) { if (!($str[$i] >= ' ' && $str[$i] <= '~')) { return false; } } + return true; } } diff --git a/tests/integration/curl/tests/CurlTest.php b/tests/integration/curl/tests/CurlTest.php index fd1b335ea..3dcf687cb 100644 --- a/tests/integration/curl/tests/CurlTest.php +++ b/tests/integration/curl/tests/CurlTest.php @@ -17,8 +17,8 @@ namespace OpenCensus\Tests\Integration\Trace; +use OpenCensus\Trace\Exporter\NullExporter; use OpenCensus\Trace\Tracer; -use OpenCensus\Trace\Exporter\ExporterInterface; use OpenCensus\Trace\Integrations\Curl; use PHPUnit\Framework\TestCase; @@ -44,8 +44,8 @@ public function testCurlExec() { $url = 'https://www.google.com/'; - $exporter = $this->prophesize(ExporterInterface::class); - $tracer = Tracer::start($exporter->reveal(), [ + $exporter = new NullExporter(); + $tracer = Tracer::start($exporter, [ 'skipReporting' => true ]); $ch = curl_init($url); diff --git a/tests/integration/guzzle5/tests/Guzzle5Test.php b/tests/integration/guzzle5/tests/Guzzle5Test.php index bf4b9293e..b741ed14b 100644 --- a/tests/integration/guzzle5/tests/Guzzle5Test.php +++ b/tests/integration/guzzle5/tests/Guzzle5Test.php @@ -19,8 +19,8 @@ use GuzzleHttp\Client; use HttpTest\HttpTestServer; +use OpenCensus\Trace\Exporter\NullExporter; use OpenCensus\Trace\Tracer; -use OpenCensus\Trace\Exporter\ExporterInterface; use OpenCensus\Trace\Integrations\Guzzle\EventSubscriber; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; @@ -54,8 +54,8 @@ function (RequestInterface $request, ResponseInterface &$response) { } ); - $exporter = $this->prophesize(ExporterInterface::class); - $tracer = Tracer::start($exporter->reveal(), [ + $exporter = new NullExporter(); + $tracer = Tracer::start($exporter, [ 'skipReporting' => true ]); @@ -91,8 +91,8 @@ function (RequestInterface $request, ResponseInterface &$response) { ); $traceContextHeader = '1603c1cde5c74f23bcf1682eb822fcf7/1150672535;o=1'; - $exporter = $this->prophesize(ExporterInterface::class); - $tracer = Tracer::start($exporter->reveal(), [ + $exporter = new NullExporter(); + $tracer = Tracer::start($exporter, [ 'skipReporting' => true, 'headers' => [ 'X-Cloud-Trace-Context' => $traceContextHeader diff --git a/tests/integration/guzzle6/tests/Guzzle6Test.php b/tests/integration/guzzle6/tests/Guzzle6Test.php index 07e8c939e..ef1f3a2a9 100644 --- a/tests/integration/guzzle6/tests/Guzzle6Test.php +++ b/tests/integration/guzzle6/tests/Guzzle6Test.php @@ -20,8 +20,8 @@ use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; use HttpTest\HttpTestServer; +use OpenCensus\Trace\Exporter\NullExporter; use OpenCensus\Trace\Tracer; -use OpenCensus\Trace\Exporter\ExporterInterface; use OpenCensus\Trace\Integrations\Guzzle\Middleware; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; @@ -53,8 +53,8 @@ function (RequestInterface $request, ResponseInterface &$response) { } ); - $exporter = $this->prophesize(ExporterInterface::class); - $tracer = Tracer::start($exporter->reveal(), [ + $exporter = new NullExporter(); + $tracer = Tracer::start($exporter, [ 'skipReporting' => true ]); $response = $this->client->get($server->getUrl()); @@ -91,8 +91,8 @@ function (RequestInterface $request, ResponseInterface &$response) { $traceContextHeader = '1603c1cde5c74f23bcf1682eb822fcf7/1150672535;o=1'; - $exporter = $this->prophesize(ExporterInterface::class); - $tracer = Tracer::start($exporter->reveal(), [ + $exporter = new NullExporter(); + $tracer = Tracer::start($exporter, [ 'skipReporting' => true, 'headers' => [ 'X-Cloud-Trace-Context' => $traceContextHeader diff --git a/tests/integration/memcached/tests/MemcachedTest.php b/tests/integration/memcached/tests/MemcachedTest.php index acc4f8efc..27f446478 100644 --- a/tests/integration/memcached/tests/MemcachedTest.php +++ b/tests/integration/memcached/tests/MemcachedTest.php @@ -17,8 +17,8 @@ namespace OpenCensus\Tests\Integration\Trace\Exporter; +use OpenCensus\Trace\Exporter\NullExporter; use OpenCensus\Trace\Tracer; -use OpenCensus\Trace\Exporter\ExporterInterface; use OpenCensus\Trace\Integrations\Memcached as MemcachedIntegration; use PHPUnit\Framework\TestCase; use Memcached; @@ -42,8 +42,8 @@ public function setUp() $this->markTestSkipped('Please enable the opencensus extension.'); } opencensus_trace_clear(); - $exporter = $this->prophesize(ExporterInterface::class); - $this->tracer = Tracer::start($exporter->reveal(), [ + $exporter = new NullExporter(); + $this->tracer = Tracer::start($exporter, [ 'skipReporting' => true ]); } diff --git a/tests/integration/pgsql/tests/PgsqlTest.php b/tests/integration/pgsql/tests/PgsqlTest.php index ac8e76f22..973e01877 100644 --- a/tests/integration/pgsql/tests/PgsqlTest.php +++ b/tests/integration/pgsql/tests/PgsqlTest.php @@ -17,8 +17,8 @@ namespace OpenCensus\Tests\Integration\Trace\Exporter; +use OpenCensus\Trace\Exporter\NullExporter; use OpenCensus\Trace\Tracer; -use OpenCensus\Trace\Exporter\ExporterInterface; use OpenCensus\Trace\Integrations\Postgres; use PHPUnit\Framework\TestCase; @@ -52,8 +52,8 @@ public function setUp() $this->markTestSkipped('Please enable the opencensus extension.'); } opencensus_trace_clear(); - $exporter = $this->prophesize(ExporterInterface::class); - $this->tracer = Tracer::start($exporter->reveal(), [ + $exporter = new NullExporter(); + $this->tracer = Tracer::start($exporter, [ 'skipReporting' => true ]); } diff --git a/tests/integration/symfony4/test.sh b/tests/integration/symfony4/test.sh index 8ba6656e1..1c9eb437c 100755 --- a/tests/integration/symfony4/test.sh +++ b/tests/integration/symfony4/test.sh @@ -24,8 +24,8 @@ cp -r src tests phpunit.xml.dist symfony/ pushd symfony composer config repositories.opencensus git ${REPO} -composer require opencensus/opencensus:dev-${BRANCH} doctrine -composer require --dev phpunit/phpunit:^7.0 guzzlehttp/guzzle:~6.0 +composer require --no-interaction opencensus/opencensus:dev-${BRANCH} doctrine +composer require --no-interaction --dev phpunit/phpunit:^7.0 guzzlehttp/guzzle:~6.0 bin/console doctrine:migrations:migrate -n vendor/bin/phpunit diff --git a/tests/unit/Core/ContextTest.php b/tests/unit/Core/ContextTest.php index e29f461b7..e4cf23b55 100644 --- a/tests/unit/Core/ContextTest.php +++ b/tests/unit/Core/ContextTest.php @@ -19,6 +19,7 @@ use OpenCensus\Core\Context; use PHPUnit\Framework\TestCase; +use PHPUnit_Framework_Error_Warning as Warning; /** * @group core @@ -68,14 +69,13 @@ public function testRestoringCurrentContext() $this->assertEquals($initialContext, Context::current()); } - /** - * @expectedException PHPUnit_Framework_Error_Warning - */ public function testRestoringCurrentContextRequiresSameObject() { $context = new Context(['foo' => 'bar']); $prevContext = $context->attach(); + $this->expectException(Warning::class); + $other = new Context(['foo' => 'bar']); $this->assertFalse($prevContext === $other); diff --git a/tests/unit/Trace/Integrations/Guzzle/EventSubscriberTest.php b/tests/unit/Trace/Integrations/Guzzle/EventSubscriberTest.php index 995dddab4..e9969e425 100644 --- a/tests/unit/Trace/Integrations/Guzzle/EventSubscriberTest.php +++ b/tests/unit/Trace/Integrations/Guzzle/EventSubscriberTest.php @@ -22,8 +22,8 @@ use GuzzleHttp\Subscriber\Mock; use GuzzleHttp\Subscriber\History; use GuzzleHttp\Message\Response; -use OpenCensus\Trace\Tracer; use OpenCensus\Trace\Exporter\ExporterInterface; +use OpenCensus\Trace\Tracer; use OpenCensus\Trace\Integrations\Guzzle\EventSubscriber; use Prophecy\Argument; use PHPUnit\Framework\TestCase; @@ -47,8 +47,8 @@ public function setUp() public function testAddsSpanContextHeader() { - $this->exporter->export(Argument::that(function ($spans) { - return count($spans) == 3 && $spans[2]->name() == 'GuzzleHttp::request'; + $this->exporter->export(Argument::that(static function ($spans) { + return count($spans) === 3 && $spans[2]->name() === 'GuzzleHttp::request'; }))->shouldBeCalled(); $rt = Tracer::start($this->exporter->reveal(), [ @@ -66,7 +66,7 @@ public function testAddsSpanContextHeader() $client->getEmitter()->attach($history); $client->getEmitter()->attach($subscriber); - Tracer::inSpan(['name' => 'parentSpan', 'spanId' => '1234'], function () use ($client) { + Tracer::inSpan(['name' => 'parentSpan', 'spanId' => '1234'], static function () use ($client) { $client->get('/'); }); diff --git a/tests/unit/Trace/Integrations/Guzzle/MiddlewareTest.php b/tests/unit/Trace/Integrations/Guzzle/MiddlewareTest.php index 9a5982d64..627a2f2bc 100644 --- a/tests/unit/Trace/Integrations/Guzzle/MiddlewareTest.php +++ b/tests/unit/Trace/Integrations/Guzzle/MiddlewareTest.php @@ -18,6 +18,7 @@ namespace OpenCensus\Tests\Unit\Trace\Integrations\Guzzle; use OpenCensus\Core\Context; +use OpenCensus\Trace\Exporter\NullExporter; use OpenCensus\Trace\Tracer; use OpenCensus\Trace\Exporter\ExporterInterface; use OpenCensus\Trace\Integrations\Guzzle\Middleware; diff --git a/tests/unit/Trace/Integrations/PDOTest.php b/tests/unit/Trace/Integrations/PDOTest.php index 9333cd805..d79625e8f 100644 --- a/tests/unit/Trace/Integrations/PDOTest.php +++ b/tests/unit/Trace/Integrations/PDOTest.php @@ -55,9 +55,4 @@ public function testHandleConnect() $this->assertEquals($expected, $spanOptions); } - - public function testStatmentExecute() - { - $this->markTestSkipped('Cannot test without a database instance'); - } } diff --git a/tests/unit/Trace/Propagator/BinaryFormatterTest.php b/tests/unit/Trace/Propagator/BinaryFormatterTest.php index 5699bb2cb..501092387 100644 --- a/tests/unit/Trace/Propagator/BinaryFormatterTest.php +++ b/tests/unit/Trace/Propagator/BinaryFormatterTest.php @@ -20,6 +20,7 @@ use OpenCensus\Trace\SpanContext; use OpenCensus\Trace\Propagator\BinaryFormatter; use PHPUnit\Framework\TestCase; +use PHPUnit_Framework_Error_Warning as Warning; /** * @group trace @@ -49,13 +50,11 @@ public function testSerialize($traceId, $spanId, $enabled, $hex) $this->assertEquals($hex, bin2hex($formatter->serialize($context))); } - /** - * @expectedException PHPUnit_Framework_Error_Warning - */ public function testDeserializeBadData() { $formatter = new BinaryFormatter(); - $context = $formatter->deserialize(hex2bin("0012341abc")); + $this->expectException(Warning::class); + $formatter->deserialize(hex2bin("0012341abc")); } public function testDeserializeBadDataReturnsEmptySpanContext() diff --git a/tests/unit/Trace/RequestHandlerTest.php b/tests/unit/Trace/RequestHandlerTest.php index ed9ceab27..ade200999 100644 --- a/tests/unit/Trace/RequestHandlerTest.php +++ b/tests/unit/Trace/RequestHandlerTest.php @@ -20,15 +20,15 @@ require_once __DIR__ . '/mock_http_response_code.php'; use OpenCensus\Trace\Annotation; +use OpenCensus\Trace\Exporter\NullExporter; use OpenCensus\Trace\Link; use OpenCensus\Trace\MessageEvent; +use OpenCensus\Trace\Sampler\AlwaysSampleSampler; +use OpenCensus\Trace\Sampler\NeverSampleSampler; use OpenCensus\Trace\Span; -use OpenCensus\Trace\SpanContext; use OpenCensus\Trace\SpanData; use OpenCensus\Trace\Status; use OpenCensus\Trace\RequestHandler; -use OpenCensus\Trace\Exporter\ExporterInterface; -use OpenCensus\Trace\Sampler\SamplerInterface; use OpenCensus\Trace\Tracer\NullTracer; use OpenCensus\Trace\Propagator\HttpHeaderPropagator; use OpenCensus\Trace\MockHttpResponseCode; @@ -41,24 +41,19 @@ class RequestHandlerTest extends TestCase { private $exporter; - private $sampler; - public function setUp() { if (extension_loaded('opencensus')) { opencensus_trace_clear(); } - $this->exporter = $this->prophesize(ExporterInterface::class); - $this->sampler = $this->prophesize(SamplerInterface::class); + $this->exporter = new NullExporter(); } public function testCanTrackContext() { - $this->sampler->shouldSample()->willReturn(true); - $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new AlwaysSampleSampler(), new HttpHeaderPropagator(), [ 'skipReporting' => true @@ -82,8 +77,8 @@ public function testCanTrackContext() public function testCanParseParentContext() { $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new NeverSampleSampler(), new HttpHeaderPropagator(), [ 'headers' => [ @@ -101,8 +96,8 @@ public function testCanParseParentContext() public function testForceEnabledContextHeader() { $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new NeverSampleSampler(), new HttpHeaderPropagator(), [ 'headers' => [ @@ -119,8 +114,8 @@ public function testForceEnabledContextHeader() public function testForceDisabledContextHeader() { $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new NeverSampleSampler(), new HttpHeaderPropagator(), [ 'headers' => [ @@ -137,10 +132,9 @@ public function testForceDisabledContextHeader() public function testAddsAttributes() { - $this->sampler->shouldSample()->willReturn(true); $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new AlwaysSampleSampler(), new HttpHeaderPropagator(), [ 'skipReporting' => true @@ -161,10 +155,9 @@ public function testAddsAttributes() public function testAddsAttributesToSpecificSpan() { - $this->sampler->shouldSample()->willReturn(true); $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new AlwaysSampleSampler(), new HttpHeaderPropagator(), [ 'skipReporting' => true @@ -187,10 +180,9 @@ public function testAddsAttributesToSpecificSpan() public function testAddsAttributesToSpecificUnattachedDetachedSpan() { - $this->sampler->shouldSample()->willReturn(true); $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new AlwaysSampleSampler(), new HttpHeaderPropagator(), [ 'skipReporting' => true @@ -211,10 +203,9 @@ public function testAddsAttributesToSpecificUnattachedDetachedSpan() public function testAddsAttributesToSpecificDetachedSpan() { - $this->sampler->shouldSample()->willReturn(true); $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new AlwaysSampleSampler(), new HttpHeaderPropagator(), [ 'skipReporting' => true @@ -235,10 +226,9 @@ public function testAddsAttributesToSpecificDetachedSpan() public function testAddsAnnotation() { - $this->sampler->shouldSample()->willReturn(true); $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new AlwaysSampleSampler(), new HttpHeaderPropagator(), [ 'skipReporting' => true @@ -269,10 +259,9 @@ public function testAddsAnnotation() public function testAddsAnnotationToSpecificSpan() { - $this->sampler->shouldSample()->willReturn(true); $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new AlwaysSampleSampler(), new HttpHeaderPropagator(), [ 'skipReporting' => true @@ -304,10 +293,9 @@ public function testAddsAnnotationToSpecificSpan() public function testAddsAnnotationToSpecificUnattachedDetachedSpan() { - $this->sampler->shouldSample()->willReturn(true); $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new AlwaysSampleSampler(), new HttpHeaderPropagator(), [ 'skipReporting' => true @@ -338,10 +326,9 @@ public function testAddsAnnotationToSpecificUnattachedDetachedSpan() public function testAddsAnnotationToSpecificDetachedSpan() { - $this->sampler->shouldSample()->willReturn(true); $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new AlwaysSampleSampler(), new HttpHeaderPropagator(), [ 'skipReporting' => true @@ -372,10 +359,9 @@ public function testAddsAnnotationToSpecificDetachedSpan() public function testAddsLink() { - $this->sampler->shouldSample()->willReturn(true); $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new AlwaysSampleSampler(), new HttpHeaderPropagator(), [ 'skipReporting' => true @@ -409,10 +395,9 @@ public function testAddsLink() public function testAddsLinkToSpecificSpan() { - $this->sampler->shouldSample()->willReturn(true); $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new AlwaysSampleSampler(), new HttpHeaderPropagator(), [ 'skipReporting' => true @@ -447,10 +432,9 @@ public function testAddsLinkToSpecificSpan() public function testAddsLinkToSpecificUnattachedDetachedSpan() { - $this->sampler->shouldSample()->willReturn(true); $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new AlwaysSampleSampler(), new HttpHeaderPropagator(), [ 'skipReporting' => true @@ -484,10 +468,9 @@ public function testAddsLinkToSpecificUnattachedDetachedSpan() public function testAddsLinkToSpecificDetachedSpan() { - $this->sampler->shouldSample()->willReturn(true); $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new AlwaysSampleSampler(), new HttpHeaderPropagator(), [ 'skipReporting' => true @@ -521,10 +504,9 @@ public function testAddsLinkToSpecificDetachedSpan() public function testAddsMessageEvent() { - $this->sampler->shouldSample()->willReturn(true); $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new AlwaysSampleSampler(), new HttpHeaderPropagator(), [ 'skipReporting' => true @@ -556,10 +538,9 @@ public function testAddsMessageEvent() public function testAddsMessageEventToSpecificSpan() { - $this->sampler->shouldSample()->willReturn(true); $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new AlwaysSampleSampler(), new HttpHeaderPropagator(), [ 'skipReporting' => true @@ -592,10 +573,9 @@ public function testAddsMessageEventToSpecificSpan() public function testAddsMessageEventToSpecificUnattachedDetachedSpan() { - $this->sampler->shouldSample()->willReturn(true); $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new AlwaysSampleSampler(), new HttpHeaderPropagator(), [ 'skipReporting' => true @@ -631,10 +611,9 @@ public function testAddsMessageEventToSpecificUnattachedDetachedSpan() public function testAddsMessageEventToSpecificDetachedSpan() { - $this->sampler->shouldSample()->willReturn(true); $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new AlwaysSampleSampler(), new HttpHeaderPropagator(), [ 'skipReporting' => true @@ -670,10 +649,9 @@ public function testAddsMessageEventToSpecificDetachedSpan() public function testNoStatusOfRootSpanOnExitWithoutHttpResponse() { - $this->sampler->shouldSample()->willReturn(true); $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new AlwaysSampleSampler(), new HttpHeaderPropagator(), [ 'skipReporting' => true @@ -693,10 +671,9 @@ public function testNoStatusOfRootSpanOnExitWithoutHttpResponse() public function testSetsStatusOfRootSpanOnExitWithHttpResponse() { - $this->sampler->shouldSample()->willReturn(true); $rt = new RequestHandler( - $this->exporter->reveal(), - $this->sampler->reveal(), + $this->exporter, + new AlwaysSampleSampler(), new HttpHeaderPropagator(), [ 'skipReporting' => true diff --git a/tests/unit/Trace/Sampler/MultiSamplerTest.php b/tests/unit/Trace/Sampler/MultiSamplerTest.php index 3b26f3213..4165c3461 100644 --- a/tests/unit/Trace/Sampler/MultiSamplerTest.php +++ b/tests/unit/Trace/Sampler/MultiSamplerTest.php @@ -17,8 +17,9 @@ namespace OpenCensus\Tests\Unit\Trace\Sampler; +use OpenCensus\Trace\Sampler\AlwaysSampleSampler; use OpenCensus\Trace\Sampler\MultiSampler; -use OpenCensus\Trace\Sampler\SamplerInterface; +use OpenCensus\Trace\Sampler\NeverSampleSampler; use PHPUnit\Framework\TestCase; /** @@ -26,48 +27,39 @@ */ class MultiSamplerTest extends TestCase { - public function testNoSamplers() + public function testNoSamplersShouldSample() { $sampler = new MultiSampler(); + $this->assertTrue($sampler->shouldSample()); } - public function testSingleSampler() + public function testOneSamplerShouldSample() { - $innerSampler = $this->prophesize(SamplerInterface::class); - $innerSampler->shouldSample()->willReturn(true)->shouldBeCalled(); - $sampler = new MultiSampler([ - $innerSampler->reveal() + new AlwaysSampleSampler(), ]); + $this->assertTrue($sampler->shouldSample()); } - public function testMultipleSamplers() + public function testMultipleSamplersShouldSample() { - $innerSampler = $this->prophesize(SamplerInterface::class); - $innerSampler->shouldSample()->willReturn(true)->shouldBeCalled(); - $innerSampler2 = $this->prophesize(SamplerInterface::class); - $innerSampler2->shouldSample()->willReturn(true)->shouldBeCalled(); - $sampler = new MultiSampler([ - $innerSampler->reveal(), - $innerSampler2->reveal() + new AlwaysSampleSampler(), + new AlwaysSampleSampler(), ]); + $this->assertTrue($sampler->shouldSample()); } - public function testInnerSamplerFails() + public function testOneFromMultipleSamplersFailsShouldNotSample() { - $innerSampler = $this->prophesize(SamplerInterface::class); - $innerSampler->shouldSample()->willReturn(true)->shouldBeCalled(); - $innerSampler2 = $this->prophesize(SamplerInterface::class); - $innerSampler2->shouldSample()->willReturn(false)->shouldBeCalled(); - $sampler = new MultiSampler([ - $innerSampler->reveal(), - $innerSampler2->reveal() + new AlwaysSampleSampler(), + new NeverSampleSampler(), ]); + $this->assertFalse($sampler->shouldSample()); } } diff --git a/tests/unit/Trace/TracerTest.php b/tests/unit/Trace/TracerTest.php index 7f8a7d7e2..3e18f3ff8 100644 --- a/tests/unit/Trace/TracerTest.php +++ b/tests/unit/Trace/TracerTest.php @@ -17,7 +17,7 @@ namespace OpenCensus\Tests\Unit\Trace; -use OpenCensus\Trace\Exporter\ExporterInterface; +use OpenCensus\Trace\Exporter\NullExporter; use OpenCensus\Trace\Sampler\AlwaysSampleSampler; use OpenCensus\Trace\Sampler\NeverSampleSampler; use OpenCensus\Trace\Tracer; @@ -29,16 +29,16 @@ */ class TracerTest extends TestCase { - private $reporter; + private $exporter; public function setUp() { - $this->reporter = $this->prophesize(ExporterInterface::class); + $this->exporter = new NullExporter(); } public function testForceDisabled() { - $rt = Tracer::start($this->reporter->reveal(), [ + $rt = Tracer::start($this->exporter, [ 'sampler' => new NeverSampleSampler(), 'skipReporting' => true ]); @@ -50,7 +50,7 @@ public function testForceDisabled() public function testForceEnabled() { - $rt = Tracer::start($this->reporter->reveal(), [ + $rt = Tracer::start($this->exporter, [ 'sampler' => new AlwaysSampleSampler(), 'skipReporting' => true ]); @@ -61,7 +61,7 @@ public function testForceEnabled() public function testGlobalAttributes() { - $rt = Tracer::start($this->reporter->reveal(), [ + $rt = Tracer::start($this->exporter, [ 'sampler' => new AlwaysSampleSampler(), 'skipReporting' => true ]); @@ -73,7 +73,7 @@ public function testGlobalAttributes() public function testGlobalAnnotation() { - $rt = Tracer::start($this->reporter->reveal(), [ + $rt = Tracer::start($this->exporter, [ 'sampler' => new AlwaysSampleSampler(), 'skipReporting' => true ]); @@ -93,7 +93,7 @@ public function testGlobalAnnotation() public function testGlobalMessageEvent() { - $rt = Tracer::start($this->reporter->reveal(), [ + $rt = Tracer::start($this->exporter, [ 'sampler' => new AlwaysSampleSampler(), 'skipReporting' => true ]); @@ -109,7 +109,7 @@ public function testGlobalMessageEvent() public function testGlobalLink() { - $rt = Tracer::start($this->reporter->reveal(), [ + $rt = Tracer::start($this->exporter, [ 'sampler' => new AlwaysSampleSampler(), 'skipReporting' => true ]);