Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

REST APIを叩くコマンドラインユーティリティを追加 #6

Merged
merged 2 commits into from
Jan 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions lib/WCTokyo/WpCheckin/Bootstrap.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace WCTokyo\WpCheckin;


use WCTokyo\WpCheckin\Pattern\SingletonPattern;
use WCTokyo\WpCheckin\Screen\Setting;

/**
* Bootstrap for plugin.
*/
class Bootstrap extends SingletonPattern {

/**
* {@inheritDoc}
*/
protected function init() {
Setting::get_instance();
if ( defined( 'WP_CLI' ) && WP_CLI ) {
\WP_CLI::add_command( 'checkin', Command::class );
}
}
}
68 changes: 68 additions & 0 deletions lib/WCTokyo/WpCheckin/Command.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

namespace WCTokyo\WpCheckin;

use cli\Table;
use WCTokyo\WpCheckin\Utilities\Request;

/**
* CLI utilities for wp-checkin
*
*/
class Command extends \WP_CLI_Command {

use Request;

/**
* Check if credential is valid.
*
* @subcommand is-valid
* @return void
*/
public function is_valid() {
$me = $this->rest_request( '/wp/v2/users/me', 'GET', [
'context' => 'edit',
] );
$table = new Table();
$table->setHeaders( [ 'Property', 'Value' ] );
foreach ( $me as $key => $value ) {
if ( 0 === strpos( $key, '_' ) ) {
continue;
}
if ( empty( $value ) ) {
$value = 'EMPTY';
} elseif ( is_array( $value ) ) {
$value = 'ARRAY';
}
$table->addRow( [ $key, $value ] );
}
$table->display();
\WP_CLI::success( __( 'ユーザー情報を取得しました。', 'wp-checkin' ) );
}

/**
* Display API.
*
* @return void
*/
public function namespaces() {
$response = $this->rest_request( '/' );
foreach ( $response['namespaces'] as $namespace ) {
\WP_CLI::line( sprintf( '%s/wp-json/%s', trailingslashit( get_option( 'wordcamp_site_url' ) ), $namespace ) );
}
\WP_CLI::line( '' );
// translators: %d is number of namespaces.
\WP_CLI::success( sprintf( __( '%dの名前空間があります。', 'wp-checkin' ), count( $response['namespaces'] ) ) );
}

/**
* {@see Request::rest_request()}
*/
private function request( $path, $method = 'GET', $data = [] ) {
$response = $this->rest_request( $path, $method, $data );
if ( is_wp_error( $response ) ) {
\WP_CLI::error( $response->get_error_message() );
}
return $response;
}
}
44 changes: 44 additions & 0 deletions lib/WCTokyo/WpCheckin/Pattern/SingletonPattern.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace WCTokyo\WpCheckin\Pattern;


/**
* Singleton pattern.
*/
abstract class SingletonPattern {

/**
* @var static[] Instance store.
*/
private static $instances = [];

/**
* Constructor.
*/
final protected function __construct() {
$this->init();
}

/**
* Executed in constructor.
*
* @return void
*/
protected function init() {
// Do something here.
}

/**
* Return instance.
*
* @return static
*/
public static function get_instance() {
$class_name = get_called_class();
if ( ! isset( self::$instances[ $class_name ] ) ) {
self::$instances[ $class_name ] = new $class_name();
}
return self::$instances[ $class_name ];
}
}
49 changes: 49 additions & 0 deletions lib/WCTokyo/WpCheckin/Screen/Setting.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

namespace WCTokyo\WpCheckin\Screen;


use WCTokyo\WpCheckin\Pattern\SingletonPattern;

/**
* Create setting screen.
*/
class Setting extends SingletonPattern {

/**
* {@inheritDoc}
*/
protected function init() {
add_action( 'admin_init', [ $this, 'register_option' ] );
}

/**
* Register option screen.
*
* @return void
*/
public function register_option() {
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
return;
}
add_settings_section(
'wp_checkin_settings',
__( 'WordCamp チェックイン設定', 'wp-checkin' ),
function() {
printf( '<p>%s</p>', esc_html__( 'WordCampのチェックインシステムに必要な設定を行います。', 'wp-checkin' ) );
},
'general'
);
foreach ( [
[ 'wordcamp_site_url', __( 'WordCampサイトのURL', 'wp-checkin' ), 'url' ],
[ 'wordcamp_user_login', __( 'ユーザー名', 'wp-checkin' ), 'text' ],
[ 'application_password', __( 'アプリケーションパスワード', 'wp-checkin' ), 'text' ],
] as list( $option_name, $label, $type ) ) {
add_settings_field( $option_name, $label, function() use ( $option_name, $type ) {
$value = get_option( $option_name );
printf( '<input type="%s" name="%s" value="%s" class="regular-text">', esc_attr( $type ), esc_attr( $option_name ), esc_attr( $value ) );
}, 'general', 'wp_checkin_settings' );
register_setting( 'general', $option_name );
}
}
}
64 changes: 64 additions & 0 deletions lib/WCTokyo/WpCheckin/Utilities/Request.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

namespace WCTokyo\WpCheckin\Utilities;


/**
* Request REST API to WordCamp site.
*/
trait Request {

/**
* Send Request to REST API.
*
* @param string $path Request path.
* @param string $method Request method[ 'GET', 'POST', 'PUT', 'DELETE', 'HEAD' ].
* @param array $data Query param for GET, body for POST.
*
* @return array|\WP_Error
*/
protected function rest_request( $path, $method = 'GET', $data = [] ) {
$method = strtoupper( $method );
if ( ! in_array( $method, [ 'GET', 'POST', 'PUT', 'DELETE', 'HEAD' ], true ) ) {
return new \WP_Error( 'invalid_method', __( 'メソッドが無効です。', 'wp-checkin' ), [
'status' => 400,
] );
}
$url = get_option( 'wordcamp_site_url' );
$user = get_option( 'wordcamp_user_login' );
$pass = get_option( 'application_password' );
if ( ! $url || ! $user || ! $pass ) {
return new \WP_Error( 'invalid_credentials', __( '認証情報が設定されていません。', 'wp-checkin' ), [
'status' => 400,
] );
}
$endpoint = trailingslashit( $url ) . 'wp-json/' . ltrim( $path, '/' );
$args = [
'method' => $method,
'timeout' => (int) apply_filters( 'wp_checkin_timeout', 30, $path, $method, $data ),
'headers' => [
'Authorization' => 'Basic ' . base64_encode( $user . ':' . $pass ),
'Content-Type' => 'application/json',
],
];
switch ( $method ) {
case 'POST':
$args['body'] = wp_json_encode( $data );
break;
default:
$endpoint = add_query_arg( $data, $endpoint );
break;
}
$response = wp_remote_request( $endpoint, $args );
if ( is_wp_error( $response ) ) {
return $response;
}
switch ( $method ) {
case 'HEAD':
return wp_remote_retrieve_headers( $response );
default:
return json_decode( $response['body'], true );
}

}
}
2 changes: 1 addition & 1 deletion wp-checkin.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,5 @@ function wp_checkin_init() {
// Load composer if exists.
require_once __DIR__ . '/vendor/autoload.php';
// Bootstrap plugins.

\WCTokyo\WpCheckin\Bootstrap::get_instance();
}