Skip to content
Snippets Groups Projects
Commit 9cca136c authored by Lucas García's avatar Lucas García
Browse files

feat: refactor as submodule

parent 94cca06d
No related branches found
No related tags found
1 merge request!2Git submodules
This commit is part of merge request !2. Comments created here will be created in the context of that merge request.
<?php
namespace WPCT_HTTP\Abstract;
use WPCT_HTTP\Menu as Menu;
use WPCT_HTTP\Settings as Settings;
abstract class Plugin extends Singleton
{
protected $name;
protected $index;
protected $textdomain;
private $menu;
protected $dependencies = [];
abstract public function init();
abstract public static function activate();
abstract public static function deactivate();
public function __construct()
{
if (empty($this->name) || empty($this->textdomain)) {
throw new \Exception('Bad plugin initialization');
}
$this->index = dirname(__FILE__, 2) . '/' . $this->index;
$this->check_dependencies();
$settings = Settings::get_instance($this->textdomain);
$this->menu = Menu::get_instance($this->name, $settings);
add_action('init', [$this, 'init'], 10);
add_action('init', function () {
$this->load_textdomain();
}, 5);
add_filter('load_textdomain_mofile', function ($mofile, $domain) {
return $this->load_mofile($mofile, $domain);
}, 10, 2);
}
public function get_menu()
{
return $this->menu;
}
public function get_name()
{
return $this->name;
}
public function get_textdomain()
{
return $this->textdomain;
}
public function get_data()
{
return apply_filters('wpct_dc_plugin_data', null, $this->index);
}
private function check_dependencies()
{
add_filter('wpct_dc_dependencies', function ($dependencies) {
foreach ($this->dependencies as $label => $url) {
$dependencies[$label] = $url;
}
return $dependencies;
});
}
private function load_textdomain()
{
$data = $this->get_data();
$domain_path = isset($data['DomainPath']) && !empty($data['DomainPath']) ? $data['DomainPath'] : '/languages';
load_plugin_textdomain(
$this->textdomain,
false,
dirname($this->index) . $domain_path,
);
}
private function load_mofile($mofile, $domain)
{
$data = $this->get_data();
$domain_path = isset($data['DomainPath']) && !empty($data['DomainPath']) ? $data['DomainPath'] : '/languages';
if ($domain === $this->textdomain && strpos($mofile, WP_LANG_DIR . '/plugins/') === false) {
$locale = apply_filters('plugin_locale', determine_locale(), $domain);
$mofile = dirname($this->index) . $domain_path . '/' . $domain . '-' . $locale . '.mo';
}
return $mofile;
}
}
<?php
namespace WPCT_HTTP\Abstract;
class Undefined
{
};
abstract class Settings extends Singleton
{
protected $group_name;
private $_defaults = [];
abstract public function register();
public function __construct($textdomain)
{
$this->group_name = $textdomain;
}
public function get_name()
{
return $this->group_name;
}
public function register_setting($name, $default = [])
{
$default = $this->get_default($name, $default);
register_setting(
$this->group_name,
$name,
[
'type' => 'array',
'show_in_rest' => false,
'default' => $default,
],
);
add_settings_section(
$name . '_section',
__($name . '--title', $this->group_name),
function () use ($name) {
$title = __($name . '--description', $this->group_name);
echo "<p>{$title}</p>";
},
$this->group_name,
);
$this->_defaults[$name] = $default;
}
public function register_field($field_name, $setting_name)
{
$field_id = $setting_name . '__' . $field_name;
add_settings_field(
$field_name,
__($field_id . '--label', $this->group_name),
function () use ($setting_name, $field_name) {
echo $this->field_render($setting_name, $field_name);
},
$this->group_name,
$setting_name . '_section',
[
'class' => $field_id,
]
);
}
public function field_render()
{
$args = func_get_args();
$setting = $args[0];
$field = $args[1];
if (count($args) >= 3) {
$value = $args[2];
} else {
$value = new Undefined();
}
return $this->_field_render($setting, $field, $value);
}
private function _field_render($setting, $field, $value)
{
$is_root = false;
if ($value instanceof Undefined) {
$value = $this->option_getter($setting, $field);
$is_root = true;
}
if (!is_array($value)) {
return $this->input_render($setting, $field, $value);
} else {
$fieldset = $this->fieldset_render($setting, $field, $value);
if ($is_root) {
$fieldset = $this->control_style($setting, $field)
. $fieldset . $this->control_render($setting, $field);
}
return $fieldset;
}
}
public function input_render($setting, $field, $value)
{
$default_value = $this->get_default($setting);
$keys = explode('][', $field);
for ($i = 0; $i < count($keys); $i++) {
$default_value = isset($default_value[$keys[$i]]) ? $default_value[$keys[$i]] : $default_value[0];
}
$is_bool = is_bool($default_value);
if ($is_bool) {
$is_bool = true;
$value = 'on' === $value;
}
if ($is_bool) {
return "<input type='checkbox' name='{$setting}[$field]' " . ($value ? 'checked' : '') . " />";
} else {
return "<input type='text' name='{$setting}[{$field}]' value='{$value}' />";
}
}
public function fieldset_render($setting, $field, $data)
{
$table_id = $setting . '__' . str_replace('][', '_', $field);
$fieldset = "<table id='{$table_id}'>";
$is_list = is_list($data);
foreach (array_keys($data) as $key) {
$fieldset .= '<tr>';
if (!$is_list) {
$fieldset .= "<th>{$key}</th>";
}
$_field = $field . '][' . $key;
$fieldset .= "<td>{$this->field_render($setting, $_field, $data[$key])}</td>";
$fieldset .= '</tr>';
}
$fieldset .= '</table>';
return $fieldset;
}
public function control_render($setting, $field)
{
$defaults = $this->get_default($setting);
ob_start();
?>
<div class="<?= $setting; ?>__<?= $field ?>--controls">
<button class="button button-primary" data-action="add">Add</button>
<button class="button button-secondary" data-action="remove">Remove</button>
</div>
<?php include 'fieldset-control-js.php' ?>
<?php
return ob_get_clean();
}
public function control_style($setting, $field)
{
return "<style>#{$setting}__{$field} td td,#{$setting}__{$field} td th{padding:0}#{$setting}__{$field} table table{margin-bottom:1rem}</style>";
}
public function option_getter($setting, $option)
{
$setting = get_option($setting) ? get_option($setting) : [];
if (!key_exists($option, $setting)) {
return null;
}
return $setting[$option];
}
public function get_default($setting_name, $default = [])
{
$default = isset($this->_defaults[$setting_name]) ? $this->_defaults[$setting_name] : $default;
return apply_filters($setting_name . '_default', $default);
}
}
function is_list($arr)
{
if (!is_array($arr)) {
return false;
}
if (sizeof($arr) === 0) {
return true;
}
return array_keys($arr) === range(0, count($arr) - 1);
}
<?php
namespace WPCT_HTTP\Abstract;
abstract class Singleton
{
private static $_instances = [];
protected function __construct()
{
}
protected function __clone()
{
}
public function __wakeup()
{
throw new Exception('Cannot unserialize a singleton.');
}
public static function get_instance()
{
$args = func_get_args();
$cls = static::class;
if (!isset(self::$_instances[$cls])) {
self::$_instances[$cls] = new static(...$args);
}
return self::$_instances[$cls];
}
}
......@@ -2,6 +2,8 @@
namespace WPCT_HTTP;
use Exception;
require_once 'class-multipart.php';
class Http_Client
......@@ -145,7 +147,7 @@ class Http_Client
{
$setting = get_option($setting);
if (!$setting) {
throw new \Exception('Wpct Http Bridge: You should configure base url on plugin settings');
throw new Exception('Wpct Http Bridge: You should configure base url on plugin settings');
}
return isset($setting[$option]) ? $setting[$option] : null;
......
......@@ -2,7 +2,7 @@
namespace WPCT_HTTP;
class Menu extends Abstract\Singleton
class Menu extends \WPCT_ABSTRACT\Singleton
{
private $name;
private $settings;
......
......@@ -2,7 +2,7 @@
namespace WPCT_HTTP;
class Settings extends Abstract\Settings
class Settings extends \WPCT_ABSTRACT\Settings
{
public function register()
{
......
<?php
// Script to be buffered from settings class
$default_value = $defaults[$field][0];
$is_array = is_array($default_value);
$table_id = $setting . '__' . str_replace('][', '_', $field);
?>
<script>
(function() {
function renderRowContent(index) {
<?php if ($is_array) : ?>
return `<table id="<?= $table_id ?>_${index}">
<?php foreach (array_keys($default_value) as $key) : ?>
<tr>
<th><?= $field ?></th>
<td><?= $this->input_render($setting, $field . '][${index}][' . $key, $default_value[$key]); ?></td>
</tr>
<?php endforeach; ?>
</table>`;
<?php else : ?>
return `<?= $this->input_render($setting, $field . '][${index}', $default_value); ?>`;
<?php endif; ?>
}
function addItem(ev) {
ev.preventDefault();
const table = document.getElementById("<?= $table_id ?>")
.children[0];
const tr = document.createElement("tr");
tr.innerHTML =
"<td>" + renderRowContent(table.children.length) + "</td>";
table.appendChild(tr);
}
function removeItem(ev) {
ev.preventDefault();
const table = document.getElementById("<?= $table_id ?>")
.children[0];
const rows = table.children;
table.removeChild(rows[rows.length - 1]);
}
const buttons = document.currentScript.previousElementSibling.querySelectorAll("button");
buttons.forEach((btn) => {
const callback = btn.dataset.action === "add" ? addItem : removeItem;
btn.addEventListener("click", callback);
});
})();
</script>
Subproject commit cffde51f8c0b32b5ae89ff18091f78d53e45d1e6
......@@ -19,99 +19,88 @@ if (!defined('ABSPATH')) {
exit;
}
if (!defined('WPCT_HTTP_AUTH_SECRET')) {
define('WPCT_HTTP_AUTH_SECRET', getenv('WPCT_HTTP_AUTH_SECRET') ? getenv('WPCT_HTTP_AUTH_SECRET') : '123456789');
}
if (!class_exists('Wpct_Http_Bridge')) :
// JWT Authentication config
define('JWT_AUTH_SECRET_KEY', WPCT_HTTP_AUTH_SECRET);
define('JWT_AUTH_CORS_ENABLE', true);
require_once 'abstract/class-singleton.php';
require_once 'abstract/class-plugin.php';
require_once 'abstract/class-settings.php';
require_once 'includes/class-menu.php';
require_once 'includes/class-settings.php';
require_once "includes/class-http-client.php";
class Wpct_Http_Bridge extends Abstract\Plugin
{
protected $name = 'Wpct Http Bridge';
protected $index = 'wpct-http-bridge.php';
protected $textdomain = 'wpct-http-bridge';
protected $dependencies = [
'jwt-authentication-for-wp-rest-api/jwt-auth.php' => [
'name' => 'JWT Authentication for WP-API',
'url' => 'https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/',
'download' => 'https://downloads.wordpress.org/plugin/jwt-authentication-for-wp-rest-api.1.3.4.zip',
],
'wpct-i18n/wpct-i18n.php' => [
'name' => 'Wpct i18n',
'url' => 'https://git.coopdevs.org/codeccoop/wp/plugins/wpct-i18n/',
'download' => 'https://git.coopdevs.org/codeccoop/wp/plugins/wpct-i18n/-/releases/permalink/latest/downloads/plugins/wpct-i18n.zip'
],
];
public function __construct()
{
parent::__construct();
if (!defined('WPCT_HTTP_AUTH_SECRET')) {
define('WPCT_HTTP_AUTH_SECRET', getenv('WPCT_HTTP_AUTH_SECRET') ? getenv('WPCT_HTTP_AUTH_SECRET') : '123456789');
}
add_filter('plugin_action_links', function ($links, $file) {
if ($file !== plugin_basename(__FILE__)) {
return $links;
}
require_once 'abstracts/class-singleton.php';
require_once 'abstracts/class-plugin.php';
require_once 'abstracts/class-settings.php';
$url = admin_url('options-general.php?page=wpct-http-bridge');
$label = __('Settings');
$link = "<a href='{$url}'>{$label}</a>";
array_unshift($links, $link);
return $links;
}, 5, 2);
}
require_once 'includes/class-menu.php';
require_once 'includes/class-settings.php';
require_once 'includes/class-http-client.php';
public static function activate()
class Wpct_Http_Bridge extends \WPCT_ABSTRACT\Plugin
{
$user = get_user_by('login', 'wpct_http_user');
if ($user) {
return;
protected $name = 'Wpct Http Bridge';
protected $textdomain = 'wpct-http-bridge';
public function __construct()
{
parent::__construct();
add_filter('plugin_action_links', function ($links, $file) {
if ($file !== plugin_basename(__FILE__)) {
return $links;
}
$url = admin_url('options-general.php?page=wpct-http-bridge');
$label = __('Settings');
$link = "<a href='{$url}'>{$label}</a>";
array_unshift($links, $link);
return $links;
}, 5, 2);
new REST_Controller();
}
$site_url = parse_url(get_site_url());
$user_id = wp_insert_user([
'user_nicename' => 'Wpct Http User',
'user_login' => 'wpct_http_user',
'user_pass' => 'wpct_http_pass',
'user_email' => 'wpct_http_user@' . $site_url['host'],
'role' => 'editor',
]);
if (is_wp_error($user_id)) {
throw new Exception($user_id->get_error_message());
public static function activate()
{
$user = get_user_by('login', 'wpct_http_user');
if ($user) {
return;
}
$site_url = parse_url(get_site_url());
$user_id = wp_insert_user([
'user_nicename' => 'Wpct Http User',
'user_login' => 'wpct_http_user',
'user_pass' => 'wpct_http_pass',
'user_email' => 'wpct_http_user@' . $site_url['host'],
'role' => 'editor',
]);
if (is_wp_error($user_id)) {
throw new Exception($user_id->get_error_message());
}
}
}
public static function deactivate()
{
$user = get_user_by('login', 'wpct_http_user');
if ($user) {
wp_delete_user($user->ID);
public static function deactivate()
{
$user = get_user_by('login', 'wpct_http_user');
if ($user) {
wp_delete_user($user->ID);
}
}
}
public function init()
{
public function init()
{
}
}
}
register_deactivation_hook(__FILE__, function () {
Wpct_Http_Bridge::deactivate();
});
register_deactivation_hook(__FILE__, function () {
Wpct_Http_Bridge::deactivate();
});
register_activation_hook(__FILE__, function () {
Wpct_Http_Bridge::activate();
});
register_activation_hook(__FILE__, function () {
Wpct_Http_Bridge::activate();
});
add_action('plugins_loaded', function () {
$plugin = Wpct_Http_Bridge::get_instance();
}, 10);
add_action('plugins_loaded', function () {
$plugin = Wpct_Http_Bridge::get_instance();
}, 10);
endif;
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment