* @file
*/
+use Psr\Log\LoggerAwareInterface;
+use Psr\Log\LoggerInterface;
+use Psr\Log\NullLogger;
+
/**
* An interface to help developers measure the performance of their applications.
* This interface closely matches the W3C's User Timing specification.
*
* @since 1.27
*/
-class Timing {
+class Timing implements LoggerAwareInterface {
/** @var array[] */
- private $entries = array();
+ private $entries = [];
+
+ /** @var LoggerInterface */
+ protected $logger;
- public function __construct() {
+ public function __construct( array $params = [] ) {
$this->clearMarks();
+ $this->setLogger( isset( $params['logger'] ) ? $params['logger'] : new NullLogger() );
+ }
+
+ /**
+ * Sets a logger instance on the object.
+ *
+ * @param LoggerInterface $logger
+ * @return null
+ */
+ public function setLogger( LoggerInterface $logger ) {
+ $this->logger = $logger;
}
/**
* @return array The mark that has been created.
*/
public function mark( $markName ) {
- $this->entries[$markName] = array(
+ $this->entries[$markName] = [
'name' => $markName,
'entryType' => 'mark',
'startTime' => microtime( true ),
'duration' => 0,
- );
+ ];
return $this->entries[$markName];
}
if ( $markName !== null ) {
unset( $this->entries[$markName] );
} else {
- $this->entries = array(
- 'requestStart' => array(
+ $this->entries = [
+ 'requestStart' => [
'name' => 'requestStart',
'entryType' => 'mark',
'startTime' => isset( $_SERVER['REQUEST_TIME_FLOAT'] )
? $_SERVER['REQUEST_TIME_FLOAT']
: $_SERVER['REQUEST_TIME'],
'duration' => 0,
- ),
- );
+ ],
+ ];
}
}
* @param string $measureName
* @param string $startMark
* @param string $endMark
- * @return array The measure that has been created.
+ * @return array|bool The measure that has been created, or false if either
+ * the start mark or the end mark do not exist.
*/
public function measure( $measureName, $startMark = 'requestStart', $endMark = null ) {
$start = $this->getEntryByName( $startMark );
+ if ( $start === null ) {
+ $this->logger->error( __METHOD__ . ": The mark '$startMark' does not exist" );
+ return false;
+ }
$startTime = $start['startTime'];
if ( $endMark ) {
$end = $this->getEntryByName( $endMark );
+ if ( $end === null ) {
+ $this->logger->error( __METHOD__ . ": The mark '$endMark' does not exist" );
+ return false;
+ }
$endTime = $end['startTime'];
} else {
$endTime = microtime( true );
}
- $this->entries[$measureName] = array(
+ $this->entries[$measureName] = [
'name' => $measureName,
'entryType' => 'measure',
'startTime' => $startTime,
'duration' => $endTime - $startTime,
- );
+ ];
return $this->entries[$measureName];
}
*/
public function getEntriesByType( $entryType ) {
$this->sortEntries();
- $entries = array();
+ $entries = [];
foreach ( $this->entries as $entry ) {
if ( $entry['entryType'] === $entryType ) {
$entries[] = $entry;