Merged FileBackend branch. Manually avoiding merging the many prop-only changes SVN...
[lhc/web/wiklou.git] / includes / filerepo / backend / FileBackendGroup.php
1 <?php
2 /**
3 * @file
4 * @ingroup FileBackend
5 */
6
7 /**
8 * Class to handle file backend registration
9 *
10 * @ingroup FileBackend
11 */
12 class FileBackendGroup {
13 protected static $instance = null;
14
15 /** @var Array of (name => ('class' =>, 'config' =>, 'instance' =>)) */
16 protected $backends = array();
17
18 protected function __construct() {}
19 protected function __clone() {}
20
21 public static function singleton() {
22 if ( self::$instance == null ) {
23 self::$instance = new self();
24 }
25 return self::$instance;
26 }
27
28 /**
29 * Destroy the singleton instance, so that a new one will be created next
30 * time singleton() is called.
31 */
32 public static function destroySingleton() {
33 self::$instance = null;
34 }
35
36 /**
37 * Register an array of file backend configurations
38 *
39 * @param $configs Array
40 * @return void
41 * @throws MWException
42 */
43 public function register( array $configs ) {
44 foreach ( $configs as $config ) {
45 if ( !isset( $config['name'] ) ) {
46 throw new MWException( "Cannot register a backend with no name." );
47 }
48 $name = $config['name'];
49 if ( !isset( $config['class'] ) ) {
50 throw new MWException( "Cannot register backend `{$name}` with no class." );
51 }
52 $class = $config['class'];
53
54 unset( $config['class'] ); // backend won't need this
55 $this->backends[$name] = array(
56 'class' => $class,
57 'config' => $config,
58 'instance' => null
59 );
60 }
61 }
62
63 /**
64 * Get the backend object with a given name
65 *
66 * @param $name string
67 * @return FileBackendBase
68 * @throws MWException
69 */
70 public function get( $name ) {
71 if ( !isset( $this->backends[$name] ) ) {
72 throw new MWException( "No backend defined with the name `$name`." );
73 }
74 // Lazy-load the actual backend instance
75 if ( !isset( $this->backends[$name]['instance'] ) ) {
76 $class = $this->backends[$name]['class'];
77 $config = $this->backends[$name]['config'];
78 $this->backends[$name]['instance'] = new $class( $config );
79 }
80 return $this->backends[$name]['instance'];
81 }
82
83 /**
84 * Get an appropriate backend object from a storage path
85 *
86 * @param $storagePath string
87 * @return FileBackendBase|null Backend or null on failure
88 */
89 public function backendFromPath( $storagePath ) {
90 list( $backend, $c, $p ) = FileBackend::splitStoragePath( $storagePath );
91 if ( $backend !== null && isset( $this->backends[$backend] ) ) {
92 return $this->get( $backend );
93 }
94 return null;
95 }
96 }