Minor OrderedStreamingForkController improvements
authorTimo Tijhof <krinklemail@gmail.com>
Wed, 10 Oct 2018 19:17:37 +0000 (20:17 +0100)
committerTimo Tijhof <krinklemail@gmail.com>
Wed, 10 Oct 2018 21:37:02 +0000 (22:37 +0100)
Follows-up c94dea7029cae.

* Avoid strlen() where a strict check suffices.
* Use substr() for both comparison and stripping, avoid
  potentially expensive, but also fragile, because strlen()-1
  can  produce $str[-1], which would
  > PHP Notice:  Uninitialized string offset: -1
  Luckily, the implied null would work as expected, given that
  `null !== "\n"` and produces the same result.

Change-Id: If61e5e412aaa2dc7c00c4441b3b7bd5f04160ec8

includes/OrderedStreamingForkController.php

index 11abc81..5424b13 100644 (file)
@@ -135,13 +135,16 @@ class OrderedStreamingForkController extends ForkController {
        protected function consumeNoFork() {
                while ( !feof( $this->input ) ) {
                        $data = fgets( $this->input );
-                       if ( $data[ strlen( $data ) - 1 ] == "\n" ) {
+                       if ( substr( $data, -1 ) === "\n" ) {
+                               // Strip any final new line used to delimit lines of input.
+                               // The last line of input might not have it, though.
                                $data = substr( $data, 0, -1 );
                        }
-                       if ( strlen( $data ) !== 0 ) {
-                               $result = call_user_func( $this->workCallback, $data );
-                               fwrite( $this->output, "$result\n" );
+                       if ( $data === '' ) {
+                               continue;
                        }
+                       $result = call_user_func( $this->workCallback, $data );
+                       fwrite( $this->output, "$result\n" );
                }
        }
 
@@ -163,12 +166,12 @@ class OrderedStreamingForkController extends ForkController {
                                        $this->updateAvailableSockets( $sockets, $used, $sockets ? 0 : 5 );
                                } while ( !$sockets );
                        }
-                       // Strip the trailing \n. The last line of a file might not have a trailing
-                       // \n though
-                       if ( $data[ strlen( $data ) - 1 ] == "\n" ) {
+                       if ( substr( $data, - 1 ) === "\n" ) {
+                               // Strip any final new line used to delimit lines of input.
+                               // The last line of input might not have it, though.
                                $data = substr( $data, 0, -1 );
                        }
-                       if ( strlen( $data ) === 0 ) {
+                       if ( $data === '' ) {
                                continue;
                        }
                        $socket = array_pop( $sockets );