Skip to content

WordPress Actions

Flowguard bietet Action-Hooks, die Entwicklern ermöglichen, benutzerdefinierten Code an bestimmten Punkten während der Flow-Ausführung auszuführen.

Übersicht

Actions sind WordPress-Hooks, mit denen Sie benutzerdefinierte Funktionen ausführen können, wenn bestimmte Ereignisse eintreten. Flowguard löst Actions vor und nach der Flow-Ausführung aus, wodurch Sie:

  • Ausführungsereignisse protokollieren können
  • Benachrichtigungen senden können
  • Externe Systeme auslösen können
  • Benutzerdefinierte Daten aktualisieren können
  • Mit anderen Plugins integrieren können

Verfügbare Actions

flowguard_before_flow_run

Wird unmittelbar vor Beginn der Flow-Ausführung ausgelöst.

Hook-Name: flowguard_before_flow_run

Parameter:

ParameterTypBeschreibung
$flow_idintDie Flow-Post-ID
$flow_dataarrayVollständige Flow-Daten, die ausgeführt werden

Flow-Daten-Struktur:

php
$flow_data = [
    'id'       => 123,                // Flow-Post-ID
    'title'    => 'Login-Test-Flow',  // Flow-Titel
    'steps'    => [...],              // Array von Step-Objekten
    'settings' => [                   // Flow-Einstellungen
        'timeout'    => 30000,
        'retries'    => 0,
        'screenshot' => true,
    ],
    'siteUrl'  => 'https://ihreseite.de',
];

Beispielverwendung:

php
/**
 * Flow-Ausführung starten protokollieren
 */
add_action('flowguard_before_flow_run', function($flow_id, $flow_data) {
    error_log(sprintf(
        'Flowguard: Starte Flow #%d "%s" mit %d Steps',
        $flow_id,
        $flow_data['title'],
        count($flow_data['steps'])
    ));
}, 10, 2);

Anwendungsfälle:

  1. Protokollierung:
php
add_action('flowguard_before_flow_run', function($flow_id, $flow_data) {
    // In benutzerdefinierte Tabelle protokollieren
    global $wpdb;
    $wpdb->insert('flow_execution_log', [
        'flow_id'    => $flow_id,
        'started_at' => current_time('mysql'),
        'status'     => 'gestartet',
    ]);
}, 10, 2);
  1. Benachrichtigungen:
php
add_action('flowguard_before_flow_run', function($flow_id, $flow_data) {
    // Slack-Benachrichtigung senden
    wp_remote_post('https://hooks.slack.com/services/IHR/WEBHOOK/URL', [
        'body' => json_encode([
            'text' => "Flow '{$flow_data['title']}' hat Ausführung gestartet",
        ]),
    ]);
}, 10, 2);
  1. Umgebung vorbereiten:
php
add_action('flowguard_before_flow_run', function($flow_id, $flow_data) {
    // Caches vor dem Testen leeren
    wp_cache_flush();

    // Testdaten einrichten
    if (strpos($flow_data['title'], 'Warenkorb-Test') !== false) {
        // Sicherstellen, dass Warenkorb leer ist
        WC()->cart->empty_cart();
    }
}, 10, 2);
  1. Integration mit anderen Plugins:
php
add_action('flowguard_before_flow_run', function($flow_id, $flow_data) {
    // Wartungsmodus während Tests pausieren
    if (function_exists('wp_maintenance_mode')) {
        update_option('wp_maintenance_mode', false);
    }
}, 10, 2);

flowguard_after_flow_run

Wird nach Abschluss der Flow-Ausführung ausgelöst (ob erfolgreich oder fehlgeschlagen).

Hook-Name: flowguard_after_flow_run

Parameter:

ParameterTypBeschreibung
$flow_idintDie Flow-Post-ID
$last_runarrayAusführungsergebnisse

Last-Run-Struktur:

php
$last_run = [
    'timestamp' => '2024-12-06T15:30:00',  // ISO 8601 Format
    'status'    => 'passed',               // passed, failed oder running
    'duration'  => 3450,                   // Ausführungszeit in Millisekunden
    'error'     => '',                     // Fehlermeldung (wenn fehlgeschlagen)
    'results'   => [                       // Step-für-Step-Ergebnisse
        [
            'step'     => 1,
            'type'     => 'navigate',
            'status'   => 'passed',
            'duration' => 1200,
            'error'    => '',
        ],
        // ... weitere Step-Ergebnisse
    ],
];

