Merge "Support mustache partials in server-side templates"
[lhc/web/wiklou.git] / includes / libs / BufferingStatsdDataFactory.php
1 <?php
2 /**
3 * Copyright 2015
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use Liuggio\StatsdClient\Entity\StatsdDataInterface;
24 use Liuggio\StatsdClient\Factory\StatsdDataFactory;
25
26 /**
27 * A factory for application metric data.
28 *
29 * This class prepends a context-specific prefix to each metric key and keeps
30 * a reference to each constructed metric in an internal array buffer.
31 *
32 * @since 1.25
33 */
34 class BufferingStatsdDataFactory extends StatsdDataFactory {
35 protected $buffer = array();
36
37 public function __construct( $prefix ) {
38 parent::__construct();
39 $this->prefix = $prefix;
40 }
41
42 /**
43 * Normalize a metric key for StatsD
44 *
45 * Replace occurences of '::' with dots and any other non-alphabetic
46 * characters with underscores. Combine runs of dots or underscores.
47 * Then trim leading or trailing dots or underscores.
48 *
49 * @param string $key
50 * @since 1.26
51 */
52 private static function normalizeMetricKey( $key ) {
53 $key = preg_replace( '/[:.]+/', '.', $key );
54 $key = preg_replace( '/[^a-z.]+/i', '_', $key );
55 $key = trim( $key, '_.' );
56 return str_replace( array( '._', '_.' ), '.', $key );
57 }
58
59 public function produceStatsdData( $key, $value = 1, $metric = StatsdDataInterface::STATSD_METRIC_COUNT ) {
60 $entity = $this->produceStatsdDataEntity();
61 if ( $key !== null ) {
62 $key = self::normalizeMetricKey( "{$this->prefix}.{$key}" );
63 $entity->setKey( $key );
64 }
65 if ( $value !== null ) {
66 $entity->setValue( $value );
67 }
68 if ( $metric !== null ) {
69 $entity->setMetric( $metric );
70 }
71 // Don't bother buffering a counter update with a delta of zero.
72 if ( !( $metric === StatsdDataInterface::STATSD_METRIC_COUNT && !$value ) ) {
73 $this->buffer[] = $entity;
74 }
75 return $entity;
76 }
77
78 public function getBuffer() {
79 return $this->buffer;
80 }
81 }