Checks if the buffer contains a valid frame to parse

@param string $buffer Binary buffer

@return bool
779639
public static function hasFrame(string $buffer): bool
    {
        $bufferLength = strlen($buffer);
        if ($bufferLength < FCGI::HEADER_LEN) {
            return false;
        }

        $fastInfo = unpack(FCGI::HEADER_FORMAT, $buffer);
        if ($bufferLength < FCGI::HEADER_LEN + $fastInfo['contentLength'] + $fastInfo['paddingLength']) {
            return false;
        }

        return true;
    }
656334
public function returnBuffer($buffer = null)
    {
        if ($this->isBufferReturned)
        {
            return $buffer;
        }

        $this->apply($this->applyOnOutput);

        if (ob_get_level() and ! empty($this->errorString))
        {
            # prepend any errors to the buffer string (any errors that were
            # echoed will have been lost during an ob_start callback)
            $buffer = $this->errorString . $buffer;
        }

        # if we were called as part of ob_start, make note of this
        # (avoid doing redundent work if called again)
        $this->isBufferReturned = true;

        return $buffer;
    }
828502
protected function processStatus(Buffer $buffer)
    {
        // Set the result to a new result instance
        $result = new Result();

        // Lets peek and see if the data starts with a \
        if ($buffer->lookAhead(1) == '\\') {
            // Burn the first one
            $buffer->skip(1);
        }

        // Explode the data
        $data = explode('\\', $buffer->getBuffer());

        // No longer needed
        unset($buffer);

        $itemCount = count($data);

        // Now lets loop the array
        for ($x = 0; $x < $itemCount; $x += 2) {
            // Set some local vars
            $key = $data[$x];
            $val = $data[$x + 1];

            if (in_array($key, ['challenge'])) {
                continue; // skip
            }

            // Regular variable so just add the value.
            $result->add($key, $val);
        }

        /*var_dump($data);
        var_dump($result->fetch());

        exit;*/

        return $result->fetch();
    }
729640
public function write($buffer)
    {
        if ($this->driver === self::DRIVER_SOCKET) {
            return socket_write($this->sock, $buffer, \strlen($buffer));
        } else {
            // $buffer = str_replace(chr(255), chr(255) . chr(255), $buffer);
            return fwrite($this->sock, $buffer);
        }
    }
1246785
private function handleBuffer($buffer) {
        $error = error_get_last();

        if ( $error ) {
            $matches = [];
            preg_match('/\: (.*) in /', $error['message'], $matches);
            $message = key_exists(1, $matches) ? $matches[1] : $error['message'];
            
            /* @var $response \PowerOn\Network\Response */
            $response = $this->_container['Response'];
            
            if ( DEV_ENVIRONMENT ) {
                $response->setHeader(500);
                return 
                      '<header>'
                        . '<h1>Error: ' . $message . '</h1>'
                        . '<h2>' . $error['file'] . ' (' . $error['line'] . ')</h2>'
                    . '</header>';
            } else {
                /* @var $logger \Monolog\Logger */
                $logger = $this->_container['Logger'];
                $logger->error($message, [
                    'type' => $error['type'],
                    'file' => $error['file'],
                    'line' => $error['line']
                ]);

                /* @var $router \AltoRouter */
                $router = $this->_container['AltoRouter'];

                $response->redirect( $router->generate('poweron_error', ['error' => 500]) );
            }
        }

        return $buffer;
    }
