summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/Maintenance/MaintenanceHelper.php
blob: 1b2de4a2919ead4973832daae6026453085b7c59 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php

namespace SMW\Maintenance;

use SMW\ApplicationFactory;

/**
 * @license GNU GPL v2+
 * @since 2.2
 *
 * @author mwjames
 */
class MaintenanceHelper {

	/**
	 * @var array
	 */
	private $globals = [];

	/**
	 * @var array
	 */
	private $runtime = [
		'start'  => 0,
		'memory' => 0
	];

	/**
	 * @since 2.2
	 */
	public function initRuntimeValues() {
		$this->runtime['start'] = microtime( true );
		$this->runtime['memory'] = memory_get_peak_usage( false );
	}

	/**
	 * @since 2.2
	 *
	 * @return array
	 */
	public function getRuntimeValues() {

		$memory = memory_get_peak_usage( false );
		$time = microtime( true ) - $this->runtime['start'];

		$hTime = round( $time, 2 ) . ' sec';
		$hTime .= ( $time > 60 ? ' (' . round( $time / 60, 2 ) . ' min)' : '' );

		return [
			'time' => $time,
			'humanreadable-time' => $hTime,
			'memory-before' => $this->runtime['memory'],
			'memory-after'  => $memory,
			'memory-used'   => $memory - $this->runtime['memory']
		];
	}

	/**
	 * @since 2.2
	 *
	 * @return string
	 */
	public function getFormattedRuntimeValues( $indent = '' ) {

		$runtimeValues = $this->getRuntimeValues();

		return "$indent Memory used: " . $runtimeValues['memory-used'] . "\n" .
			"$indent Time: " . $runtimeValues['humanreadable-time'];
	}

	/**
	 * @since 2.2
	 *
	 * @param string $key
	 * @param string $value
	 */
	public function setGlobalToValue( $key, $value ) {

		if ( !isset( $GLOBALS[$key] ) ) {
			return;
		}

		$this->globals[$key] = $GLOBALS[$key];
		$GLOBALS[$key] = $value;
		ApplicationFactory::getInstance()->getSettings()->set( $key, $value );
	}

	/**
	 * @since 2.2
	 */
	public function reset() {

		foreach ( $this->globals as $key => $value ) {
			$GLOBALS[$key] = $value;
			ApplicationFactory::getInstance()->getSettings()->set( $key, $value );
		}

		$this->runtime['start'] = 0;
		$this->runtime['memory'] = 0;
	}

}