Beispielverwendung:

php
/**
 * Flow-Ausführung abgeschlossen protokollieren
 */
add_action('flowguard_after_flow_run', function($flow_id, $last_run) {
    error_log(sprintf(
        'Flowguard: Flow #%d abgeschlossen mit Status "%s" in %dms',
        $flow_id,
        $last_run['status'],
        $last_run['duration']
    ));
}, 10, 2);

Anwendungsfälle:

  1. E-Mail-Benachrichtigungen bei Fehlern:
php
add_action('flowguard_after_flow_run', function($flow_id, $last_run) {
    if ($last_run['status'] === 'failed') {
        $flow = get_post($flow_id);

        wp_mail(
            'admin@ihreseite.de',
            'Flowguard: Flow fehlgeschlagen',
            sprintf(
                "Flow '%s' ist fehlgeschlagen:\n\n%s",
                $flow->post_title,
                $last_run['error']
            )
        );
    }
}, 10, 2);
  1. Statistiken verfolgen:
php
add_action('flowguard_after_flow_run', function($flow_id, $last_run) {
    // Ausführungsverlauf speichern
    $history = get_option('flowguard_execution_history', []);
    $history[] = [
        'flow_id'   => $flow_id,
        'timestamp' => $last_run['timestamp'],
        'status'    => $last_run['status'],
        'duration'  => $last_run['duration'],
    ];

    // Letzte 100 Ausführungen behalten
    if (count($history) > 100) {
        $history = array_slice($history, -100);
    }

    update_option('flowguard_execution_history', $history);
}, 10, 2);
  1. Slack-Integration:
php
add_action('flowguard_after_flow_run', function($flow_id, $last_run) {
    $flow = get_post($flow_id);
    $emoji = $last_run['status'] === 'passed' ? ':white_check_mark:' : ':x:';

    wp_remote_post('https://hooks.slack.com/services/IHR/WEBHOOK/URL', [
        'body' => json_encode([
            'text' => sprintf(
                "%s Flow '%s' %s in %.2fs",
                $emoji,
                $flow->post_title,
                $last_run['status'],
                $last_run['duration'] / 1000
            ),
        ]),
    ]);
}, 10, 2);
  1. Behebung auslösen:
php
add_action('flowguard_after_flow_run', function($flow_id, $last_run) {
    if ($last_run['status'] === 'failed') {
        // Automatische Korrektur versuchen
        $flow = get_post($flow_id);

        if (strpos($flow->post_title, 'Cache') !== false) {
            // Alle Caches leeren, wenn cache-bezogener Test fehlgeschlagen ist
            wp_cache_flush();

            // Optional Flow erneut ausführen
            do_action('flowguard_rerun_flow', $flow_id);
        }
    }
}, 10, 2);
  1. Externes Monitoring aktualisieren:
php
add_action('flowguard_after_flow_run', function($flow_id, $last_run) {
    // An Monitoring-Dienst senden (z.B. Datadog, New Relic)
    wp_remote_post('https://monitoring-dienst.de/api/events', [
        'headers' => ['Authorization' => 'Bearer IHR_API_KEY'],
        'body'    => json_encode([
            'event_type' => 'flowguard.execution',
            'flow_id'    => $flow_id,
            'status'     => $last_run['status'],
            'duration'   => $last_run['duration'],
            'timestamp'  => strtotime($last_run['timestamp']),
        ]),
    ]);
}, 10, 2);

Action-Priorität

Alle Flowguard-Actions akzeptieren Prioritäts- und Argumentanzahl-Parameter:

php
add_action('flowguard_before_flow_run', 'ihre_funktion', $prioritaet, $akzeptierte_args);

Standardpriorität: 10

Niedrigere Zahlen = Frühere Ausführung Höhere Zahlen = Spätere Ausführung

Beispiel mit Priorität:

