- Updates shortcodes logic

- Implements [newsletter:total] and [newsletter:number] shortcodes
- Implements shortcode replacement in subject line
- Updates unit tests
Issue #380
This commit is contained in:
Vlad
2016-03-19 11:19:22 -04:00
parent 71d8fb0d93
commit 6ec15bec22
6 changed files with 65 additions and 42 deletions

View File

@@ -2,52 +2,51 @@
namespace MailPoet\Newsletter\Shortcodes;
class Shortcodes {
public $rendered_newsletter;
public $newsletter;
public $subscriber;
function __construct(
$rendered_newsletter,
$newsletter = false,
$subscriber = false
) {
$this->rendered_newsletter = $rendered_newsletter;
$this->newsletter = $newsletter;
$this->subscriber = $subscriber;
}
function extract() {
preg_match_all('/\[(?:\w+):.*?\]/', $this->rendered_newsletter, $shortcodes);
function extract($text) {
preg_match_all('/\[(?:\w+):.*?\]/', $text, $shortcodes);
return array_unique($shortcodes[0]);
}
function process($shortcodes) {
function process($shortcodes, $text) {
$processed_shortcodes = array_map(
function ($shortcode) {
function($shortcode) use($text) {
preg_match(
'/\[(?P<type>\w+):(?P<action>\w+)(?:.*?default:(?P<default>.*?))?\]/',
$shortcode,
$shortcode_details
);
$shortcode_class =
__NAMESPACE__ . '\\Categories\\' . ucfirst($shortcode_details['type']);
$shortcode_action = $shortcode_details['action'];
$shortcode_default_value = isset($shortcode_details['default'])
? $shortcode_details['default'] : false;
if(!class_exists($shortcode_class)) return false;
return $shortcode_class::process(
$shortcode_details['action'],
isset($shortcode_details['default'])
? $shortcode_details['default'] : false,
$shortcode_action,
$shortcode_default_value,
$this->newsletter,
$this->subscriber
$this->subscriber,
$text
);
}, $shortcodes);
return $processed_shortcodes;
}
function replace() {
$shortcodes = $this->extract($this->rendered_newsletter);
$processed_shortcodes = $this->process($shortcodes);
function replace($text) {
$shortcodes = $this->extract($text);
$processed_shortcodes = $this->process($shortcodes, $text);
$shortcodes = array_intersect_key($shortcodes, $processed_shortcodes);
return str_replace($shortcodes, $processed_shortcodes, $this->rendered_newsletter);
return str_replace($shortcodes, $processed_shortcodes, $text);
}
}