MediaWiki REL1_28
/src/tests/phpunit/MediaWikiTestCase.php

Sets a global, maintaining a stashed version of the previous global to be restored in tearDown.

Sets a global, maintaining a stashed version of the previous global to be restored in tearDownThe key is added to the array of globals that will be reset afterwards in the tearDown().

protected function setUp() { $this->setMwGlobals( 'wgRestrictStuff', true ); }

function testFoo() {}

function testBar() {} $this->assertTrue( self::getX()->doStuff() );

$this->setMwGlobals( 'wgRestrictStuff', false ); $this->assertTrue( self::getX()->doStuff() ); }

function testQuux() {}

Parameters
array | string$pairsKey to the global variable, or an array of key/value pairs.
mixed$valueValue to set the global to (ignored if an array is given as first argument).
Note
To allow changes to global variables to take effect on global service instances, call overrideMwServices().
Since
1.21
<?php
use Psr\Log\LoggerInterface;
abstract class MediaWikiTestCase extends PHPUnit_Framework_TestCase {
private static $serviceLocator = null;
private $called = [];
public static $users;
protected $db;
protected $tablesUsed = []; // tables with data
private static $useTemporaryTables = true;
private static $reuseDB = false;
private static $dbSetup = false;
private static $oldTablePrefix = '';
private $phpErrorLevel;
private $tmpFiles = [];
private $mwGlobals = [];
private $loggers = [];
const DB_PREFIX = 'unittest_';
const ORA_DB_PREFIX = 'ut_';
protected $supportedDBs = [
'mysql',
'sqlite',
'postgres',
'oracle'
];
public function __construct( $name = null, array $data = [], $dataName = '' ) {
parent::__construct( $name, $data, $dataName );
$this->backupGlobals = false;
$this->backupStaticAttributes = false;
}
public function __destruct() {
// Complain if self::setUp() was called, but not self::tearDown()
// $this->called['setUp'] will be checked by self::testMediaWikiTestCaseParentSetupCalled()
if ( isset( $this->called['setUp'] ) && !isset( $this->called['tearDown'] ) ) {
throw new MWException( static::class . "::tearDown() must call parent::tearDown()" );
}
}
public static function setUpBeforeClass() {
parent::setUpBeforeClass();
// Get the service locator, and reset services if it's not done already
self::$serviceLocator = self::prepareServices( new GlobalVarConfig() );
}
public static function getTestUser( $groups = [] ) {
}
public static function getMutableTestUser( $groups = [] ) {
return TestUserRegistry::getMutableTestUser( __CLASS__, $groups );
}
public static function getTestSysop() {
return self::getTestUser( [ 'sysop', 'bureaucrat' ] );
}
public static function prepareServices( Config $bootstrapConfig ) {
static $services = null;
if ( !$services ) {
$services = self::resetGlobalServices( $bootstrapConfig );
}
return $services;
}
protected static function resetGlobalServices( Config $bootstrapConfig = null ) {
$oldServices = MediaWikiServices::getInstance();
$oldConfigFactory = $oldServices->getConfigFactory();
$testConfig = self::makeTestConfig( $bootstrapConfig );
MediaWikiServices::resetGlobalInstance( $testConfig );
$serviceLocator = MediaWikiServices::getInstance();
self::installTestServices(
$oldConfigFactory,
$serviceLocator
);
return $serviceLocator;
}
private static function makeTestConfig(
Config $baseConfig = null,
Config $customOverrides = null
) {
$defaultOverrides = new HashConfig();
if ( !$baseConfig ) {
$baseConfig = MediaWikiServices::getInstance()->getBootstrapConfig();
}
/* Some functions require some kind of caching, and will end up using the db,
* which we can't allow, as that would open a new connection for mysql.
* Replace with a HashBag. They would not be going to persist anyway.
*/
$hashCache = [ 'class' => 'HashBagOStuff', 'reportDupes' => false ];
$objectCaches = [
CACHE_DB => $hashCache,
CACHE_ACCEL => $hashCache,
CACHE_MEMCACHED => $hashCache,
'apc' => $hashCache,
'xcache' => $hashCache,
'wincache' => $hashCache,
] + $baseConfig->get( 'ObjectCaches' );
$defaultOverrides->set( 'ObjectCaches', $objectCaches );
$defaultOverrides->set( 'MainCacheType', CACHE_NONE );
$defaultOverrides->set( 'JobTypeConf', [ 'default' => [ 'class' => 'JobQueueMemory' ] ] );
// Use a fast hash algorithm to hash passwords.
$defaultOverrides->set( 'PasswordDefault', 'A' );
$testConfig = $customOverrides
? new MultiConfig( [ $customOverrides, $defaultOverrides, $baseConfig ] )
: new MultiConfig( [ $defaultOverrides, $baseConfig ] );
return $testConfig;
}
private static function installTestServices(
ConfigFactory $oldConfigFactory,
MediaWikiServices $newServices
) {
// Use bootstrap config for all configuration.
// This allows config overrides via global variables to take effect.
$bootstrapConfig = $newServices->getBootstrapConfig();
$newServices->resetServiceForTesting( 'ConfigFactory' );
$newServices->redefineService(
'ConfigFactory',
self::makeTestConfigFactoryInstantiator(
$oldConfigFactory,
[ 'main' => $bootstrapConfig ]
)
);
}
private static function makeTestConfigFactoryInstantiator(
ConfigFactory $oldFactory,
array $configurations
) {
return function( MediaWikiServices $services ) use ( $oldFactory, $configurations ) {
$factory = new ConfigFactory();
// clone configurations from $oldFactory that are not overwritten by $configurations
$namesToClone = array_diff(
$oldFactory->getConfigNames(),
array_keys( $configurations )
);
foreach ( $namesToClone as $name ) {
$factory->register( $name, $oldFactory->makeConfig( $name ) );
}
foreach ( $configurations as $name => $config ) {
$factory->register( $name, $config );
}
return $factory;
};
}
private function doLightweightServiceReset() {
ObjectCache::clear();
$services = MediaWikiServices::getInstance();
$services->resetServiceForTesting( 'MainObjectStash' );
$services->resetServiceForTesting( 'LocalServerObjectCache' );
$services->getMainWANObjectCache()->clearProcessCache();
// TODO: move global state into MediaWikiServices
if ( session_id() !== '' ) {
session_write_close();
session_id( '' );
}
MediaWiki\Session\SessionManager::resetCache();
}
public function run( PHPUnit_Framework_TestResult $result = null ) {
// Reset all caches between tests.
$this->doLightweightServiceReset();
$needsResetDB = false;
if ( !self::$dbSetup || $this->needsDB() ) {
// set up a DB connection for this test to use
self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
self::$reuseDB = $this->getCliArg( 'reuse-db' );
$this->db = wfGetDB( DB_MASTER );
$this->checkDbIsSupported();
if ( !self::$dbSetup ) {
$this->setupAllTestDBs();
$this->addCoreDBData();
if ( ( $this->db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
$this->resetDB( $this->db, $this->tablesUsed );
}
}
// TODO: the DB setup should be done in setUpBeforeClass(), so the test DB
// is available in subclass's setUpBeforeClass() and setUp() methods.
// This would also remove the need for the HACK that is oncePerClass().
if ( $this->oncePerClass() ) {
$this->addDBDataOnce();
}
$this->addDBData();
$needsResetDB = true;
}
parent::run( $result );
if ( $needsResetDB ) {
$this->resetDB( $this->db, $this->tablesUsed );
}
}
private function oncePerClass() {
// Remember current test class in the database connection,
// so we know when we need to run addData.
$class = static::class;
$first = !isset( $this->db->_hasDataForTestClass )
|| $this->db->_hasDataForTestClass !== $class;
$this->db->_hasDataForTestClass = $class;
return $first;
}
public function usesTemporaryTables() {
return self::$useTemporaryTables;
}
protected function getNewTempFile() {
$fileName = tempnam( wfTempDir(), 'MW_PHPUnit_' . get_class( $this ) . '_' );
$this->tmpFiles[] = $fileName;
return $fileName;
}
protected function getNewTempDirectory() {
// Starting of with a temporary /file/.
$fileName = $this->getNewTempFile();
// Converting the temporary /file/ to a /directory/
// The following is not atomic, but at least we now have a single place,
// where temporary directory creation is bundled and can be improved
unlink( $fileName );
$this->assertTrue( wfMkdirParents( $fileName ) );
return $fileName;
}
protected function setUp() {
parent::setUp();
$this->called['setUp'] = true;
$this->phpErrorLevel = intval( ini_get( 'error_reporting' ) );
// Cleaning up temporary files
foreach ( $this->tmpFiles as $fileName ) {
if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
unlink( $fileName );
} elseif ( is_dir( $fileName ) ) {
wfRecursiveRemoveDir( $fileName );
}
}
if ( $this->needsDB() && $this->db ) {
// Clean up open transactions
while ( $this->db->trxLevel() > 0 ) {
$this->db->rollback( __METHOD__, 'flush' );
}
// Check for unsafe queries
if ( $this->db->getType() === 'mysql' ) {
$this->db->query( "SET sql_mode = 'STRICT_ALL_TABLES'" );
}
}
DeferredUpdates::clearPendingUpdates();
ObjectCache::getMainWANInstance()->clearProcessCache();
// XXX: reset maintenance triggers
// Hook into period lag checks which often happen in long-running scripts
$lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
ob_start( 'MediaWikiTestCase::wfResetOutputBuffersBarrier' );
}
protected function addTmpFiles( $files ) {
$this->tmpFiles = array_merge( $this->tmpFiles, (array)$files );
}
protected function tearDown() {
$status = ob_get_status();
if ( isset( $status['name'] ) &&
$status['name'] === 'MediaWikiTestCase::wfResetOutputBuffersBarrier'
) {
ob_end_flush();
}
$this->called['tearDown'] = true;
// Cleaning up temporary files
foreach ( $this->tmpFiles as $fileName ) {
if ( is_file( $fileName ) || ( is_link( $fileName ) ) ) {
unlink( $fileName );
} elseif ( is_dir( $fileName ) ) {
wfRecursiveRemoveDir( $fileName );
}
}
if ( $this->needsDB() && $this->db ) {
// Clean up open transactions
while ( $this->db->trxLevel() > 0 ) {
$this->db->rollback( __METHOD__, 'flush' );
}
if ( $this->db->getType() === 'mysql' ) {
$this->db->query( "SET sql_mode = " . $this->db->addQuotes( $wgSQLMode ) );
}
}
// Restore mw globals
foreach ( $this->mwGlobals as $key => $value ) {
$GLOBALS[$key] = $value;
}
$this->mwGlobals = [];
$this->restoreLoggers();
if ( self::$serviceLocator && MediaWikiServices::getInstance() !== self::$serviceLocator ) {
MediaWikiServices::forceGlobalInstance( self::$serviceLocator );
}
// TODO: move global state into MediaWikiServices
if ( session_id() !== '' ) {
session_write_close();
session_id( '' );
}
MediaWiki\Session\SessionManager::resetCache();
MediaWiki\Auth\AuthManager::resetCache();
$phpErrorLevel = intval( ini_get( 'error_reporting' ) );
if ( $phpErrorLevel !== $this->phpErrorLevel ) {
ini_set( 'error_reporting', $this->phpErrorLevel );
$oldHex = strtoupper( dechex( $this->phpErrorLevel ) );
$newHex = strtoupper( dechex( $phpErrorLevel ) );
$message = "PHP error_reporting setting was left dirty: "
. "was 0x$oldHex before test, 0x$newHex after test!";
$this->fail( $message );
}
parent::tearDown();
}
final public function testMediaWikiTestCaseParentSetupCalled() {
$this->assertArrayHasKey( 'setUp', $this->called,
static::class . '::setUp() must call parent::setUp()'
);
}
protected function setService( $name, $object ) {
// If we did not yet override the service locator, so so now.
if ( MediaWikiServices::getInstance() === self::$serviceLocator ) {
$this->overrideMwServices();
}
MediaWikiServices::getInstance()->disableService( $name );
MediaWikiServices::getInstance()->redefineService(
function () use ( $object ) {
return $object;
}
);
}
protected function setMwGlobals( $pairs, $value = null ) {
if ( is_string( $pairs ) ) {
$pairs = [ $pairs => $value ];
}
$this->stashMwGlobals( array_keys( $pairs ) );
foreach ( $pairs as $key => $value ) {
$GLOBALS[$key] = $value;
}
}
private static function canShallowCopy( $value ) {
if ( is_scalar( $value ) || $value === null ) {
return true;
}
if ( is_array( $value ) ) {
foreach ( $value as $subValue ) {
if ( !is_scalar( $subValue ) && $subValue !== null ) {
return false;
}
}
return true;
}
return false;
}
protected function stashMwGlobals( $globalKeys ) {
if ( is_string( $globalKeys ) ) {
$globalKeys = [ $globalKeys ];
}
foreach ( $globalKeys as $globalKey ) {
// NOTE: make sure we only save the global once or a second call to
// setMwGlobals() on the same global would override the original
// value.
if ( !array_key_exists( $globalKey, $this->mwGlobals ) ) {
if ( !array_key_exists( $globalKey, $GLOBALS ) ) {
throw new Exception( "Global with key {$globalKey} doesn't exist and cant be stashed" );
}
// NOTE: we serialize then unserialize the value in case it is an object
// this stops any objects being passed by reference. We could use clone
// and if is_object but this does account for objects within objects!
if ( self::canShallowCopy( $GLOBALS[$globalKey] ) ) {
$this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
} elseif (
// Many MediaWiki types are safe to clone. These are the
// ones that are most commonly stashed.
$GLOBALS[$globalKey] instanceof Language ||
$GLOBALS[$globalKey] instanceof User ||
$GLOBALS[$globalKey] instanceof FauxRequest
) {
$this->mwGlobals[$globalKey] = clone $GLOBALS[$globalKey];
} else {
try {
$this->mwGlobals[$globalKey] = unserialize( serialize( $GLOBALS[$globalKey] ) );
} catch ( Exception $e ) {
$this->mwGlobals[$globalKey] = $GLOBALS[$globalKey];
}
}
}
}
}
protected function mergeMwGlobalArrayValue( $name, $values ) {
if ( !isset( $GLOBALS[$name] ) ) {
$merged = $values;
} else {
if ( !is_array( $GLOBALS[$name] ) ) {
throw new MWException( "MW global $name is not an array." );
}
// NOTE: do not use array_merge, it screws up for numeric keys.
$merged = $GLOBALS[$name];
foreach ( $values as $k => $v ) {
$merged[$k] = $v;
}
}
$this->setMwGlobals( $name, $merged );
}
protected function overrideMwServices( Config $configOverrides = null, array $services = [] ) {
if ( !$configOverrides ) {
$configOverrides = new HashConfig();
}
$oldInstance = MediaWikiServices::getInstance();
$oldConfigFactory = $oldInstance->getConfigFactory();
$testConfig = self::makeTestConfig( null, $configOverrides );
$newInstance = new MediaWikiServices( $testConfig );
// Load the default wiring from the specified files.
// NOTE: this logic mirrors the logic in MediaWikiServices::newInstance.
$wiringFiles = $testConfig->get( 'ServiceWiringFiles' );
$newInstance->loadWiringFiles( $wiringFiles );
// Provide a traditional hook point to allow extensions to configure services.
Hooks::run( 'MediaWikiServices', [ $newInstance ] );
foreach ( $services as $name => $callback ) {
$newInstance->redefineService( $name, $callback );
}
self::installTestServices(
$oldConfigFactory,
$newInstance
);
MediaWikiServices::forceGlobalInstance( $newInstance );
return $newInstance;
}
public function setUserLang( $lang ) {
RequestContext::getMain()->setLanguage( $lang );
$this->setMwGlobals( 'wgLang', RequestContext::getMain()->getLanguage() );
}
public function setContentLang( $lang ) {
if ( $lang instanceof Language ) {
$langCode = $lang->getCode();
$langObj = $lang;
} else {
$langCode = $lang;
$langObj = Language::factory( $langCode );
}
$this->setMwGlobals( [
'wgLanguageCode' => $langCode,
'wgContLang' => $langObj,
] );
}
protected function setLogger( $channel, LoggerInterface $logger ) {
// TODO: Once loggers are managed by MediaWikiServices, use
// overrideMwServices() to set loggers.
$provider = LoggerFactory::getProvider();
$wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
$singletons = $wrappedProvider->singletons;
if ( $provider instanceof MonologSpi ) {
if ( !isset( $this->loggers[$channel] ) ) {
$this->loggers[$channel] = isset( $singletons['loggers'][$channel] )
? $singletons['loggers'][$channel] : null;
}
$singletons['loggers'][$channel] = $logger;
} elseif ( $provider instanceof LegacySpi ) {
if ( !isset( $this->loggers[$channel] ) ) {
$this->loggers[$channel] = isset( $singletons[$channel] ) ? $singletons[$channel] : null;
}
$singletons[$channel] = $logger;
} else {
throw new LogicException( __METHOD__ . ': setting a logger for ' . get_class( $provider )
. ' is not implemented' );
}
$wrappedProvider->singletons = $singletons;
}
private function restoreLoggers() {
$provider = LoggerFactory::getProvider();
$wrappedProvider = TestingAccessWrapper::newFromObject( $provider );
$singletons = $wrappedProvider->singletons;
foreach ( $this->loggers as $channel => $logger ) {
if ( $provider instanceof MonologSpi ) {
if ( $logger === null ) {
unset( $singletons['loggers'][$channel] );
} else {
$singletons['loggers'][$channel] = $logger;
}
} elseif ( $provider instanceof LegacySpi ) {
if ( $logger === null ) {
unset( $singletons[$channel] );
} else {
$singletons[$channel] = $logger;
}
}
}
$wrappedProvider->singletons = $singletons;
$this->loggers = [];
}
public function dbPrefix() {
return $this->db->getType() == 'oracle' ? self::ORA_DB_PREFIX : self::DB_PREFIX;
}
public function needsDB() {
# if the test says it uses database tables, it needs the database
if ( $this->tablesUsed ) {
return true;
}
# if the test says it belongs to the Database group, it needs the database
$rc = new ReflectionClass( $this );
if ( preg_match( '/@group +Database/im', $rc->getDocComment() ) ) {
return true;
}
return false;
}
protected function insertPage(
$pageName,
$text = 'Sample page for unit test.',
$namespace = null
) {
if ( is_string( $pageName ) ) {
$title = Title::newFromText( $pageName, $namespace );
} else {
$title = $pageName;
}
$user = static::getTestSysop()->getUser();
$comment = __METHOD__ . ': Sample page for unit test.';
// Avoid memory leak...?
// LinkCache::singleton()->clear();
// Maybe. But doing this absolutely breaks $title->isRedirect() when called during unit tests....
$page->doEditContent( ContentHandler::makeContent( $text, $title ), $comment, 0, false, $user );
return [
'title' => $title,
'id' => $page->getId(),
];
}
public function addDBDataOnce() {
}
public function addDBData() {
}
private function addCoreDBData() {
if ( $this->db->getType() == 'oracle' ) {
# Insert 0 user to prevent FK violations
# Anonymous user
if ( !$this->db->selectField( 'user', '1', [ 'user_id' => 0 ] ) ) {
$this->db->insert( 'user', [
'user_id' => 0,
'user_name' => 'Anonymous' ], __METHOD__, [ 'IGNORE' ] );
}
# Insert 0 page to prevent FK violations
# Blank page
if ( !$this->db->selectField( 'page', '1', [ 'page_id' => 0 ] ) ) {
$this->db->insert( 'page', [
'page_id' => 0,
'page_namespace' => 0,
'page_title' => ' ',
'page_restrictions' => null,
'page_is_redirect' => 0,
'page_is_new' => 0,
'page_random' => 0,
'page_touched' => $this->db->timestamp(),
'page_latest' => 0,
'page_len' => 0 ], __METHOD__, [ 'IGNORE' ] );
}
}
User::resetIdByNameCache();
// Make sysop user
$user = static::getTestSysop()->getUser();
// Make 1 page with 1 revision
$page = WikiPage::factory( Title::newFromText( 'UTPage' ) );
if ( $page->getId() == 0 ) {
$page->doEditContent(
new WikitextContent( 'UTContent' ),
'UTPageSummary',
false,
);
// doEditContent() probably started the session via
// User::loadFromSession(). Close it now.
if ( session_id() !== '' ) {
session_write_close();
session_id( '' );
}
}
}
public static function teardownTestDB() {
if ( !self::$dbSetup ) {
return;
}
foreach ( $wgJobClasses as $type => $class ) {
// Delete any jobs under the clone DB (or old prefix in other stores)
JobQueueGroup::singleton()->get( $type )->delete();
}
CloneDatabase::changePrefix( self::$oldTablePrefix );
self::$oldTablePrefix = false;
self::$dbSetup = false;
}
protected static function setupDatabaseWithTestPrefix( Database $db, $prefix ) {
$tablesCloned = self::listTables( $db );
$dbClone = new CloneDatabase( $db, $tablesCloned, $prefix );
$dbClone->useTemporaryTables( self::$useTemporaryTables );
if ( ( $db->getType() == 'oracle' || !self::$useTemporaryTables ) && self::$reuseDB ) {
return false;
} else {
$dbClone->cloneTableStructure();
return true;
}
}
public function setupAllTestDBs() {
self::$oldTablePrefix = $wgDBprefix;
$testPrefix = $this->dbPrefix();
// switch to a temporary clone of the database
self::setupTestDB( $this->db, $testPrefix );
if ( self::isUsingExternalStoreDB() ) {
self::setupExternalStoreTestDBs( $testPrefix );
}
}
public static function setupTestDB( Database $db, $prefix ) {
if ( self::$dbSetup ) {
return;
}
if ( $db->tablePrefix() === $prefix ) {
throw new MWException(
'Cannot run unit tests, the database prefix is already "' . $prefix . '"' );
}
// TODO: the below should be re-written as soon as LBFactory, LoadBalancer,
// and Database no longer use global state.
self::$dbSetup = true;
if ( !self::setupDatabaseWithTestPrefix( $db, $prefix ) ) {
return;
}
// Assuming this isn't needed for External Store database, and not sure if the procedure
// would be available there.
if ( $db->getType() == 'oracle' ) {
$db->query( 'BEGIN FILL_WIKI_INFO; END;' );
}
}
protected static function setupExternalStoreTestDBs( $testPrefix ) {
$connections = self::getExternalStoreDatabaseConnections();
foreach ( $connections as $dbw ) {
// Hack: cloneTableStructure sets $wgDBprefix to the unit test
// prefix,. Even though listTables now uses tablePrefix, that
// itself is populated from $wgDBprefix by default.
// We have to set it back, or we won't find the original 'blobs'
// table to copy.
$dbw->tablePrefix( self::$oldTablePrefix );
self::setupDatabaseWithTestPrefix( $dbw, $testPrefix );
}
}
protected static function getExternalStoreDatabaseConnections() {
$externalStoreDB = ExternalStore::getStoreObject( 'DB' );
$defaultArray = (array) $wgDefaultExternalStore;
$dbws = [];
foreach ( $defaultArray as $url ) {
if ( strpos( $url, 'DB://' ) === 0 ) {
list( $proto, $cluster ) = explode( '://', $url, 2 );
// Avoid getMaster() because setupDatabaseWithTestPrefix()
// requires Database instead of plain DBConnRef/IDatabase
$lb = $externalStoreDB->getLoadBalancer( $cluster );
$dbw = $lb->getConnection( DB_MASTER );
$dbws[] = $dbw;
}
}
return $dbws;
}
protected static function isUsingExternalStoreDB() {
return false;
}
$defaultArray = (array) $wgDefaultExternalStore;
foreach ( $defaultArray as $url ) {
if ( strpos( $url, 'DB://' ) === 0 ) {
return true;
}
}
return false;
}
private function resetDB( $db, $tablesUsed ) {
if ( $db ) {
$userTables = [ 'user', 'user_groups', 'user_properties' ];
$coreDBDataTables = array_merge( $userTables, [ 'page', 'revision' ] );
// If any of the user tables were marked as used, we should clear all of them.
if ( array_intersect( $tablesUsed, $userTables ) ) {
$tablesUsed = array_unique( array_merge( $tablesUsed, $userTables ) );
}
$truncate = in_array( $db->getType(), [ 'oracle', 'mysql' ] );
foreach ( $tablesUsed as $tbl ) {
// TODO: reset interwiki table to its original content.
if ( $tbl == 'interwiki' ) {
continue;
}
if ( $truncate ) {
$db->query( 'TRUNCATE TABLE ' . $db->tableName( $tbl ), __METHOD__ );
} else {
$db->delete( $tbl, '*', __METHOD__ );
}
if ( $tbl === 'page' ) {
// Forget about the pages since they don't
// exist in the DB.
LinkCache::singleton()->clear();
}
}
if ( array_intersect( $tablesUsed, $coreDBDataTables ) ) {
// Re-add core DB data that was deleted
$this->addCoreDBData();
}
}
}
public function __call( $func, $args ) {
static $compatibility = [
'assertEmpty' => 'assertEmpty2', // assertEmpty was added in phpunit 3.7.32
];
if ( isset( $compatibility[$func] ) ) {
return call_user_func_array( [ $this, $compatibility[$func] ], $args );
} else {
throw new MWException( "Called non-existent $func method on "
. get_class( $this ) );
}
}
private function assertEmpty2( $value, $msg ) {
$this->assertTrue( $value == '', $msg );
}
private static function unprefixTable( &$tableName, $ind, $prefix ) {
$tableName = substr( $tableName, strlen( $prefix ) );
}
private static function isNotUnittest( $table ) {
return strpos( $table, 'unittest_' ) !== 0;
}
public static function listTables( Database $db ) {
$prefix = $db->tablePrefix();
$tables = $db->listTables( $prefix, __METHOD__ );
if ( $db->getType() === 'mysql' ) {
static $viewListCache = null;
if ( $viewListCache === null ) {
$viewListCache = $db->listViews( null, __METHOD__ );
}
// T45571: cannot clone VIEWs under MySQL
$tables = array_diff( $tables, $viewListCache );
}
array_walk( $tables, [ __CLASS__, 'unprefixTable' ], $prefix );
// Don't duplicate test tables from the previous fataled run
$tables = array_filter( $tables, [ __CLASS__, 'isNotUnittest' ] );
if ( $db->getType() == 'sqlite' ) {
$tables = array_flip( $tables );
// these are subtables of searchindex and don't need to be duped/dropped separately
unset( $tables['searchindex_content'] );
unset( $tables['searchindex_segdir'] );
unset( $tables['searchindex_segments'] );
$tables = array_flip( $tables );
}
return $tables;
}
protected function checkDbIsSupported() {
if ( !in_array( $this->db->getType(), $this->supportedDBs ) ) {
throw new MWException( $this->db->getType() . " is not currently supported for unit testing." );
}
}
public function getCliArg( $offset ) {
if ( isset( PHPUnitMaintClass::$additionalOptions[$offset] ) ) {
}
}
public function setCliArg( $offset, $value ) {
}
public function hideDeprecated( $function ) {
MediaWiki\suppressWarnings();
wfDeprecated( $function );
MediaWiki\restoreWarnings();
}
protected function assertSelect( $table, $fields, $condition, array $expectedRows ) {
if ( !$this->needsDB() ) {
throw new MWException( 'When testing database state, the test cases\'s needDB()' .
' method should return true. Use @group Database or $this->tablesUsed.' );
}
$db = wfGetDB( DB_SLAVE );
$res = $db->select( $table, $fields, $condition, wfGetCaller(), [ 'ORDER BY' => $fields ] );
$this->assertNotEmpty( $res, "query failed: " . $db->lastError() );
$i = 0;
foreach ( $expectedRows as $expected ) {
$r = $res->fetchRow();
self::stripStringKeys( $r );
$i += 1;
$this->assertNotEmpty( $r, "row #$i missing" );
$this->assertEquals( $expected, $r, "row #$i mismatches" );
}
$r = $res->fetchRow();
self::stripStringKeys( $r );
$this->assertFalse( $r, "found extra row (after #$i)" );
}
protected function arrayWrap( array $elements ) {
return array_map(
function ( $element ) {
return [ $element ];
},
$elements
);
}
protected function assertArrayEquals( array $expected, array $actual,
$ordered = false, $named = false
) {
if ( !$ordered ) {
$this->objectAssociativeSort( $expected );
$this->objectAssociativeSort( $actual );
}
if ( !$named ) {
$expected = array_values( $expected );
$actual = array_values( $actual );
}
call_user_func_array(
[ $this, 'assertEquals' ],
array_merge( [ $expected, $actual ], array_slice( func_get_args(), 4 ) )
);
}
protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
$expected = str_replace( '>', ">\n", $expected );
$actual = str_replace( '>', ">\n", $actual );
$this->assertEquals( $expected, $actual, $msg );
}
protected function objectAssociativeSort( array &$array ) {
uasort(
$array,
function ( $a, $b ) {
return serialize( $a ) > serialize( $b ) ? 1 : -1;
}
);
}
protected static function stripStringKeys( &$r ) {
if ( !is_array( $r ) ) {
return;
}
foreach ( $r as $k => $v ) {
if ( is_string( $k ) ) {
unset( $r[$k] );
}
}
}
protected function assertTypeOrValue( $type, $actual, $value = false, $message = '' ) {
if ( $actual === $value ) {
$this->assertTrue( true, $message );
} else {
$this->assertType( $type, $actual, $message );
}
}
protected function assertType( $type, $actual, $message = '' ) {
if ( class_exists( $type ) || interface_exists( $type ) ) {
$this->assertInstanceOf( $type, $actual, $message );
} else {
$this->assertInternalType( $type, $actual, $message );
}
}
protected function isWikitextNS( $ns ) {
if ( isset( $wgNamespaceContentModels[$ns] ) ) {
}
return true;
}
protected function getDefaultWikitextNS() {
static $wikitextNS = null; // this is not going to change
if ( $wikitextNS !== null ) {
return $wikitextNS;
}
// quickly short out on most common case:
if ( !isset( $wgNamespaceContentModels[NS_MAIN] ) ) {
return NS_MAIN;
}
// NOTE: prefer content namespaces
$namespaces = array_unique( array_merge(
MWNamespace::getContentNamespaces(),
[ NS_MAIN, NS_HELP, NS_PROJECT ], // prefer these
MWNamespace::getValidNamespaces()
) );
$namespaces = array_diff( $namespaces, [
NS_FILE, NS_CATEGORY, NS_MEDIAWIKI, NS_USER // don't mess with magic namespaces
] );
$talk = array_filter( $namespaces, function ( $ns ) {
return MWNamespace::isTalk( $ns );
} );
// prefer non-talk pages
$namespaces = array_diff( $namespaces, $talk );
$namespaces = array_merge( $namespaces, $talk );
// check default content model of each namespace
foreach ( $namespaces as $ns ) {
if ( !isset( $wgNamespaceContentModels[$ns] ) ||
) {
$wikitextNS = $ns;
return $wikitextNS;
}
}
// give up
// @todo Inside a test, we could skip the test as incomplete.
// But frequently, this is used in fixture setup.
throw new MWException( "No namespace defaults to wikitext!" );
}
protected function markTestSkippedIfNoDiff3() {
# This check may also protect against code injection in
# case of broken installations.
MediaWiki\suppressWarnings();
$haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
MediaWiki\restoreWarnings();
if ( !$haveDiff3 ) {
$this->markTestSkipped( "Skip test, since diff3 is not configured" );
}
}
protected function checkPHPExtension( $extName ) {
$loaded = extension_loaded( $extName );
if ( !$loaded ) {
$this->markTestSkipped( "PHP extension '$extName' is not loaded, skipping." );
}
return $loaded;
}
protected function assertValidHtmlSnippet( $html ) {
$html = '<!DOCTYPE html><html><head><title>test</title></head><body>' . $html . '</body></html>';
$this->assertValidHtmlDocument( $html );
}
protected function assertValidHtmlDocument( $html ) {
// Note: we only validate if the tidy PHP extension is available.
// In case wgTidyInternal is false, MWTidy would fall back to the command line version
// of tidy. In that case however, we can not reliably detect whether a failing validation
// is due to malformed HTML, or caused by tidy not being installed as a command line tool.
// That would cause all HTML assertions to fail on a system that has no tidy installed.
if ( !$GLOBALS['wgTidyInternal'] || !MWTidy::isEnabled() ) {
$this->markTestSkipped( 'Tidy extension not installed' );
}
$errorBuffer = '';
MWTidy::checkErrors( $html, $errorBuffer );
$allErrors = preg_split( '/[\r\n]+/', $errorBuffer );
// Filter Tidy warnings which aren't useful for us.
// Tidy eg. often cries about parameters missing which have actually
// been deprecated since HTML4, thus we should not care about them.
$errors = preg_grep(
'/^(.*Warning: (trimming empty|.* lacks ".*?" attribute).*|\s*)$/m',
$allErrors, PREG_GREP_INVERT
);
$this->assertEmpty( $errors, implode( "\n", $errors ) );
}
private static function tagMatch( $matcher, $actual, $isHtml = true ) {
$dom = PHPUnit_Util_XML::load( $actual, $isHtml );
$tags = PHPUnit_Util_XML::findNodes( $dom, $matcher, $isHtml );
return count( $tags ) > 0 && $tags[0] instanceof DOMNode;
}
public static function assertTag( $matcher, $actual, $message = '', $isHtml = true ) {
// trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
self::assertTrue( self::tagMatch( $matcher, $actual, $isHtml ), $message );
}
public static function assertNotTag( $matcher, $actual, $message = '', $isHtml = true ) {
// trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
self::assertFalse( self::tagMatch( $matcher, $actual, $isHtml ), $message );
}
public static function wfResetOutputBuffersBarrier( $buffer ) {
return $buffer;
}
protected function setTemporaryHook( $hookName, $handler ) {
$this->mergeMwGlobalArrayValue( 'wgHooks', [ $hookName => [ $handler ] ] );
}
}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
serialize()
unserialize( $serialized)
$GLOBALS['IP']
$wgDBprefix
Table name prefix.
$wgSQLMode
SQL Mode - default is turning off all modes, including strict, if set.
array $wgDefaultExternalStore
The place to put new revisions, false to put them in the local text table.
$wgDiff3
Path to the GNU diff3 utility.
$wgJobClasses
Maps jobs to their handling classes; extensions can add to this to provide custom jobs.
$wgNamespaceContentModels
Associative array mapping namespace IDs to the name of the content model pages in that namespace shou...
const DB_SLAVE
Definition Defines.php:28
wfTempDir()
Tries to get the system directory for temporary files.
wfRecursiveRemoveDir( $dir)
Remove a directory and all its content.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
if(! $wgDBerrorLogTZ) $wgRequest
Definition Setup.php:664
if( $line===false) $args
Definition cdb.php:64
static changePrefix( $prefix)
Change the table prefix on all open DB connections/.
Factory class to create Config objects.
makeConfig( $name)
Create a given Config using the registered callback for $name.
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
Relational database abstraction object.
Definition Database.php:36
delete( $table, $conds, $fname=__METHOD__)
DELETE query wrapper.
tablePrefix( $prefix=null)
Get/set the table prefix.
Definition Database.php:448
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
query( $sql, $fname=__METHOD__, $tempIgnore=false)
Run an SQL query and return the result.
Definition Database.php:829
tableName( $name, $format='quoted')
Format a table name ready for use in constructing an SQL query.
listViews( $prefix=null, $fname=__METHOD__)
Lists all the VIEWs in the database.
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.
static getStoreObject( $proto, array $params=[])
Get an external store object of the given type, with the given parameters.
WebRequest clone which takes values from a provided array.
static destroySingleton()
Destroy the singleton instance.
Accesses configuration settings from $GLOBALS.
A Config instance which stores all settings as a member variable.
static destroySingletons()
Destroy the singleton instances.
static singleton( $wiki=false)
Internationalisation code.
Definition Language.php:35
MediaWiki exception.
static checkErrors( $text, &$errorStr=null)
Check HTML for errors, used if $wgValidateAllHtml = true.
Definition MWTidy.php:63
static isEnabled()
Definition MWTidy.php:79
static setLBFactoryTriggers(LBFactory $LBFactory)
LoggerFactory service provider that creates LegacyLogger instances.
Definition LegacySpi.php:38
PSR-3 logger instance factory.
LoggerFactory service provider that creates loggers implemented by Monolog.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Provides a fallback sequence for Config objects.
static $additionalOptions
Definition phpunit.php:18
static resetMain()
Resets singleton returned by getMain().
static getMain()
Static methods.
static clear()
Clear the registry.
static getMutableTestUser( $testName, $groups=[])
Get a TestUser object that the caller may modify.
static getImmutableTestUser( $groups=[])
Get a TestUser object that the caller may not modify.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:48
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition WikiPage.php:115
Content object for wiki text pages.
$res
Definition database.txt:21
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
when a variable name is used in a it is silently declared as a new local masking the global
Definition design.txt:95
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
$lbFactory
const NS_HELP
Definition Defines.php:68
const NS_USER
Definition Defines.php:58
const NS_FILE
Definition Defines.php:62
const CACHE_NONE
Definition Defines.php:94
const NS_MAIN
Definition Defines.php:56
const NS_MEDIAWIKI
Definition Defines.php:64
const CACHE_ACCEL
Definition Defines.php:97
const CONTENT_MODEL_WIKITEXT
Definition Defines.php:239
const CACHE_MEMCACHED
Definition Defines.php:96
const CACHE_DB
Definition Defines.php:95
const NS_PROJECT
Definition Defines.php:60
const NS_CATEGORY
Definition Defines.php:70
const EDIT_NEW
Definition Defines.php:146
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition hooks.txt:1049
the array() calling protocol came about after MediaWiki 1.4rc1.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition hooks.txt:249
namespace are movable Hooks may change this value to override the return value of MWNamespace::isMovable(). 'NewDifferenceEngine' do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition hooks.txt:2568
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist & $tables
Definition hooks.txt:1028
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Associative array mapping language codes to prefixed links of the form "language:title". & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition hooks.txt:1937
namespace and then decline to actually register it & $namespaces
Definition hooks.txt:956
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:986
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Definition hooks.txt:2207
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition hooks.txt:1957
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:304
namespace are movable Hooks may change this value to override the return value of MWNamespace::isMovable(). 'NewDifferenceEngine' do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition hooks.txt:2534
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition hooks.txt:925
processing should stop and the error should be shown to the user * false
Definition hooks.txt:189
returning false will NOT prevent logging $e
Definition hooks.txt:2110
$comment
$files
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition injection.txt:25
Interface for configuration instances.
Definition Config.php:28
lastError()
Get a description of the last error.
getType()
Get the type of the DBMS, as it appears in $wgDBtype.
MediaWiki Logger LegacySpi
Definition logger.txt:53
MediaWiki Logger MonologSpi
Definition logger.txt:58
$buffer
const DB_MASTER
Definition defines.php:23
if(!isset( $args[0])) $lang