Registration flow filter for PHP?

I need to debug the socket connection that my PHP interface does for the backend service on another host, and I need to do this as close as possible to the metal. I have already abstracted communication at different levels, which, among other things, gives me the ability to easily attach stream filters to the connection. Therefore, the problem must be solved very easily: pack a stream filter into a class that allows you to perform arbitrary callbacks when data is sent or received, and then, for example, attach them to several log files.

The only problem is that my (naive?) Expecting that some such filter implementation floating on the Internet seems wrong! I do not mind writing a filter myself, but maybe there is something available that I just could not find?

For reference, I made google a lot of obvious changes to the "php logging stream filter".

Update: To clarify what I'm looking for, this is what would allow me to write code that is morally equivalent to this:

$params = array( 'onDataSent' => function($data) { echo "Sent: $data\n"; }, 'onDataReceived' => function($data) { echo "Received: $data\n"; }, ); stream_filter_register('logging', 'HookableStreamFilter'); stream_filter_append($someStream, 'logging', STREAM_FILTER_ALL, $params); 
+4
source share
1 answer

For posterity, this is what I ended up whipping. The filter itself comes from php_user_filter , which is described in the documents for stream_filter_register :

 class HookableFilter extends php_user_filter { public function filter($in, $out, &$consumed, $closing) { $data = ''; while ($bucket = stream_bucket_make_writeable($in)) { $consumed += $bucket->datalen; $data .= $bucket->data; stream_bucket_append($out, $bucket); } call_user_func($this->params, $data); return PSFS_PASS_ON; } } 

Note that I use $this->params directly as a callback, making it really Spartan in the function (there is a reason, see below).

Registering a filter using PHP:

 stream_filter_register('generic.hookable', 'HookableFilter'); 

Attaching a filter to a stream:

 $callback = function($data) { /* log the data */ }; stream_filter_append($stream, 'generic.hookable', STREAM_FILTER_READ, $callback); stream_filter_append($stream, 'generic.hookable', STREAM_FILTER_WRITE, $callback); 

Important: As far as I could see, if you attach a filter to both channels of a duplex stream (for example, one of them was created with stream_socket_client ) so that your filter does not know which channel it works when it is called. Therefore, if you need to distinguish between incoming and outgoing data as I was, the only option is to attach a filter separately to each channel. If you do this, you will also definitely want to provide a different callback for each channel (not the same as done in the simplified example above).

+1
source

Source: https://habr.com/ru/post/1399991/


All Articles