Files
grav-plugin-listmonk/listmonk.php
2025-07-12 16:45:24 +02:00

234 lines
6.8 KiB
PHP

<?php
namespace Grav\Plugin;
use AdnanHussainTurki\ListMonk\ListMonk;
use AdnanHussainTurki\ListMonk\Models\MonkSubscriber;
use Composer\Autoload\ClassLoader;
use Grav\Common\Data\Data;
use Grav\Common\Plugin;
use Grav\Plugin\Form\Form;
use Grav\Plugin\Listmonk\Exceptions\ListmonkClientException;
use Grav\Plugin\Listmonk\Exceptions\ListmonkException;
use RocketTheme\Toolbox\Event\Event;
use ValueError;
/**
* Class ListmonkPlugin
* @package Grav\Plugin
*/
class ListmonkPlugin extends Plugin
{
private ?ListMonk $client = null;
/**
* @return array
*
* The getSubscribedEvents() gives the core a list of events
* that the plugin wants to listen to. The key of each
* array section is the event that the plugin listens to
* and the value (in the form of an array) contains the
* callable (or function) as well as the priority. The
* higher the number the higher the priority.
*/
public static function getSubscribedEvents(): array
{
return [
'onPluginsInitialized' => ['onPluginsInitialized', 0],
'onFormProcessed' => ['onFormProcessed', 0],
];
}
/**
* Composer autoload
*
* @return ClassLoader
*/
public function autoload(): ClassLoader
{
return require __DIR__ . '/vendor/autoload.php';
}
/**
* Initialize the plugin
*/
public function onPluginsInitialized(): void
{
// Don't proceed if we are in the admin plugin
if ($this->isAdmin()) {
return;
}
// Enable the main events we are interested in
$this->enable([
// Put your main events here
]);
}
/**
* Process `listmonk` form actions
*
* @param Event $event
* @return void
* @throws MailerSendException
* @throws \JsonException
* @throws \MailerSend\Exceptions\MailerSendAssertException
*/
public function onFormProcessed(Event $event): void
{
$form = $event['form'];
$params = $event['params'];
switch ($event['action']) {
case 'listmonk_newsletter':
$this->processNewsletterForm($event, $form, $this->getParams($form, $params));
break;
#case 'listmonk':
# $this->processForm($event, $form, $this->getParams($form, $params));
# break;
}#
}
/**
* Process `listmonk_newsletter` form action
*
* @param Event $event
* @return void
*/
private function processNewsletterForm(Event $event, Form $form, array $params): void
{
try {
$subscriber = new MonkSubscriber();
$subscriber->setName($params['name']);
$subscriber->setEmail($params['email']);
$subscriber->setLists([
$this->config->get('plugins.listmonk.newsletter.list')
]);
$subscriber->setStatus($this->config->get('plugins.listmonk.newsletter.subscriber.status'));
$subscriber->setAttribs($this->processAttributes([
'source' => 'gravcms',
]));
$this->grav->fireEvent('onListmonkSubscriberObjectCreated', new Event([
'subscriber' => $subscriber,
]));
$this->getListmonkClient()
->subscribers()
->create($subscriber);
$this->grav->fireEvent('onListmonkSubscriberCreated', new Event([
'subscriber' => $subscriber,
]));
} catch (\Exception $e) {
$this->grav->fireEvent('onFormValidationError', new Event([
'form' => $form,
'message' => $this->parseMessage($e->getMessage())
]));
$event->stopPropagation();
}
}
private function processAttributes(array $attributes): array
{
$globals = $this->config->get('plugins.listmonk.newsletter.subscriber.attributes');
if ($globals) {
$globals = json_decode($globals, true);
if (!is_null($globals)) {
$attributes = array_merge($globals, $attributes);
}
}
return $attributes;
}
private function parseMessage(string $message): string
{
try {
$json = json_decode($message, true);
if (!is_null($json)) {
if (isset($json['message'])) {
return $json['message'];
}
return json_encode($json, JSON_FORCE_OBJECT);
}
return $message;
} catch (ValueError $e) {
return $e->getMessage();
}
}
/**
* Process `listmonk` form action
*
* @param Event $event
* @return void
*/
private function processForm(Event $event, Form $form, array $params): void
{
try {
$client = $this->getListmonkClient();
} catch (ListmonkClientException $e) {
$this->grav->fireEvent('onFormValidationError', new Event([
'form' => $form,
'message' => $e->getMessage()
]));
$event->stopPropagation();
} catch (ListmonkException $e) {
$event->stopPropagation();
throw new \RuntimeException('Error while processing form', -1, $e);
}
}
private function getListmonkClient(): ListMonk
{
if ($this->client instanceof ListMonk) {
return $this->client;
}
if (!$hostname = $this->config->get('plugins.listmonk.api.hostname')) {
throw new ListmonkClientException('Listmonk API hostname not configured');
}
if (!$username = $this->config->get('plugins.listmonk.api.username')) {
throw new ListmonkClientException('Listmonk API username not configured');
}
if (!$token = $this->config->get('plugins.listmonk.api.token')) {
throw new ListmonkClientException('Listmonk API token not configured');
}
$this->client = new ListMonk($hostname, $username, $token);
$this->grav->fireEvent('onListmonkClientCreated', new Event([
'client' => $this->client
]));
return $this->client;
}
private function getParams($form, $params): array
{
$vars = new Data([
'form' => $form,
'page' => $this->grav['page']
]);
$this->grav->fireEvent('onListmonkVars', new Event([
'vars' => $vars
]));
return $this->processParams($params, $vars->toArray());
}
private function processParams(array $params, array $vars = []): array
{
$twig = $this->grav['twig'];
array_walk_recursive($params, function(&$value) use ($twig, $vars) {
$value = $twig->processString($value, $vars);
});
return $params;
}
}