summaryrefslogtreecommitdiff
blob: 92914350ac6113f5999a625b40b2555aec512dd2 (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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<?php
/**
 * Plugin connection management class.
 *
 * @package automattic/jetpack-connection
 */

namespace Automattic\Jetpack\Connection;

/**
 * Plugin connection management class.
 * The class represents a single plugin that uses Jetpack connection.
 * Its functionality has been pretty simplistic so far: add to the storage (`Plugin_Storage`), remove it from there,
 * and determine whether it's the last active connection. As the component grows, there'll be more functionality added.
 */
class Plugin {

	/**
	 * List of the keys allowed as arguments
	 *
	 * @var array
	 */
	private $arguments_whitelist = array(
		'url_info',
	);

	/**
	 * Plugin slug.
	 *
	 * @var string
	 */
	private $slug;

	/**
	 * Initialize the plugin manager.
	 *
	 * @param string $slug Plugin slug.
	 */
	public function __construct( $slug ) {
		$this->slug = $slug;
	}

	/**
	 * Get the plugin slug.
	 *
	 * @return string
	 */
	public function get_slug() {
		return $this->slug;
	}

	/**
	 * Add the plugin connection info into Jetpack.
	 *
	 * @param string $name Plugin name, required.
	 * @param array  $args Plugin arguments, optional.
	 *
	 * @return $this
	 * @see $this->arguments_whitelist
	 */
	public function add( $name, array $args = array() ) {
		$args = compact( 'name' ) + array_intersect_key( $args, array_flip( $this->arguments_whitelist ) );

		Plugin_Storage::upsert( $this->slug, $args );

		return $this;
	}

	/**
	 * Remove the plugin connection info from Jetpack.
	 *
	 * @return $this
	 */
	public function remove() {
		Plugin_Storage::delete( $this->slug );

		return $this;
	}

	/**
	 * Determine if this plugin connection is the only one active at the moment, if any.
	 *
	 * @return bool
	 */
	public function is_only() {
		$plugins = Plugin_Storage::get_all( true );

		return ! $plugins || ( array_key_exists( $this->slug, $plugins ) && 1 === count( $plugins ) );
	}

	/**
	 * Add the plugin to the set of disconnected ones.
	 *
	 * @return bool
	 */
	public function disable() {
		return Plugin_Storage::disable_plugin( $this->slug );
	}

	/**
	 * Remove the plugin from the set of disconnected ones.
	 *
	 * @return bool
	 */
	public function enable() {
		return Plugin_Storage::enable_plugin( $this->slug );
	}

	/**
	 * Whether this plugin is allowed to use the connection.
	 *
	 * @return bool
	 */
	public function is_enabled() {
		return ! in_array( $this->slug, Plugin_Storage::get_all_disabled_plugins(), true );
	}

}