<?php

/**
 * Example (PHP 7.0-compatible): one message, multiple groups, different actions.
 *
 * Run this file in THREE separate terminals, once per group:
 *     php consume_multi_group.php email-service
 *     php consume_multi_group.php analytics-service
 *     php consume_multi_group.php audit-service
 *
 * Then publish one message with produce.php. Because each terminal uses a
 * different group.id, ALL THREE receive the same message and each performs
 * a different action.
 */

require_once __DIR__ . '/../autoload.php';

$group = isset($argv[1]) ? $argv[1] : 'email-service';

// PHP 7.0 has no arrow functions (fn) — use closures.
// Map each group to the action it performs on the same message.
$actions = array(
    'email-service' => function (array $m) {
        printf("[email]     sending mail for: %s\n", $m['payload']);
    },
    'analytics-service' => function (array $m) {
        printf("[analytics] recording metric for: %s\n", $m['payload']);
    },
    'audit-service' => function (array $m) {
        printf("[audit]     writing audit log for: %s\n", $m['payload']);
    },
);

if (isset($actions[$group])) {
    $action = $actions[$group];
} else {
    $action = function (array $m) use ($group) {
        printf("[%s] %s\n", $group, $m['payload']);
    };
}

$config   = new KafkaConfig('127.0.0.1:9092');
$consumer = new Consumer($config, $group, array('orders'));

echo "Consumer group '{$group}' listening on 'orders'... (Ctrl+C to stop)\n";

// Stop cleanly on Ctrl+C (requires the pcntl extension).
if (function_exists('pcntl_async_signals')) {
    pcntl_async_signals(true);
    pcntl_signal(SIGINT, function () use ($consumer) {
        $consumer->stop();
    });
}

$consumer->consume($action);
$consumer->close();