php
// Dies zuerst ausführen (Priorität 5)
add_action('flowguard_before_flow_run', 'setup_test_environment', 5, 2);

// Dies als zweites ausführen (Priorität 10, Standard)
add_action('flowguard_before_flow_run', 'log_execution', 10, 2);

// Dies zuletzt ausführen (Priorität 20)
add_action('flowguard_before_flow_run', 'notify_team', 20, 2);

Actions entfernen

Um eine zuvor hinzugefügte Action zu entfernen:

php
remove_action('flowguard_before_flow_run', 'ihre_funktion', $prioritaet);

Beispiel:

php
// Action hinzufügen
add_action('flowguard_after_flow_run', 'send_notification', 10, 2);

// Action später entfernen
remove_action('flowguard_after_flow_run', 'send_notification', 10);

Best Practices

1. Flow-Kontext prüfen

Actions basierend auf Flow-Eigenschaften filtern:

php
add_action('flowguard_before_flow_run', function($flow_id, $flow_data) {
    // Nur für Produktions-Flows ausführen
    if (strpos($flow_data['title'], '[Produktion]') !== false) {
        // Spezielle Behandlung für Produktionstests
    }
}, 10, 2);

2. Fehler elegant behandeln

Lassen Sie Ihre Action-Callbacks nicht die Flow-Ausführung unterbrechen:

php
add_action('flowguard_after_flow_run', function($flow_id, $last_run) {
    try {
        // Ihr Code hier
        send_notification($flow_id, $last_run);
    } catch (Exception $e) {
        error_log('Flowguard-Benachrichtigung fehlgeschlagen: ' . $e->getMessage());
        // Nicht erneut werfen - Flow abschließen lassen
    }
}, 10, 2);

3. Passende Priorität verwenden

Ordnen Sie Ihre Actions logisch an:

  • Niedrige Priorität (5-9): Setup und Vorbereitung
  • Standardpriorität (10): Hauptoperationen
  • Hohe Priorität (11-20): Aufräumen und Benachrichtigungen

4. Aufwändige Operationen vermeiden

Halten Sie Action-Callbacks schnell, um die Ausführung nicht zu verzögern:

php
add_action('flowguard_after_flow_run', function($flow_id, $last_run) {
    // Gut: Benachrichtigung für asynchrone Verarbeitung einreihen
    wp_schedule_single_event(time(), 'send_flow_notification', [$flow_id, $last_run]);

    // Schlecht: E-Mail synchron senden (langsam)
    // wp_mail('admin@beispiel.de', 'Flow abgeschlossen', '...');
}, 10, 2);

5. Hooks dokumentieren

Kommentieren Sie Ihre Action-Callbacks:

php
/**
 * Slack-Benachrichtigung senden, wenn kritische Flows fehlschlagen
 *
 * @param int   $flow_id   Flow-Post-ID
 * @param array $last_run  Ausführungsergebnisse
 */
add_action('flowguard_after_flow_run', function($flow_id, $last_run) {
    // Implementierung
}, 10, 2);

Vollständiges Beispiel: Flow-Monitoring-System

Hier ist ein vollständiges Beispiel, das umfassendes Flow-Monitoring implementiert:

php
<?php
/**
 * Flowguard Benutzerdefiniertes Monitoring
 */

class Flowguard_Monitor {

    public function __construct() {
        add_action('flowguard_before_flow_run', [$this, 'before_run'], 10, 2);
        add_action('flowguard_after_flow_run', [$this, 'after_run'], 10, 2);
    }

    /**
     * Flow-Start protokollieren
     */
    public function before_run($flow_id, $flow_data) {
        // In Datenbank protokollieren
        global $wpdb;
        $wpdb->insert('flow_executions', [
            'flow_id'    => $flow_id,
            'flow_title' => $flow_data['title'],
            'started_at' => current_time('mysql'),
            'status'     => 'running',
        ]);

        // Ausführungs-ID für spätere Verwendung speichern
        $execution_id = $wpdb->insert_id;
        update_post_meta($flow_id, '_current_execution_id', $execution_id);

        // Team für kritische Flows benachrichtigen
        if ($this->is_critical_flow($flow_data)) {
            $this->notify_slack("Kritischer Flow '{$flow_data['title']}' gestartet");
        }
    }