268676
public function consumeFrame(Buffer $buffer)
    {
        // not enough data
        if ($buffer->getLength() < 7) {
            return null;
        }

        $type = $buffer->readUint8(0);
        $channel = $buffer->readUint16(1);
        $payloadSize = $buffer->readUint32(3);
        $payloadOffset = 7; // type:uint8=>1 + channel:uint16=>2 + payloadSize:uint32=>4 ==> 7

        // not enough data
        if ($buffer->getLength() < $payloadOffset + $payloadSize + 1 /* frame end byte */) {
            return null;
        }

        $buffer->consume(7);
        $payload = $buffer->consume($payloadSize);
        $frameEnd = $buffer->consumeUint8();

        if ($frameEnd !== Constants::FRAME_END) {
            throw new ProtocolException(sprintf("Frame end byte invalid - expected 0x%02x, got 0x%02x.", Constants::FRAME_END, $frameEnd));
        }

        $frameBuffer = new Buffer($payload);

        if ($type === Constants::FRAME_METHOD) {
            $frame = $this->consumeMethodFrame($frameBuffer);

        } elseif ($type === Constants::FRAME_HEADER) {
            // see https://github.com/pika/pika/blob/master/pika/spec.py class BasicProperties
            $frame = new ContentHeaderFrame();
            $frame->classId = $frameBuffer->consumeUint16();
            $frame->weight = $frameBuffer->consumeUint16();
            $frame->bodySize = $frameBuffer->consumeUint64();
            $frame->flags = $flags = $frameBuffer->consumeUint16();

            if ($flags & ContentHeaderFrame::FLAG_CONTENT_TYPE) {
                $frame->contentType = $frameBuffer->consume($frameBuffer->consumeUint8());
            }

            if ($flags & ContentHeaderFrame::FLAG_CONTENT_ENCODING) {
                $frame->contentEncoding = $frameBuffer->consume($frameBuffer->consumeUint8());
            }

            if ($flags & ContentHeaderFrame::FLAG_HEADERS) {
                $frame->headers = $this->consumeTable($frameBuffer);
            }

            if ($flags & ContentHeaderFrame::FLAG_DELIVERY_MODE) {
                $frame->deliveryMode = $frameBuffer->consumeUint8();
            }

            if ($flags & ContentHeaderFrame::FLAG_PRIORITY) {
                $frame->priority = $frameBuffer->consumeUint8();
            }

            if ($flags & ContentHeaderFrame::FLAG_CORRELATION_ID) {
                $frame->correlationId = $frameBuffer->consume($frameBuffer->consumeUint8());
            }

            if ($flags & ContentHeaderFrame::FLAG_REPLY_TO) {
                $frame->replyTo = $frameBuffer->consume($frameBuffer->consumeUint8());
            }

            if ($flags & ContentHeaderFrame::FLAG_EXPIRATION) {
                $frame->expiration = $frameBuffer->consume($frameBuffer->consumeUint8());
            }

            if ($flags & ContentHeaderFrame::FLAG_MESSAGE_ID) {
                $frame->messageId = $frameBuffer->consume($frameBuffer->consumeUint8());
            }

            if ($flags & ContentHeaderFrame::FLAG_TIMESTAMP) {
                $frame->timestamp = $this->consumeTimestamp($frameBuffer);
            }

            if ($flags & ContentHeaderFrame::FLAG_TYPE) {
                $frame->typeHeader = $frameBuffer->consume($frameBuffer->consumeUint8());
            }

            if ($flags & ContentHeaderFrame::FLAG_USER_ID) {
                $frame->userId = $frameBuffer->consume($frameBuffer->consumeUint8());
            }

            if ($flags & ContentHeaderFrame::FLAG_APP_ID) {
                $frame->appId = $frameBuffer->consume($frameBuffer->consumeUint8());
            }

            if ($flags & ContentHeaderFrame::FLAG_CLUSTER_ID) {
                $frame->clusterId = $frameBuffer->consume($frameBuffer->consumeUint8());
            }

        } elseif ($type === Constants::FRAME_BODY) {
            $frame = new ContentBodyFrame();
            $frame->payload = $frameBuffer->consume($frameBuffer->getLength());

        } elseif ($type === Constants::FRAME_HEARTBEAT) {
            $frame = new HeartbeatFrame();
            if (!$frameBuffer->isEmpty()) {
                throw new ProtocolException("Heartbeat frame must be empty.");
            }

        } else {
            throw new ProtocolException("Unhandled frame type '{$type}'.");
        }

        if (!$frameBuffer->isEmpty()) {
            throw new ProtocolException("Frame buffer not entirely consumed.");
        }

        /** @var AbstractFrame $frame */
        $frame->type = $type;
        $frame->channel = $channel;
        $frame->payloadSize = $payloadSize;
        // DO NOT CALL! ContentBodyFrame uses payload for body
        // $frame->setPayload($payload);

        return $frame;
    }
694860
public static function minify($buffer)
    {
        $search = [
            // Strip whitespaces after tags, except space
            '/\>[^\S]+/s',

            // Strip whitespaces before tags, except space
            '/[^\S]+\</s',

            // Shorten multiple whitespace sequences
            '/(\s)+/s',
        ];

        $replace = [
            '>',
            '<',
            '\\1',
        ];

        $buffer = preg_replace($search, $replace, $buffer);

        return $buffer;
    }
420017
protected function parseServerParameters(Buffer &$buffer)
    {

        // Init the parsed data array
        $parsed = [];

        // Read the number of parameters to parse
        $parameterSize = $buffer->readInt32Signed();

        // Iterate over the parameter size
        for ($i = 0; $i < $parameterSize; $i++) {
            // Read the type of return this is
            $dataType = $buffer->readInt8Signed();

            switch ($dataType) {
                // 32-bit int
                case 1:
                    $parsed[$i] = $buffer->readInt32Signed();
                    break;

                // 64-bit int
                case 2:
                    $parsed[$i] = $buffer->readInt64();
                    break;

                // Float
                case 3:
                    $parsed[$i] = $buffer->readFloat32();
                    break;

                // String
                case 4:
                    // The first 2 bytes are the string length
                    $strLength = $buffer->readInt16Signed();

                    // Read the above length from the buffer
                    $parsed[$i] = $buffer->read($strLength);

                    unset($strLength);
                    break;

                // Boolean
                case 5:
                    $parsed[$i] = (bool)$buffer->readInt8Signed();
                    break;

                // 8-bit int
                case 6:
                    $parsed[$i] = $buffer->readInt8Signed();
                    break;

                // 16-bit int
                case 7:
                    $parsed[$i] = $buffer->readInt16Signed();
                    break;

                // Array
                case 8:
                    // Not implemented
                    throw new Exception("StarMade array parsing is not implemented!");
            }
        }

        return $parsed;
    }
