WordPress 4.4
[autoinstalls/wordpress.git] / wp-includes / class-wp-widget-factory.php
1 <?php
2 /**
3  * Widget API: WP_Widget_Factory class
4  *
5  * @package WordPress
6  * @subpackage Widgets
7  * @since 4.4.0
8  */
9
10 /**
11  * Singleton that registers and instantiates WP_Widget classes.
12  *
13  * @since 2.8.0
14  * @since 4.4.0 Moved to its own file from wp-includes/widgets.php
15  */
16 class WP_Widget_Factory {
17         public $widgets = array();
18
19         /**
20          * PHP5 constructor.
21          */
22         public function __construct() {
23                 add_action( 'widgets_init', array( $this, '_register_widgets' ), 100 );
24         }
25
26         /**
27          * PHP4 constructor.
28          */
29         public function WP_Widget_Factory() {
30                 _deprecated_constructor( 'WP_Widget_Factory', '4.2.0' );
31                 self::__construct();
32         }
33
34         /**
35          * Register a widget subclass.
36          *
37          * @since 2.8.0
38          * @access public
39          *
40          * @param string $widget_class The name of a {@see WP_Widget} subclass.
41          */
42         public function register( $widget_class ) {
43                 $this->widgets[$widget_class] = new $widget_class();
44         }
45
46         /**
47          * Un-register a widget subclass.
48          *
49          * @since 2.8.0
50          * @access public
51          *
52          * @param string $widget_class The name of a {@see WP_Widget} subclass.
53          */
54         public function unregister( $widget_class ) {
55                 unset( $this->widgets[ $widget_class ] );
56         }
57
58         /**
59          * Utility method for adding widgets to the registered widgets global.
60          *
61          * @since 2.8.0
62          * @access public
63          *
64          * @global array $wp_registered_widgets
65          */
66         public function _register_widgets() {
67                 global $wp_registered_widgets;
68                 $keys = array_keys($this->widgets);
69                 $registered = array_keys($wp_registered_widgets);
70                 $registered = array_map('_get_widget_id_base', $registered);
71
72                 foreach ( $keys as $key ) {
73                         // don't register new widget if old widget with the same id is already registered
74                         if ( in_array($this->widgets[$key]->id_base, $registered, true) ) {
75                                 unset($this->widgets[$key]);
76                                 continue;
77                         }
78
79                         $this->widgets[$key]->_register();
80                 }
81         }
82 }