Merge pull request #1689 from mailpoet/wp-functions

Encapsulating WP calls
This commit is contained in:
wxa
2018-12-27 11:05:08 +03:00
committed by GitHub
23 changed files with 146 additions and 97 deletions

View File

@ -36,6 +36,11 @@ class Newsletters extends APIEndpoint {
public $permissions = array( public $permissions = array(
'global' => AccessControl::PERMISSION_MANAGE_EMAILS 'global' => AccessControl::PERMISSION_MANAGE_EMAILS
); );
private $wp;
function __construct() {
$this->wp = new WPFunctions;
}
function __construct( function __construct(
Listing\BulkActionController $bulk_action, Listing\BulkActionController $bulk_action,
@ -198,7 +203,7 @@ class Newsletters extends APIEndpoint {
$queue = $newsletter->queue()->findOne(); $queue = $newsletter->queue()->findOne();
if($queue) { if($queue) {
$queue->task() $queue->task()
->whereLte('scheduled_at', Carbon::createFromTimestamp(WPFunctions::currentTime('timestamp'))) ->whereLte('scheduled_at', Carbon::createFromTimestamp($this->wp->currentTime('timestamp')))
->where('status', SendingQueue::STATUS_SCHEDULED) ->where('status', SendingQueue::STATUS_SCHEDULED)
->findResultSet() ->findResultSet()
->set('scheduled_at', $next_run_date) ->set('scheduled_at', $next_run_date)
@ -443,7 +448,7 @@ class Newsletters extends APIEndpoint {
'mta_log' => Setting::getValue('mta_log'), 'mta_log' => Setting::getValue('mta_log'),
'mta_method' => Setting::getValue('mta.method'), 'mta_method' => Setting::getValue('mta.method'),
'cron_accessible' => CronHelper::isDaemonAccessible(), 'cron_accessible' => CronHelper::isDaemonAccessible(),
'current_time' => WPFunctions::currentTime('mysql') 'current_time' => $this->wp->currentTime('mysql')
)); ));
} }

View File

@ -39,10 +39,12 @@ class Menu {
public $renderer; public $renderer;
private $access_control; private $access_control;
private $subscribers_over_limit; private $subscribers_over_limit;
private $wp;
function __construct($renderer, AccessControl $access_control) { function __construct($renderer, AccessControl $access_control) {
$this->renderer = $renderer; $this->renderer = $renderer;
$this->access_control = $access_control; $this->access_control = $access_control;
$this->wp = new WPFunctions;
} }
function init() { function init() {
@ -373,7 +375,7 @@ class Menu {
$data['is_old_user'] = false; $data['is_old_user'] = false;
if(!empty($data['settings']['installed_at'])) { if(!empty($data['settings']['installed_at'])) {
$installed_at = Carbon::createFromTimestamp(strtotime($data['settings']['installed_at'])); $installed_at = Carbon::createFromTimestamp(strtotime($data['settings']['installed_at']));
$current_time = Carbon::createFromTimestamp(WPFunctions::currentTime('timestamp')); $current_time = Carbon::createFromTimestamp($this->wp->currentTime('timestamp'));
$data['is_new_user'] = $current_time->diffInDays($installed_at) <= 30; $data['is_new_user'] = $current_time->diffInDays($installed_at) <= 30;
$data['is_old_user'] = $current_time->diffInMonths($installed_at) >= 6; $data['is_old_user'] = $current_time->diffInMonths($installed_at) >= 6;
$data['stop_call_for_rating'] = isset($data['settings']['stop_call_for_rating']) ? $data['settings']['stop_call_for_rating'] : false; $data['stop_call_for_rating'] = isset($data['settings']['stop_call_for_rating']) ? $data['settings']['stop_call_for_rating'] : false;
@ -826,7 +828,7 @@ class Menu {
return true; return true;
} }
$installed_at = Carbon::createFromTimestamp(strtotime($installed_at)); $installed_at = Carbon::createFromTimestamp(strtotime($installed_at));
$current_time = Carbon::createFromTimestamp(WPFunctions::currentTime('timestamp')); $current_time = Carbon::createFromTimestamp($this->wp->currentTime('timestamp'));
return $current_time->diffInDays($installed_at) <= 30; return $current_time->diffInDays($installed_at) <= 30;
} }
} }

View File

@ -82,7 +82,8 @@ class CronHelper {
); );
$result = self::queryCronUrl($url); $result = self::queryCronUrl($url);
if(is_wp_error($result)) return $result->get_error_message(); if(is_wp_error($result)) return $result->get_error_message();
$response = WPFunctions::wpRemoteRetrieveBody($result); $wp = new WPFunctions();
$response = $wp->wpRemoteRetrieveBody($result);
$response = substr(trim($response), -strlen(DaemonHttpRunner::PING_SUCCESS_RESPONSE)) === DaemonHttpRunner::PING_SUCCESS_RESPONSE ? $response = substr(trim($response), -strlen(DaemonHttpRunner::PING_SUCCESS_RESPONSE)) === DaemonHttpRunner::PING_SUCCESS_RESPONSE ?
DaemonHttpRunner::PING_SUCCESS_RESPONSE : DaemonHttpRunner::PING_SUCCESS_RESPONSE :
$response; $response;
@ -104,7 +105,8 @@ class CronHelper {
$daemon['run_accessed_at'] = time(); $daemon['run_accessed_at'] = time();
self::saveDaemon($daemon); self::saveDaemon($daemon);
$result = self::queryCronUrl($url); $result = self::queryCronUrl($url);
return WPFunctions::wpRemoteRetrieveBody($result); $wp = new WPFunctions();
return $wp->wpRemoteRetrieveBody($result);
} }
/** /**
@ -127,7 +129,7 @@ class CronHelper {
return null; return null;
} }
static function queryCronUrl($url) { static function queryCronUrl($url, $wp = null) {
$args = WPHooks::applyFilters( $args = WPHooks::applyFilters(
'mailpoet_cron_request_args', 'mailpoet_cron_request_args',
array( array(
@ -137,7 +139,10 @@ class CronHelper {
'user-agent' => 'MailPoet Cron' 'user-agent' => 'MailPoet Cron'
) )
); );
return WPFunctions::wpRemotePost($url, $args); if(is_null($wp)) {
$wp = new WPFunctions();
}
return $wp->wpRemotePost($url, $args);
} }
static function getCronUrl($action, $data = false) { static function getCronUrl($action, $data = false) {

View File

@ -19,6 +19,7 @@ if(!defined('ABSPATH')) exit;
class Scheduler { class Scheduler {
public $timer; public $timer;
private $wp;
const UNCONFIRMED_SUBSCRIBER_RESCHEDULE_TIMEOUT = 5; const UNCONFIRMED_SUBSCRIBER_RESCHEDULE_TIMEOUT = 5;
const TASK_BATCH_SIZE = 5; const TASK_BATCH_SIZE = 5;
@ -26,6 +27,7 @@ class Scheduler {
$this->timer = ($timer) ? $timer : microtime(true); $this->timer = ($timer) ? $timer : microtime(true);
// abort if execution limit is reached // abort if execution limit is reached
CronHelper::enforceExecutionLimit($this->timer); CronHelper::enforceExecutionLimit($this->timer);
$this->wp = new WPFunctions();
} }
function process() { function process() {
@ -172,7 +174,7 @@ class Scheduler {
// check if subscriber is confirmed (subscribed) // check if subscriber is confirmed (subscribed)
if($subscriber->status !== Subscriber::STATUS_SUBSCRIBED) { if($subscriber->status !== Subscriber::STATUS_SUBSCRIBED) {
// reschedule delivery in 5 minutes // reschedule delivery in 5 minutes
$scheduled_at = Carbon::createFromTimestamp(WPFunctions::currentTime('timestamp')); $scheduled_at = Carbon::createFromTimestamp($this->wp->currentTime('timestamp'));
$queue->scheduled_at = $scheduled_at->addMinutes( $queue->scheduled_at = $scheduled_at->addMinutes(
self::UNCONFIRMED_SUBSCRIBER_RESCHEDULE_TIMEOUT self::UNCONFIRMED_SUBSCRIBER_RESCHEDULE_TIMEOUT
); );

View File

@ -241,8 +241,11 @@ class Migration extends SimpleWorker {
return true; return true;
} }
static function getNextRunDate() { static function getNextRunDate($wp = null) {
if(is_null($wp)) {
$wp = new WPFunctions();
}
// run migration immediately // run migration immediately
return Carbon::createFromTimestamp(WPFunctions::currentTime('timestamp')); return Carbon::createFromTimestamp($wp->currentTime('timestamp'));
} }
} }

View File

@ -11,7 +11,7 @@ if(!defined('ABSPATH')) exit;
abstract class SimpleWorker { abstract class SimpleWorker {
public $timer; public $timer;
private $wp;
const TASK_TYPE = null; const TASK_TYPE = null;
const TASK_BATCH_SIZE = 5; const TASK_BATCH_SIZE = 5;
@ -22,6 +22,7 @@ abstract class SimpleWorker {
$this->timer = ($timer) ? $timer : microtime(true); $this->timer = ($timer) ? $timer : microtime(true);
// abort if execution limit is reached // abort if execution limit is reached
CronHelper::enforceExecutionLimit($this->timer); CronHelper::enforceExecutionLimit($this->timer);
$this->wp = new WPFunctions();
} }
function checkProcessingRequirements() { function checkProcessingRequirements() {
@ -100,19 +101,20 @@ abstract class SimpleWorker {
} }
function complete(ScheduledTask $task) { function complete(ScheduledTask $task) {
$task->processed_at = WPFunctions::currentTime('mysql'); $task->processed_at = $this->wp->currentTime('mysql');
$task->status = ScheduledTask::STATUS_COMPLETED; $task->status = ScheduledTask::STATUS_COMPLETED;
$task->save(); $task->save();
} }
function reschedule(ScheduledTask $task, $timeout) { function reschedule(ScheduledTask $task, $timeout) {
$scheduled_at = Carbon::createFromTimestamp(WPFunctions::currentTime('timestamp')); $scheduled_at = Carbon::createFromTimestamp($this->wp->currentTime('timestamp'));
$task->scheduled_at = $scheduled_at->addMinutes($timeout); $task->scheduled_at = $scheduled_at->addMinutes($timeout);
$task->save(); $task->save();
} }
static function getNextRunDate() { static function getNextRunDate() {
$date = Carbon::createFromTimestamp(WPFunctions::currentTime('timestamp')); $wp = new WPFunctions();
$date = Carbon::createFromTimestamp($wp->currentTime('timestamp'));
// Random day of the next week // Random day of the next week
$date->setISODate($date->format('o'), $date->format('W') + 1, mt_rand(1, 7)); $date->setISODate($date->format('o'), $date->format('W') + 1, mt_rand(1, 7));
$date->startOfDay(); $date->startOfDay();
@ -121,8 +123,9 @@ abstract class SimpleWorker {
static function getScheduledTasks($future = false) { static function getScheduledTasks($future = false) {
$dateWhere = ($future) ? 'whereGt' : 'whereLte'; $dateWhere = ($future) ? 'whereGt' : 'whereLte';
$wp = new WPFunctions();
return ScheduledTask::where('type', static::TASK_TYPE) return ScheduledTask::where('type', static::TASK_TYPE)
->$dateWhere('scheduled_at', Carbon::createFromTimestamp(WPFunctions::currentTime('timestamp'))) ->$dateWhere('scheduled_at', Carbon::createFromTimestamp($wp->currentTime('timestamp')))
->whereNull('deleted_at') ->whereNull('deleted_at')
->where('status', ScheduledTask::STATUS_SCHEDULED) ->where('status', ScheduledTask::STATUS_SCHEDULED)
->limit(self::TASK_BATCH_SIZE) ->limit(self::TASK_BATCH_SIZE)
@ -130,8 +133,9 @@ abstract class SimpleWorker {
} }
static function getRunningTasks() { static function getRunningTasks() {
$wp = new WPFunctions();
return ScheduledTask::where('type', static::TASK_TYPE) return ScheduledTask::where('type', static::TASK_TYPE)
->whereLte('scheduled_at', Carbon::createFromTimestamp(WPFunctions::currentTime('timestamp'))) ->whereLte('scheduled_at', Carbon::createFromTimestamp($wp->currentTime('timestamp')))
->whereNull('deleted_at') ->whereNull('deleted_at')
->whereNull('status') ->whereNull('status')
->limit(self::TASK_BATCH_SIZE) ->limit(self::TASK_BATCH_SIZE)

View File

@ -32,6 +32,8 @@ class AmazonSES {
/** @var AmazonSESMapper */ /** @var AmazonSESMapper */
private $error_mapper; private $error_mapper;
private $wp;
function __construct( function __construct(
$region, $region,
$access_key, $access_key,
@ -61,11 +63,12 @@ class AmazonSES {
$this->date = gmdate('Ymd\THis\Z'); $this->date = gmdate('Ymd\THis\Z');
$this->date_without_time = gmdate('Ymd'); $this->date_without_time = gmdate('Ymd');
$this->error_mapper = $error_mapper; $this->error_mapper = $error_mapper;
$this->wp = new WPFunctions();
} }
function send($newsletter, $subscriber, $extra_params = array()) { function send($newsletter, $subscriber, $extra_params = array()) {
try { try {
$result = WPFunctions::wpRemotePost( $result = $this->wp->wpRemotePost(
$this->url, $this->url,
$this->request($newsletter, $subscriber, $extra_params) $this->request($newsletter, $subscriber, $extra_params)
); );
@ -77,8 +80,8 @@ class AmazonSES {
$error = $this->error_mapper->getConnectionError($result->get_error_message()); $error = $this->error_mapper->getConnectionError($result->get_error_message());
return Mailer::formatMailerErrorResult($error); return Mailer::formatMailerErrorResult($error);
} }
if(WPFunctions::wpRemoteRetrieveResponseCode($result) !== 200) { if($this->wp->wpRemoteRetrieveResponseCode($result) !== 200) {
$response = simplexml_load_string(WPFunctions::wpRemoteRetrieveBody($result)); $response = simplexml_load_string($this->wp->wpRemoteRetrieveBody($result));
$error = $this->error_mapper->getErrorFromResponse($response, $subscriber); $error = $this->error_mapper->getErrorFromResponse($response, $subscriber);
return Mailer::formatMailerErrorResult($error); return Mailer::formatMailerErrorResult($error);
} }

View File

@ -17,15 +17,18 @@ class SendGrid {
/** @var SendGridMapper */ /** @var SendGridMapper */
private $error_mapper; private $error_mapper;
private $wp;
function __construct($api_key, $sender, $reply_to, SendGridMapper $error_mapper) { function __construct($api_key, $sender, $reply_to, SendGridMapper $error_mapper) {
$this->api_key = $api_key; $this->api_key = $api_key;
$this->sender = $sender; $this->sender = $sender;
$this->reply_to = $reply_to; $this->reply_to = $reply_to;
$this->error_mapper = $error_mapper; $this->error_mapper = $error_mapper;
$this->wp = new WPFunctions();
} }
function send($newsletter, $subscriber, $extra_params = array()) { function send($newsletter, $subscriber, $extra_params = array()) {
$result = WPFunctions::wpRemotePost( $result = $this->wp->wpRemotePost(
$this->url, $this->url,
$this->request($newsletter, $subscriber, $extra_params) $this->request($newsletter, $subscriber, $extra_params)
); );
@ -33,7 +36,7 @@ class SendGrid {
$error = $this->error_mapper->getConnectionError($result->get_error_message()); $error = $this->error_mapper->getConnectionError($result->get_error_message());
return Mailer::formatMailerErrorResult($error); return Mailer::formatMailerErrorResult($error);
} }
if(WPFunctions::wpRemoteRetrieveResponseCode($result) !== 200) { if($this->wp->wpRemoteRetrieveResponseCode($result) !== 200) {
$response = json_decode($result['body'], true); $response = json_decode($result['body'], true);
$error = $this->error_mapper->getErrorFromResponse($response, $subscriber); $error = $this->error_mapper->getErrorFromResponse($response, $subscriber);
return Mailer::formatMailerErrorResult($error); return Mailer::formatMailerErrorResult($error);

View File

@ -16,6 +16,13 @@ class ScheduledTask extends Model {
const PRIORITY_MEDIUM = 5; const PRIORITY_MEDIUM = 5;
const PRIORITY_LOW = 10; const PRIORITY_LOW = 10;
private $wp;
function __construct() {
parent::__construct();
$this->wp = new WPFunctions();
}
function subscribers() { function subscribers() {
return $this->hasManyThrough( return $this->hasManyThrough(
__NAMESPACE__.'\Subscriber', __NAMESPACE__.'\Subscriber',
@ -61,7 +68,7 @@ class ScheduledTask extends Model {
} }
function complete() { function complete() {
$this->processed_at = WPFunctions::currentTime('mysql'); $this->processed_at = $this->wp->currentTime('mysql');
$this->set('status', self::STATUS_COMPLETED); $this->set('status', self::STATUS_COMPLETED);
$this->save(); $this->save();
return ($this->getErrors() === false && $this->id() > 0); return ($this->getErrors() === false && $this->id() > 0);

View File

@ -14,11 +14,13 @@ class PostTransformer {
private $args; private $args;
private $with_layout; private $with_layout;
private $image_position; private $image_position;
private $wp;
function __construct($args) { function __construct($args) {
$this->args = $args; $this->args = $args;
$this->with_layout = isset($args['withLayout']) ? (bool)filter_var($args['withLayout'], FILTER_VALIDATE_BOOLEAN) : false; $this->with_layout = isset($args['withLayout']) ? (bool)filter_var($args['withLayout'], FILTER_VALIDATE_BOOLEAN) : false;
$this->image_position = 'left'; $this->image_position = 'left';
$this->wp = new WPFunctions();
} }
function getDivider() { function getDivider() {
@ -150,7 +152,7 @@ class PostTransformer {
} }
$thumbnail_id = get_post_thumbnail_id($post_id); $thumbnail_id = get_post_thumbnail_id($post_id);
$image_info = WPFunctions::getImageInfo($thumbnail_id); $image_info = $this->wp->getImageInfo($thumbnail_id);
// get alt text // get alt text
$alt_text = trim(strip_tags(get_post_meta( $alt_text = trim(strip_tags(get_post_meta(

View File

@ -226,7 +226,8 @@ class Scheduler {
} }
static function getNextRunDate($schedule, $from_timestamp = false) { static function getNextRunDate($schedule, $from_timestamp = false) {
$from_timestamp = ($from_timestamp) ? $from_timestamp : WPFunctions::currentTime('timestamp'); $wp = new WPFunctions();
$from_timestamp = ($from_timestamp) ? $from_timestamp : $wp->currentTime('timestamp');
try { try {
$schedule = \Cron\CronExpression::factory($schedule); $schedule = \Cron\CronExpression::factory($schedule);
$next_run_date = $schedule->getNextRunDate(Carbon::createFromTimestamp($from_timestamp)) $next_run_date = $schedule->getNextRunDate(Carbon::createFromTimestamp($from_timestamp))
@ -238,7 +239,8 @@ class Scheduler {
} }
static function getPreviousRunDate($schedule, $from_timestamp = false) { static function getPreviousRunDate($schedule, $from_timestamp = false) {
$from_timestamp = ($from_timestamp) ? $from_timestamp : WPFunctions::currentTime('timestamp'); $wp = new WPFunctions();
$from_timestamp = ($from_timestamp) ? $from_timestamp : $wp->currentTime('timestamp');
try { try {
$schedule = \Cron\CronExpression::factory($schedule); $schedule = \Cron\CronExpression::factory($schedule);
$previous_run_date = $schedule->getPreviousRunDate(Carbon::createFromTimestamp($from_timestamp)) $previous_run_date = $schedule->getPreviousRunDate(Carbon::createFromTimestamp($from_timestamp))
@ -250,7 +252,8 @@ class Scheduler {
} }
static function getScheduledTimeWithDelay($after_time_type, $after_time_number) { static function getScheduledTimeWithDelay($after_time_type, $after_time_number) {
$current_time = Carbon::createFromTimestamp(WPFunctions::currentTime('timestamp')); $wp = new WPFunctions();
$current_time = Carbon::createFromTimestamp($wp->currentTime('timestamp'));
switch($after_time_type) { switch($after_time_type) {
case 'hours': case 'hours':
return $current_time->addHours($after_time_number); return $current_time->addHours($after_time_number);

View File

@ -16,11 +16,12 @@ class Date {
'mtext' => 'F', 'mtext' => 'F',
'y' => 'Y' 'y' => 'Y'
); );
$wp = new WPFunctions();
if(!empty($action_mapping[$shortcode_details['action']])) { if(!empty($action_mapping[$shortcode_details['action']])) {
return date_i18n($action_mapping[$shortcode_details['action']], WPFunctions::currentTime('timestamp')); return date_i18n($action_mapping[$shortcode_details['action']], $wp->currentTime('timestamp'));
} }
return ($shortcode_details['action'] === 'custom' && $shortcode_details['action_argument'] === 'format') ? return ($shortcode_details['action'] === 'custom' && $shortcode_details['action_argument'] === 'format') ?
date_i18n($shortcode_details['action_argument_value'], WPFunctions::currentTime('timestamp')) : date_i18n($shortcode_details['action_argument_value'], $wp->currentTime('timestamp')) :
false; false;
} }
} }

View File

@ -56,8 +56,9 @@ class Bridge {
'blocking' => true, 'blocking' => true,
'timeout' => 10 'timeout' => 10
); );
$result = WPFunctions::wpRemoteGet(self::BRIDGE_URL, $params); $wp = new WPFunctions();
return WPFunctions::wpRemoteRetrieveResponseCode($result) === 200; $result = $wp->wpRemoteGet(self::BRIDGE_URL, $params);
return $wp->wpRemoteRetrieveResponseCode($result) === 200;
} }
function initApi($api_key) { function initApi($api_key) {

View File

@ -23,6 +23,7 @@ class API {
const RESPONSE_CODE_BANNED_ACCOUNT = 403; const RESPONSE_CODE_BANNED_ACCOUNT = 403;
private $api_key; private $api_key;
private $wp;
public $url_me = 'https://bridge.mailpoet.com/api/v0/me'; public $url_me = 'https://bridge.mailpoet.com/api/v0/me';
public $url_premium = 'https://bridge.mailpoet.com/api/v0/premium'; public $url_premium = 'https://bridge.mailpoet.com/api/v0/premium';
@ -30,8 +31,13 @@ class API {
public $url_bounces = 'https://bridge.mailpoet.com/api/v0/bounces/search'; public $url_bounces = 'https://bridge.mailpoet.com/api/v0/bounces/search';
public $url_stats = 'https://bridge.mailpoet.com/api/v0/stats'; public $url_stats = 'https://bridge.mailpoet.com/api/v0/stats';
function __construct($api_key) { function __construct($api_key, $wp = null) {
$this->setKey($api_key); $this->setKey($api_key);
if(is_null($wp)) {
$this->wp = new WPFunctions();
} else {
$this->wp = $wp;
}
} }
function checkMSSKey() { function checkMSSKey() {
@ -40,10 +46,10 @@ class API {
array('site' => home_url()) array('site' => home_url())
); );
$code = WPFunctions::wpRemoteRetrieveResponseCode($result); $code = $this->wp->wpRemoteRetrieveResponseCode($result);
switch($code) { switch($code) {
case 200: case 200:
$body = json_decode(WPFunctions::wpRemoteRetrieveBody($result), true); $body = json_decode($this->wp->wpRemoteRetrieveBody($result), true);
break; break;
default: default:
$body = null; $body = null;
@ -59,10 +65,10 @@ class API {
array('site' => home_url()) array('site' => home_url())
); );
$code = WPFunctions::wpRemoteRetrieveResponseCode($result); $code = $this->wp->wpRemoteRetrieveResponseCode($result);
switch($code) { switch($code) {
case 200: case 200:
if($body = WPFunctions::wpRemoteRetrieveBody($result)) { if($body = $this->wp->wpRemoteRetrieveBody($result)) {
$body = json_decode($body, true); $body = json_decode($body, true);
} }
break; break;
@ -87,11 +93,11 @@ class API {
); );
} }
$response_code = WPFunctions::wpRemoteRetrieveResponseCode($result); $response_code = $this->wp->wpRemoteRetrieveResponseCode($result);
if($response_code !== 201) { if($response_code !== 201) {
$response = (WPFunctions::wpRemoteRetrieveBody($result)) ? $response = ($this->wp->wpRemoteRetrieveBody($result)) ?
WPFunctions::wpRemoteRetrieveBody($result) : $this->wp->wpRemoteRetrieveBody($result) :
WPFunctions::wpRemoteRetrieveResponseMessage($result); $this->wp->wpRemoteRetrieveResponseMessage($result);
return array( return array(
'status' => self::SENDING_STATUS_SEND_ERROR, 'status' => self::SENDING_STATUS_SEND_ERROR,
'message' => $response, 'message' => $response,
@ -106,8 +112,8 @@ class API {
$this->url_bounces, $this->url_bounces,
$emails $emails
); );
if(WPFunctions::wpRemoteRetrieveResponseCode($result) === 200) { if($this->wp->wpRemoteRetrieveResponseCode($result) === 200) {
return json_decode(WPFunctions::wpRemoteRetrieveBody($result), true); return json_decode($this->wp->wpRemoteRetrieveBody($result), true);
} }
return false; return false;
} }
@ -118,7 +124,7 @@ class API {
array('subscriber_count' => (int)$count), array('subscriber_count' => (int)$count),
'PUT' 'PUT'
); );
return WPFunctions::wpRemoteRetrieveResponseCode($result) === self::RESPONSE_CODE_STATS_SAVED; return $this->wp->wpRemoteRetrieveResponseCode($result) === self::RESPONSE_CODE_STATS_SAVED;
} }
function setKey($api_key) { function setKey($api_key) {
@ -144,6 +150,6 @@ class API {
), ),
'body' => json_encode($body) 'body' => json_encode($body)
); );
return WPFunctions::wpRemotePost($url, $params); return $this->wp->wpRemotePost($url, $params);
} }
} }

View File

@ -8,11 +8,12 @@ if(!defined('ABSPATH')) exit;
class API { class API {
private $api_key; private $api_key;
private $wp;
public $url_products = 'https://release.mailpoet.com/products/'; public $url_products = 'https://release.mailpoet.com/products/';
function __construct($api_key) { function __construct($api_key) {
$this->setKey($api_key); $this->setKey($api_key);
$this->wp = new WPFunctions();
} }
function getPluginInformation($plugin_name) { function getPluginInformation($plugin_name) {
@ -20,10 +21,10 @@ class API {
$this->url_products . $plugin_name $this->url_products . $plugin_name
); );
$code = WPFunctions::wpRemoteRetrieveResponseCode($result); $code = $this->wp->wpRemoteRetrieveResponseCode($result);
switch($code) { switch($code) {
case 200: case 200:
if($body = WPFunctions::wpRemoteRetrieveBody($result)) { if($body = $this->wp->wpRemoteRetrieveBody($result)) {
$body = json_decode($body); $body = json_decode($body);
} }
break; break;
@ -50,6 +51,6 @@ class API {
'timeout' => 10, 'timeout' => 10,
'httpversion' => '1.0' 'httpversion' => '1.0'
); );
return WPFunctions::wpRemoteGet($url, $args); return $this->wp->wpRemoteGet($url, $args);
} }
} }

View File

@ -229,12 +229,13 @@ class Sending {
} }
static function getScheduledQueues($amount = self::RESULT_BATCH_SIZE) { static function getScheduledQueues($amount = self::RESULT_BATCH_SIZE) {
$wp = new WPFunctions();
$tasks = ScheduledTask::table_alias('tasks') $tasks = ScheduledTask::table_alias('tasks')
->select('tasks.*') ->select('tasks.*')
->join(SendingQueue::$_table, 'tasks.id = queues.task_id', 'queues') ->join(SendingQueue::$_table, 'tasks.id = queues.task_id', 'queues')
->whereNull('tasks.deleted_at') ->whereNull('tasks.deleted_at')
->where('tasks.status', ScheduledTask::STATUS_SCHEDULED) ->where('tasks.status', ScheduledTask::STATUS_SCHEDULED)
->whereLte('tasks.scheduled_at', Carbon::createFromTimestamp(WPFunctions::currentTime('timestamp'))) ->whereLte('tasks.scheduled_at', Carbon::createFromTimestamp($wp->currentTime('timestamp')))
->where('tasks.type', 'sending') ->where('tasks.type', 'sending')
->whereNotEqual('tasks.status', ScheduledTask::STATUS_PAUSED) ->whereNotEqual('tasks.status', ScheduledTask::STATUS_PAUSED)
->orderByAsc('tasks.updated_at') ->orderByAsc('tasks.updated_at')

View File

@ -10,7 +10,10 @@ class DateTime {
const DEFAULT_TIME_FORMAT = 'H:i:s'; const DEFAULT_TIME_FORMAT = 'H:i:s';
const DEFAULT_DATE_TIME_FORMAT = 'Y-m-d H:i:s'; const DEFAULT_DATE_TIME_FORMAT = 'Y-m-d H:i:s';
private $wp;
function __construct() { function __construct() {
$this->wp = new WPFunctions();
} }
function getTimeFormat() { function getTimeFormat() {
@ -27,7 +30,7 @@ class DateTime {
function getCurrentTime($format=false) { function getCurrentTime($format=false) {
if (empty($format)) $format = $this->getTimeFormat(); if (empty($format)) $format = $this->getTimeFormat();
return WPFunctions::currentTime($format); return $this->wp->currentTime($format);
} }
function getCurrentDate($format=false) { function getCurrentDate($format=false) {

View File

@ -4,39 +4,31 @@ namespace MailPoet\WP;
use MailPoet\Config\Env; use MailPoet\Config\Env;
class Functions { class Functions {
static function wpRemotePost() { function wpRemotePost() {
return self::callWithFallback('wp_remote_post', func_get_args()); return call_user_func_array('wp_remote_post', func_get_args());
} }
static function wpRemoteGet() { function wpRemoteGet() {
return self::callWithFallback('wp_remote_get', func_get_args()); return call_user_func_array('wp_remote_get', func_get_args());
} }
static function wpRemoteRetrieveBody() { function wpRemoteRetrieveBody() {
return self::callWithFallback('wp_remote_retrieve_body', func_get_args()); return call_user_func_array('wp_remote_retrieve_body', func_get_args());
} }
static function wpRemoteRetrieveResponseCode() { function wpRemoteRetrieveResponseCode() {
return self::callWithFallback('wp_remote_retrieve_response_code', func_get_args()); return call_user_func_array('wp_remote_retrieve_response_code', func_get_args());
} }
static function wpRemoteRetrieveResponseMessage() { function wpRemoteRetrieveResponseMessage() {
return self::callWithFallback('wp_remote_retrieve_response_message', func_get_args()); return call_user_func_array('wp_remote_retrieve_response_message', func_get_args());
} }
static function currentTime() { function currentTime() {
return self::callWithFallback('current_time', func_get_args()); return call_user_func_array('current_time', func_get_args());
} }
private static function callWithFallback($func, $args) { function getImageInfo($id) {
$local_func = __NAMESPACE__ . '\\' . $func;
if(function_exists($local_func)) {
return call_user_func_array($local_func, $args);
}
return call_user_func_array($func, $args);
}
static function getImageInfo($id) {
/* /*
* In some cases wp_get_attachment_image_src ignore the second parameter * In some cases wp_get_attachment_image_src ignore the second parameter
* and use global variable $content_width value instead. * and use global variable $content_width value instead.

View File

@ -2,12 +2,13 @@
namespace MailPoet\Test\Cron; namespace MailPoet\Test\Cron;
use Codeception\Stub;
use AspectMock\Test as Mock; use AspectMock\Test as Mock;
use Helper\WordPress as WPHelper;
use MailPoet\Cron\CronHelper; use MailPoet\Cron\CronHelper;
use MailPoet\Cron\DaemonHttpRunner; use MailPoet\Cron\DaemonHttpRunner;
use MailPoet\Models\Setting; use MailPoet\Models\Setting;
use MailPoet\WP\Hooks as WPHooks; use MailPoet\WP\Hooks as WPHooks;
use MailPoet\WP\Functions as WPFunctions;
class CronHelperTest extends \MailPoetTest { class CronHelperTest extends \MailPoetTest {
function _before() { function _before() {
@ -272,13 +273,14 @@ class CronHelperTest extends \MailPoetTest {
expect($args)->notEmpty(); expect($args)->notEmpty();
return $request_args; return $request_args;
}; };
$wp_remote_get_args = array(); $wp_remote_get_args = [];
WPHelper::interceptFunction('wp_remote_post', function() use (&$wp_remote_get_args) { $wp = Stub::make(new WPFunctions(), [
$wp_remote_get_args = func_get_args(); 'wpRemotePost' => function() use (&$wp_remote_get_args) {
}); return $wp_remote_get_args = func_get_args();
}
]);
WPHooks::addFilter('mailpoet_cron_request_args', $filter); WPHooks::addFilter('mailpoet_cron_request_args', $filter);
CronHelper::queryCronUrl('test', $wp);
CronHelper::queryCronUrl('test');
expect($wp_remote_get_args[1])->equals($request_args); expect($wp_remote_get_args[1])->equals($request_args);
WPHooks::removeFilter('mailpoet_cron_request_args', $filter); WPHooks::removeFilter('mailpoet_cron_request_args', $filter);
@ -300,7 +302,6 @@ class CronHelperTest extends \MailPoetTest {
} }
function _after() { function _after() {
WPHelper::releaseAllFunctions();
Mock::clean(); Mock::clean();
\ORM::raw_execute('TRUNCATE ' . Setting::$_table); \ORM::raw_execute('TRUNCATE ' . Setting::$_table);
} }

View File

@ -1,8 +1,9 @@
<?php <?php
namespace MailPoet\Test\Cron\Workers; namespace MailPoet\Test\Cron\Workers;
use Carbon\Carbon; use Carbon\Carbon;
use Helper\WordPress as WordPressHelper; use Codeception\Stub;
use MailPoet\Cron\Workers\SendingQueue\Migration; use MailPoet\Cron\Workers\SendingQueue\Migration;
use MailPoet\Mailer\MailerLog; use MailPoet\Mailer\MailerLog;
use MailPoet\Models\ScheduledTask; use MailPoet\Models\ScheduledTask;
@ -11,6 +12,7 @@ use MailPoet\Models\SendingQueue;
use MailPoet\Models\Setting; use MailPoet\Models\Setting;
use MailPoet\Models\Subscriber; use MailPoet\Models\Subscriber;
use MailPoet\Tasks\Sending as SendingTask; use MailPoet\Tasks\Sending as SendingTask;
use MailPoet\WP\Functions as WPFunctions;
class MigrationTest extends \MailPoetTest { class MigrationTest extends \MailPoetTest {
function _before() { function _before() {
@ -111,14 +113,15 @@ class MigrationTest extends \MailPoetTest {
function testItUsesWPTimeToReturnNextRunDate() { function testItUsesWPTimeToReturnNextRunDate() {
$timestamp = 1514801410; $timestamp = 1514801410;
WordPressHelper::interceptFunction('current_time', function($time) use($timestamp) { $wp = Stub::make(new WPFunctions, [
'currentTime' => function($time) use($timestamp) {
// "timestamp" string is passed as an argument // "timestamp" string is passed as an argument
expect($time)->equals('timestamp'); expect($time)->equals('timestamp');
return $timestamp; return $timestamp;
}); }
]);
$next_run_date = Migration::getNextRunDate(); $next_run_date = Migration::getNextRunDate($wp);
expect($next_run_date->timestamp)->equals($timestamp); expect($next_run_date->timestamp)->equals($timestamp);
} }
@ -200,7 +203,5 @@ class MigrationTest extends \MailPoetTest {
$this->restoreTable(); $this->restoreTable();
$this->altered = false; $this->altered = false;
} }
WordPressHelper::releaseAllFunctions();
} }
} }

View File

@ -231,8 +231,9 @@ class NewsletterTest extends \MailPoetTest {
$queue = $this->queue; $queue = $this->queue;
$newsletter = $this->newsletter_task->preProcessNewsletter($newsletter, $queue); $newsletter = $this->newsletter_task->preProcessNewsletter($newsletter, $queue);
$queue = SendingTask::getByNewsletterId($newsletter->id); $queue = SendingTask::getByNewsletterId($newsletter->id);
$wp = new Functions();
expect($queue->newsletter_rendered_subject) expect($queue->newsletter_rendered_subject)
->contains(date_i18n('dS', Functions::currentTime('timestamp'))); ->contains(date_i18n('dS', $wp->currentTime('timestamp')));
} }
function testItUsesADefaultSubjectIfRenderedSubjectIsEmptyWhenPreprocessingNewsletter() { function testItUsesADefaultSubjectIfRenderedSubjectIsEmptyWhenPreprocessingNewsletter() {

View File

@ -3,13 +3,13 @@
namespace MailPoet\Test\Services; namespace MailPoet\Test\Services;
use Codeception\Util\Stub; use Codeception\Util\Stub;
use Helper\WordPress as WPHelper;
use MailPoet\Mailer\Mailer; use MailPoet\Mailer\Mailer;
use MailPoet\Models\Setting; use MailPoet\Models\Setting;
use MailPoet\Services\Bridge; use MailPoet\Services\Bridge;
use MailPoet\Services\Bridge\API; use MailPoet\Services\Bridge\API;
use MailPoet\Services\Bridge\BridgeTestMockAPI as MockAPI; use MailPoet\Services\Bridge\BridgeTestMockAPI as MockAPI;
use MailPoet\WP\Hooks as WPHooks; use MailPoet\WP\Hooks as WPHooks;
use MailPoet\WP\Functions as WPFunctions;
require_once('BridgeTestMockAPI.php'); require_once('BridgeTestMockAPI.php');
@ -257,10 +257,12 @@ class BridgeTest extends \MailPoetTest {
function testItAllowsChangingRequestTimeout() { function testItAllowsChangingRequestTimeout() {
$wp_remote_post_args = array(); $wp_remote_post_args = array();
WPHelper::interceptFunction('wp_remote_post', function() use (&$wp_remote_post_args) { $wp = Stub::make(new WPFunctions, [
'wpRemotePost' => function() use (&$wp_remote_post_args) {
$wp_remote_post_args = func_get_args(); $wp_remote_post_args = func_get_args();
}); }
$api = new API('test_key'); ]);
$api = new API('test_key', $wp);
// test default request value // test default request value
$api->sendMessages('test'); $api->sendMessages('test');
@ -311,7 +313,6 @@ class BridgeTest extends \MailPoetTest {
} }
function _after() { function _after() {
WPHelper::releaseAllFunctions();
\ORM::raw_execute('TRUNCATE ' . Setting::$_table); \ORM::raw_execute('TRUNCATE ' . Setting::$_table);
} }
} }

View File

@ -50,7 +50,8 @@ class FunctionsTest extends \MailPoetTest {
$id = $this->makeAttachment($upload); $id = $this->makeAttachment($upload);
expect($id)->notEmpty(); expect($id)->notEmpty();
$image = WPFunctions::getImageInfo($id); $wp = new WPFunctions();
$image = $wp->getImageInfo($id);
expect($image[1])->equals(Env::NEWSLETTER_CONTENT_WIDTH); expect($image[1])->equals(Env::NEWSLETTER_CONTENT_WIDTH);
wp_delete_attachment($id, $force_delete = true); wp_delete_attachment($id, $force_delete = true);