| 1 |
<?php |
| 2 |
|
| 3 |
namespace PostHog\Consumer; |
| 4 |
|
| 5 |
use Exception; |
| 6 |
use PostHog\Consumer; |
| 7 |
|
| 8 |
class File extends Consumer |
| 9 |
{ |
| 10 |
protected $type = "File"; |
| 11 |
|
| 12 |
private $file_handle; |
| 13 |
|
| 14 |
/** |
| 15 |
* The file consumer writes capture and identify calls to a file. |
| 16 |
* @param string $apiKey |
| 17 |
* @param array $options |
| 18 |
* string "filename" - where to log the posthog calls |
| 19 |
*/ |
| 20 |
public function __construct($apiKey, $options = array()) |
| 21 |
{ |
| 22 |
if (!isset($options["filename"])) { |
| 23 |
$options["filename"] = sys_get_temp_dir() . DIRECTORY_SEPARATOR . "posthog.log"; |
| 24 |
} |
| 25 |
parent::__construct($apiKey, $options); |
| 26 |
|
| 27 |
try { |
| 28 |
$this->file_handle = fopen($options["filename"], "a"); |
| 29 |
chmod($options["filename"], 0777); |
| 30 |
} catch (Exception $e) { |
| 31 |
$this->handleError($e->getCode(), $e->getMessage()); |
| 32 |
} |
| 33 |
} |
| 34 |
|
| 35 |
public function __destruct() |
| 36 |
{ |
| 37 |
if ($this->file_handle && "Unknown" != get_resource_type($this->file_handle)) { |
| 38 |
fclose($this->file_handle); |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* Define getter method for consumer type |
| 44 |
* |
| 45 |
* @return string |
| 46 |
*/ |
| 47 |
public function getConsumer() |
| 48 |
{ |
| 49 |
return $this->type; |
| 50 |
} |
| 51 |
|
| 52 |
/** |
| 53 |
* Captures a user action |
| 54 |
* |
| 55 |
* @param array $message |
| 56 |
* @return bool whether the capture call succeeded |
| 57 |
*/ |
| 58 |
public function capture(array $message) |
| 59 |
{ |
| 60 |
return $this->write($message); |
| 61 |
} |
| 62 |
|
| 63 |
/** |
| 64 |
* Tags properties about the user. |
| 65 |
* |
| 66 |
* @param array $message |
| 67 |
* @return bool whether the identify call succeeded |
| 68 |
*/ |
| 69 |
public function identify(array $message) |
| 70 |
{ |
| 71 |
return $this->write($message); |
| 72 |
} |
| 73 |
|
| 74 |
/** |
| 75 |
* Aliases from one user id to another |
| 76 |
* |
| 77 |
* @param array $message |
| 78 |
* @return boolean whether the alias call succeeded |
| 79 |
*/ |
| 80 |
public function alias(array $message) |
| 81 |
{ |
| 82 |
return $this->write($message); |
| 83 |
} |
| 84 |
|
| 85 |
/** |
| 86 |
* Writes the API call to a file as line-delimited json |
| 87 |
* @param array $body post body content. |
| 88 |
* @return bool whether the request succeeded |
| 89 |
*/ |
| 90 |
private function write($body) |
| 91 |
{ |
| 92 |
if (!$this->file_handle) { |
| 93 |
return false; |
| 94 |
} |
| 95 |
|
| 96 |
$content = json_encode($body); |
| 97 |
$content .= "\n"; |
| 98 |
|
| 99 |
return fwrite($this->file_handle, $content) == strlen($content); |
| 100 |
} |
| 101 |
} |
| 102 |
|