1.0 ) { throw new InvalidArgumentException( "Sample rate can only be between 0.0 and 1.0. Got: " . $newSampleRate ); } } /** * Returns a subset of samples based on configured sample rate. * * @param float $sampleRate * @param array $samples * @return array */ public static function getFilteredSamples( float $sampleRate, array $samples ): array { if ( $sampleRate === 1.0 ) { return $samples; } $output = []; $randMax = mt_getrandmax(); foreach ( $samples as $sample ) { if ( mt_rand() / $randMax < $sampleRate ) { $output[] = $sample; } } return $output; } /** * Determines if provided string is a valid name. * * @param string $name * @return void * @throws InvalidArgumentException * @throws InvalidConfigurationException */ public static function validateMetricName( string $name ) { if ( $name === "" ) { throw new InvalidArgumentException( "Stats: Metric name cannot be empty." ); } if ( !preg_match( self::RE_VALID_NAME_AND_LABEL_NAME, $name ) ) { throw new InvalidConfigurationException( "Invalid metric name: '" . $name . "'" ); } } /** * Determines if provided string is a valid label key. * * @param string $key * @return void * @throws InvalidArgumentException * @throws InvalidConfigurationException */ public static function validateLabelKey( string $key ) { if ( $key === "" ) { throw new InvalidArgumentException( "Stats: Label key cannot be empty." ); } if ( !preg_match( self::RE_VALID_NAME_AND_LABEL_NAME, $key ) ) { throw new InvalidConfigurationException( "Invalid label key: '" . $key . "'" ); } } public static function validateLabelValue( string $value ) { if ( $value === "" ) { throw new InvalidArgumentException( "Stats: Label value cannot be empty." ); } } /** * Normalize an array of strings. * * @param string[] $entities * @return string[] */ public static function normalizeArray( array $entities ): array { $normalizedEntities = []; foreach ( $entities as $entity ) { $normalizedEntities[] = self::normalizeString( $entity ); } return $normalizedEntities; } /** * Normalize strings to a metrics-compatible format. * * Replace all other non-alphanumeric characters with an underscore. * Trim leading or trailing underscores. * * @param string $entity * @return string */ public static function normalizeString( string $entity ): string { $entity = preg_replace( '/[^a-z\d]+/i', '_', $entity ); return trim( $entity, "_" ); } }