109621
public static function containsUCS2Characters($string)
    {
        $GSMCharsetAsString = implode(array_keys(GSMCharset::$GSMCharset));

        foreach (self::mb_str_split($string) as $char) {
            if (mb_strpos($GSMCharsetAsString, $char) === false) {
                return true;
            }
        }

        return false;
    }
1156017
public function afterScript(Buffer $buffer)
    {
        $buffer->write(sprintf('$z->pop(\'%s\');', $this->key));
        $buffer->write(sprintf('$z->pop(\'%s\');', $this->value));
        $buffer->indent(-1);
        $buffer->writeln('}');
    }
62620
public function equals(Buffer $other)
    {
        return ($other->getSize() === $this->getSize()
             && $other->getBinary() === $this->getBinary());
    }
295635
public function statements($buffer)
    {
        $result = $this->_createResult($buffer);
        
        while (strlen($result->buffer) > 0) {
            $this->_resetResult($result);
            
            if ($result->state == '<<<') {
                if (!$this->_initializeHeredoc($result)) {
                    continue;
                }
            }
            
            $rules = array(
                '_scanUse',
                '_scanEscapedChar',
                '_scanRegion',
                '_scanStateEntrant',
                '_scanWsp',
                '_scanChar'
            );
            
            foreach ($rules as $method) {
                if ($this->$method($result)) {
                    break;
                }
            }
            
            if ($result->stop) {
                break;
            }
        }
        
        if (!empty($result->statements) && trim($result->stmt) === '' && strlen($result->buffer) == 0) {
            $this->_combineStatements($result);
            $this->_prepareForDebug($result);
            return $result->statements;
        }
    }
185517
private function readMessages(string $buffer) : int
    {
        $emitted_messages = 0;
        $i = 0;
        while (($buffer[$i] ?? '') !== '') {
            $this->buffer .= $buffer[$i++];
            switch ($this->parsing_mode) {
                case self::PARSE_HEADERS:
                    if ($this->buffer === "\r\n") {
                        $this->parsing_mode = self::PARSE_BODY;
                        $this->content_length = (int)$this->headers['Content-Length'];
                        $this->buffer = '';
                    } elseif (substr($this->buffer, -2) === "\r\n") {
                        $parts = explode(':', $this->buffer);
                        $this->headers[$parts[0]] = trim($parts[1]);
                        $this->buffer = '';
                    }
                    break;
                case self::PARSE_BODY:
                    if (strlen($this->buffer) === $this->content_length) {
                        if (!$this->is_accepting_new_requests) {
                            // If we fork, don't read any bytes in the input buffer from the worker process.
                            $this->emitClose();
                            return $emitted_messages;
                        }
                        // MessageBody::parse can throw an Error, maybe log an error?
                        try {
                            $msg = new Message(MessageBody::parse($this->buffer), $this->headers);
                        } catch (Exception $_) {
                            $msg = null;
                        }
                        if ($msg) {
                            $emitted_messages++;
                            $this->emit('message', [$msg]);
                            /** @psalm-suppress DocblockTypeContradiction */
                            if (!$this->is_accepting_new_requests) {
                                // If we fork, don't read any bytes in the input buffer from the worker process.
                                $this->emitClose();
                                return $emitted_messages;
                            }
                        }
                        $this->parsing_mode = self::PARSE_HEADERS;
                        $this->headers = [];
                        $this->buffer = '';
                    }
                    break;
            }
        }
        return $emitted_messages;
    }
137449
private function _minifyHtml($buffer) {
        $search = ['/\>[^\S ]+/s', '/[^\S ]+\</s', '/\>(\s)+/s', '/(\s)+\</s'];
        $replace = ['> ', ' <', '> ', ' <'];
        $buffer = preg_replace($search, $replace, $buffer);

        return $buffer;
    }
