Skip to content

6.3 CSV Module

Juan Morales edited this page Mar 5, 2021 · 2 revisions

Module: CSV

Features

This modules generates a CSV output of the log being generated.

The output format will follow this form: 'currentLogId',{"testKey1":"testData1", "testKey2":"testData2", ..... , "testKeyN":"testDataN"}

The first field is the log ID which is a value that makes the log record unique; the second value is a JSON string with every key-value pair generated for that log record.

Code analysis

Please check the comments

<?php declare(strict_types=1);

namespace Footprint\Modules;

use Footprint\Interfaces\IModule;
use Footprint\Tracker;

class CSV implements IModule
{
    //The module ID will be CSV
    const MODULE_ID = "CSV";

    /*
     * Because this module will output a CSV file with the "logs" generatd by the Tracker
     * during a running instance, we use this variable/property to hold a reference to the
     * file handler that will be use to write that file into disk.
     */
    protected $fileHandler;

    //The class accepts one argument, its a string with the path/filename to be used
    public function __construct(string $filename) {
        //Right at the instantation of the module, the output file is created
        if (!$this->fileHandler = fopen($filename, "w+")) {
            return;
        }
    }

    public function getId() {
        return self::MODULE_ID;
    }

    public function onInit(Tracker &$tracker) {
        return;
    }

    /*
     * When the Tracker instance is about to terminate, this callback will be call ... by the Tracker
     * Thats when this module closes the file handler
     */
    public function onEnd(Tracker &$tracker) {
        fclose($this->fileHandler);
        return;
    }

    public function onLoad(Tracker &$tracker) {
        return;
    }

    public function onUnload(Tracker &$tracker) {
        return;
    }

    /*
     * Every time the Tracker excutes a log(), this module saves the content
     * of the current log record generated by the Tracker, ... in the output file.
     */
    public function onLog(Tracker &$tracker) {
        fputcsv(
            $this->fileHandler,
            [$tracker->getLogId(), $tracker->getLogDataAsJSON()],
            ",",
            "'"
        );
    }

    public function onLogBuild(Tracker &$tracker) {
        return;
    }

    public function getKeys() : array {
        return [];
    }
}

That is the implementation of a module that produces a final output in the disk, in this case, a CSV file.