|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace HelloFresh\Stats\Bucket; |
| 4 | + |
| 5 | + |
| 6 | +use Behat\Transliterator\Transliterator; |
| 7 | +use HelloFresh\Stats\Bucket; |
| 8 | + |
| 9 | +class Plain implements Bucket |
| 10 | +{ |
| 11 | + /** @var string */ |
| 12 | + protected $section; |
| 13 | + /** @var string */ |
| 14 | + protected $operation; |
| 15 | + /** @var bool */ |
| 16 | + protected $success; |
| 17 | + |
| 18 | + protected static $status = [true => Bucket::SUFFIX_STATUS_OK, false => Bucket::SUFFIX_STATUS_FAIL]; |
| 19 | + |
| 20 | + /** |
| 21 | + * Plain constructor. |
| 22 | + * |
| 23 | + * @param string $section |
| 24 | + * @param MetricOperation $operation |
| 25 | + * @param bool $success |
| 26 | + */ |
| 27 | + public function __construct($section, MetricOperation $operation, $success) |
| 28 | + { |
| 29 | + $this->section = static::sanitizeMetricName($section); |
| 30 | + $this->success = $success; |
| 31 | + |
| 32 | + $operationSanitized = []; |
| 33 | + foreach ($operation as $op) { |
| 34 | + $operationSanitized[] = static::sanitizeMetricName($op); |
| 35 | + } |
| 36 | + $this->operation = implode('.', $operationSanitized); |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * @inheritdoc |
| 41 | + */ |
| 42 | + public function metric() |
| 43 | + { |
| 44 | + return sprintf('%s.%s', $this->section, $this->operation); |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * @inheritdoc |
| 49 | + */ |
| 50 | + public function metricWithSuffix() |
| 51 | + { |
| 52 | + return sprintf('%s-%s.%s', $this->section, static::$status[$this->success], $this->operation); |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * @inheritdoc |
| 57 | + */ |
| 58 | + public function metricTotal() |
| 59 | + { |
| 60 | + return sprintf('%s.%s', Bucket::TOTAL_BUCKET, $this->section); |
| 61 | + } |
| 62 | + |
| 63 | + /** |
| 64 | + * @inheritdoc |
| 65 | + */ |
| 66 | + public function metricTotalWithSuffix() |
| 67 | + { |
| 68 | + return sprintf('%s.%s-%s', Bucket::TOTAL_BUCKET, $this->section, static::$status[$this->success]); |
| 69 | + } |
| 70 | + |
| 71 | + /** |
| 72 | + * @param string $metric |
| 73 | + * |
| 74 | + * @return string |
| 75 | + */ |
| 76 | + public static function sanitizeMetricName($metric) |
| 77 | + { |
| 78 | + if ($metric == "") { |
| 79 | + return Bucket::METRIC_EMPTY_PLACEHOLDER; |
| 80 | + } |
| 81 | + |
| 82 | + // convert unicode symbols to ASCII |
| 83 | + $asciiMetric = Transliterator::utf8ToAscii($metric); |
| 84 | + if ($asciiMetric != $metric) { |
| 85 | + $metric = Bucket::PREFIX_UNICODE . $asciiMetric; |
| 86 | + } |
| 87 | + |
| 88 | + // replace underscores with double underscores |
| 89 | + // and dots with single underscore |
| 90 | + return str_replace( |
| 91 | + '.', |
| 92 | + '_', |
| 93 | + str_replace('_', '__', $metric) |
| 94 | + ); |
| 95 | + } |
| 96 | +} |
0 commit comments