446069
protected function isCorrect(string $sentence): bool
    {
        $bracketsStack = [];
        $sentenceChars = str_split($sentence);
        $openBrackets = array_keys($this->brackets);
        foreach ($sentenceChars as $char) {
            if (in_array($char, $openBrackets)) {
                $bracketsStack[] = $this->brackets[$char];
                continue;
            }

            if (in_array($char, $this->brackets)) {
                $idx = array_search($char, $bracketsStack);
                if ($idx !== false) {
                    unset($bracketsStack[$idx]);
                    continue;
                }
                return false;
            }
        }

        return count($bracketsStack) === 0;
    }
533223
public function appendFrame(AbstractFrame $frame, Buffer $buffer)
    {
        if ($frame instanceof MethodFrame && $frame->payload !== null) {
            // payload already supplied

        } elseif ($frame instanceof MethodFrame) {
            $frameBuffer = new Buffer();
            $this->appendMethodFrame($frame, $frameBuffer);
            $frame->payloadSize = $frameBuffer->getLength();
            $frame->payload = $frameBuffer;

        } elseif ($frame instanceof ContentHeaderFrame) {
            $frameBuffer = new Buffer();
            // see https://github.com/pika/pika/blob/master/pika/spec.py class BasicProperties
            $frameBuffer->appendUint16($frame->classId);
            $frameBuffer->appendUint16($frame->weight);
            $frameBuffer->appendUint64($frame->bodySize);

            $flags = $frame->flags;

            $frameBuffer->appendUint16($flags);

            if ($flags & ContentHeaderFrame::FLAG_CONTENT_TYPE) {
                $frameBuffer->appendUint8(strlen($frame->contentType));
                $frameBuffer->append($frame->contentType);
            }

            if ($flags & ContentHeaderFrame::FLAG_CONTENT_ENCODING) {
                $frameBuffer->appendUint8(strlen($frame->contentEncoding));
                $frameBuffer->append($frame->contentEncoding);
            }

            if ($flags & ContentHeaderFrame::FLAG_HEADERS) {
                $this->appendTable($frame->headers, $frameBuffer);
            }

            if ($flags & ContentHeaderFrame::FLAG_DELIVERY_MODE) {
                $frameBuffer->appendUint8($frame->deliveryMode);
            }

            if ($flags & ContentHeaderFrame::FLAG_PRIORITY) {
                $frameBuffer->appendUint8($frame->priority);
            }

            if ($flags & ContentHeaderFrame::FLAG_CORRELATION_ID) {
                $frameBuffer->appendUint8(strlen($frame->correlationId));
                $frameBuffer->append($frame->correlationId);
            }

            if ($flags & ContentHeaderFrame::FLAG_REPLY_TO) {
                $frameBuffer->appendUint8(strlen($frame->replyTo));
                $frameBuffer->append($frame->replyTo);
            }

            if ($flags & ContentHeaderFrame::FLAG_EXPIRATION) {
                $frameBuffer->appendUint8(strlen($frame->expiration));
                $frameBuffer->append($frame->expiration);
            }

            if ($flags & ContentHeaderFrame::FLAG_MESSAGE_ID) {
                $frameBuffer->appendUint8(strlen($frame->messageId));
                $frameBuffer->append($frame->messageId);
            }

            if ($flags & ContentHeaderFrame::FLAG_TIMESTAMP) {
                $this->appendTimestamp($frame->timestamp, $frameBuffer);
            }

            if ($flags & ContentHeaderFrame::FLAG_TYPE) {
                $frameBuffer->appendUint8(strlen($frame->typeHeader));
                $frameBuffer->append($frame->typeHeader);
            }

            if ($flags & ContentHeaderFrame::FLAG_USER_ID) {
                $frameBuffer->appendUint8(strlen($frame->userId));
                $frameBuffer->append($frame->userId);
            }

            if ($flags & ContentHeaderFrame::FLAG_APP_ID) {
                $frameBuffer->appendUint8(strlen($frame->appId));
                $frameBuffer->append($frame->appId);
            }

            if ($flags & ContentHeaderFrame::FLAG_CLUSTER_ID) {
                $frameBuffer->appendUint8(strlen($frame->clusterId));
                $frameBuffer->append($frame->clusterId);
            }

            $frame->payloadSize = $frameBuffer->getLength();
            $frame->payload = $frameBuffer;

        } elseif ($frame instanceof ContentBodyFrame) {
            // body frame's payload is already loaded

        } elseif ($frame instanceof HeartbeatFrame) {
            // heartbeat frame is empty

        } else {
            throw new ProtocolException("Unhandled frame '" . get_class($frame) . "'.");
        }

        $buffer->appendUint8($frame->type);
        $buffer->appendUint16($frame->channel);
        $buffer->appendUint32($frame->payloadSize);
        $buffer->append($frame->payload);
        $buffer->appendUint8(Constants::FRAME_END);
    }
27224
public function has($event)
    {
        list($event, $payload) = $this->parseEventAndPayload($event, []);

        return array_key_exists($event, $this->listeners);
    }