    /**
     * Flow-Abschluss protokollieren
     */
    public function after_run($flow_id, $last_run) {
        global $wpdb;

        // Ausführungs-ID abrufen
        $execution_id = get_post_meta($flow_id, '_current_execution_id', true);

        // Datenbank aktualisieren
        $wpdb->update(
            'flow_executions',
            [
                'status'       => $last_run['status'],
                'duration'     => $last_run['duration'],
                'error'        => $last_run['error'],
                'completed_at' => current_time('mysql'),
            ],
            ['id' => $execution_id]
        );

        // Fehler behandeln
        if ($last_run['status'] === 'failed') {
            $this->handle_failure($flow_id, $last_run);
        }

        // Statistiken senden
        $this->update_statistics($flow_id, $last_run);

        // Aufräumen
        delete_post_meta($flow_id, '_current_execution_id');
    }

    /**
     * Flow-Fehler behandeln
     */
    private function handle_failure($flow_id, $last_run) {
        $flow = get_post($flow_id);

        // Admin per E-Mail benachrichtigen
        wp_mail(
            get_option('admin_email'),
            'Flowguard: Flow fehlgeschlagen',
            $this->format_failure_email($flow, $last_run)
        );

        // Slack benachrichtigen
        $this->notify_slack("Flow '{$flow->post_title}' fehlgeschlagen: {$last_run['error']}");

        // Fehlerzähler erhöhen
        $failures = (int) get_post_meta($flow_id, '_failure_count', true);
        update_post_meta($flow_id, '_failure_count', $failures + 1);
    }

    /**
     * Statistiken aktualisieren
     */
    private function update_statistics($flow_id, $last_run) {
        $stats = get_option('flowguard_statistics', [
            'total_executions' => 0,
            'total_passed'     => 0,
            'total_failed'     => 0,
            'total_duration'   => 0,
        ]);

        $stats['total_executions']++;
        $stats['total_' . $last_run['status']]++;
        $stats['total_duration'] += $last_run['duration'];

        update_option('flowguard_statistics', $stats);
    }

    /**
     * Prüfen, ob Flow kritisch ist
     */
    private function is_critical_flow($flow_data) {
        $critical_keywords = ['checkout', 'zahlung', 'login', 'kritisch'];
        $title_lower = strtolower($flow_data['title']);

        foreach ($critical_keywords as $keyword) {
            if (strpos($title_lower, $keyword) !== false) {
                return true;
            }
        }

        return false;
    }

    /**
     * Slack-Benachrichtigung senden
     */
    private function notify_slack($message) {
        $webhook_url = get_option('flowguard_slack_webhook');

        if (!$webhook_url) {
            return;
        }

        wp_remote_post($webhook_url, [
            'body' => json_encode(['text' => $message]),
            'headers' => ['Content-Type' => 'application/json'],
        ]);
    }

    /**
     * Fehler-E-Mail formatieren
     */
    private function format_failure_email($flow, $last_run) {
        return sprintf(
            "Flow: %s\n" .
            "Status: Fehlgeschlagen\n" .
            "Dauer: %dms\n" .
            "Fehler: %s\n\n" .
            "Flow ansehen: %s",
            $flow->post_title,
            $last_run['duration'],
            $last_run['error'],
            admin_url('admin.php?page=flowguard#/flows/' . $flow->ID)
        );
    }
}

// Initialisieren
new Flowguard_Monitor();

Verwandte Dokumentation

Zukünftige Actions

Zusätzliche Actions für zukünftige Versionen geplant:

  • flowguard_flow_created - Wenn ein Flow erstellt wird
  • flowguard_flow_updated - Wenn ein Flow aktualisiert wird
  • flowguard_flow_deleted - Wenn ein Flow gelöscht wird
  • flowguard_step_executed - Nach Ausführung jedes Steps
  • flowguard_flow_scheduled - Wenn ein Flow geplant wird

Support

Bei Fragen zu Actions:

  1. Lesen Sie die WordPress Plugin API Dokumentation
  2. Prüfen Sie den Flowguard-Quellcode
  3. Kontaktieren Sie den Support für Unterstützung