返回包长度

@param string $buffer
@return int return current package length
334742
public static function input($buffer)
    {
        if (strlen($buffer) < self::HEAD_LEN) {
            return 0;
        }
        $data = unpack("Npack_len", $buffer);
        return $data['pack_len'];
    }
696737
public function write($buffer)
    {
        $buffer = (string) $buffer;
        $bufLen = Binary::safeStrlen($buffer);

        $socket = $this->getSocket();
        $written = 0;

        while ($written < $bufLen) {
            // PHP's fwrite does not behave nice in regards to errors, so we wrap
            // it with a temporary error handler and treat every warning/notice as
            // a error
            $failed = false;
            $errorMessage = "Failed to write to socket";
            set_error_handler(function ($errno, $errstr) use (&$failed, &$errorMessage) {
                $failed = true;
                $errorMessage .= ": $errstr ($errno)";
            });
            $byteCount = fwrite($socket, Binary::safeSubstr($buffer, $written));
            restore_error_handler();

            if ($byteCount === 0 && defined('HHVM_VERSION')) {
                $failed = true;
            }

            if ($failed || $byteCount === false) {
                throw new \RuntimeException($errorMessage);
            }

            $written += $byteCount;
        }


        return $written;
    }
484589
public function output($buffer) {
        if (!$buffer && !$this->__result) {
            return '';
        }

        $out = '';
        // Always include the output generated by the expression first
        if ($buffer) {
            $out .= Garp_Cli::lineOut($buffer, null, true, false);
        }

        // And follow-up with the populated result, if any
        if ($this->__result) {
            // Try to format as user-friendly as possible
            $isObjWithToArray = is_object($this->__result) &&
                method_exists($this->__result, 'toArray');
            $this->__result = $isObjWithToArray ? $this->__result->toArray() : $this->__result;
            $this->__result = var_export($this->__result, true);
            $out .= Garp_Cli::lineOut($this->__result, Garp_Cli::BLUE, true, false);
        }

        return $out;
    }
1182710
public static function getLength($str)
    {
        $bytes = 0;
        $chars = 0;
        while ($bytes < strlen($str)) {
            $charBytes = 1;
            if ((ord($str[$bytes]) & 0xC0) == 0xC0) {
                $charBytes++;
                if (ord($str[$bytes]) & 0x20 ) {
                    $charBytes++;
                    if (ord($str[$bytes]) & 0x10 ) {
                        $charBytes++;
                    }
                }
            }

            if ($bytes + $charBytes > strlen($str)) {
                // wrong character
                break;
            }

            $chars++;
            $bytes += $charBytes;
        }

        return $chars;
    }
340918
public static function input($buffer, ConnectionInterface $connection)
    {
        // Receive length.
        $recv_len = strlen($buffer);
        // We need more data.
        if ($recv_len < 6) {
            return 0;
        }

        // Has not yet completed the handshake.
        if (empty($connection->websocketHandshake)) {
            return static::dealHandshake($buffer, $connection);
        }

        // Buffer websocket frame data.
        if ($connection->websocketCurrentFrameLength) {
            // We need more frame data.
            if ($connection->websocketCurrentFrameLength > $recv_len) {
                // Return 0, because it is not clear the full packet length, waiting for the frame of fin=1.
                return 0;
            }
        } else {
            $firstbyte    = ord($buffer[0]);
            $secondbyte   = ord($buffer[1]);
            $data_len     = $secondbyte & 127;
            $is_fin_frame = $firstbyte >> 7;
            $masked       = $secondbyte >> 7;

            if (!$masked) {
                Worker::safeEcho("frame not masked so close the connection\n");
                $connection->close();
                return 0;
            }

            $opcode       = $firstbyte & 0xf;
            switch ($opcode) {
                case 0x0:
                    break;
                // Blob type.
                case 0x1:
                    break;
                // Arraybuffer type.
                case 0x2:
                    break;
                // Close package.
                case 0x8:
                    // Try to emit onWebSocketClose callback.
                    if (isset($connection->onWebSocketClose) || isset($connection->worker->onWebSocketClose)) {
                        try {
                            call_user_func(isset($connection->onWebSocketClose)?$connection->onWebSocketClose:$connection->worker->onWebSocketClose, $connection);
                        } catch (\Exception $e) {
                            Worker::log($e);
                            exit(250);
                        } catch (\Error $e) {
                            Worker::log($e);
                            exit(250);
                        }
                    } // Close connection.
                    else {
                        $connection->close("\x88\x02\x27\x10", true);
                    }
                    return 0;
                // Ping package.
                case 0x9:
                    break;
                // Pong package.
                case 0xa:
                    break;
                // Wrong opcode. 
                default :
                    Worker::safeEcho("error opcode $opcode and close websocket connection. Buffer:" . bin2hex($buffer) . "\n");
                    $connection->close();
                    return 0;
            }

            // Calculate packet length.
            $head_len = 6;
            if ($data_len === 126) {
                $head_len = 8;
                if ($head_len > $recv_len) {
                    return 0;
                }
                $pack     = unpack('nn/ntotal_len', $buffer);
                $data_len = $pack['total_len'];
            } else {
                if ($data_len === 127) {
                    $head_len = 14;
                    if ($head_len > $recv_len) {
                        return 0;
                    }
                    $arr      = unpack('n/N2c', $buffer);
                    $data_len = $arr['c1']*4294967296 + $arr['c2'];
                }
            }
            $current_frame_length = $head_len + $data_len;

            $total_package_size = strlen($connection->websocketDataBuffer) + $current_frame_length;
            if ($total_package_size > $connection->maxPackageSize) {
                Worker::safeEcho("error package. package_length=$total_package_size\n");
                $connection->close();
                return 0;
            }

            if ($is_fin_frame) {
                if ($opcode === 0x9) {
                    if ($recv_len >= $current_frame_length) {
                        $ping_data = static::decode(substr($buffer, 0, $current_frame_length), $connection);
                        $connection->consumeRecvBuffer($current_frame_length);
                        $tmp_connection_type = isset($connection->websocketType) ? $connection->websocketType : static::BINARY_TYPE_BLOB;
                        $connection->websocketType = "\x8a";
                        if (isset($connection->onWebSocketPing) || isset($connection->worker->onWebSocketPing)) {
                            try {
                                call_user_func(isset($connection->onWebSocketPing)?$connection->onWebSocketPing:$connection->worker->onWebSocketPing, $connection, $ping_data);
                            } catch (\Exception $e) {
                                Worker::log($e);
                                exit(250);
                            } catch (\Error $e) {
                                Worker::log($e);
                                exit(250);
                            }
                        } else {
                            $connection->send($ping_data);
                        }
                        $connection->websocketType = $tmp_connection_type;
                        if ($recv_len > $current_frame_length) {
                            return static::input(substr($buffer, $current_frame_length), $connection);
                        }
                    }
                    return 0;
                } else if ($opcode === 0xa) {
                    if ($recv_len >= $current_frame_length) {
                        $pong_data = static::decode(substr($buffer, 0, $current_frame_length), $connection);
                        $connection->consumeRecvBuffer($current_frame_length);
                        $tmp_connection_type = isset($connection->websocketType) ? $connection->websocketType : static::BINARY_TYPE_BLOB;
                        $connection->websocketType = "\x8a";
                        // Try to emit onWebSocketPong callback.
                        if (isset($connection->onWebSocketPong) || isset($connection->worker->onWebSocketPong)) {
                            try {
                                call_user_func(isset($connection->onWebSocketPong)?$connection->onWebSocketPong:$connection->worker->onWebSocketPong, $connection, $pong_data);
                            } catch (\Exception $e) {
                                Worker::log($e);
                                exit(250);
                            } catch (\Error $e) {
                                Worker::log($e);
                                exit(250);
                            }
                        }
                        $connection->websocketType = $tmp_connection_type;
                        if ($recv_len > $current_frame_length) {
                            return static::input(substr($buffer, $current_frame_length), $connection);
                        }
                    }
                    return 0;
                }
                return $current_frame_length;
            } else {
                $connection->websocketCurrentFrameLength = $current_frame_length;
            }
        }

        // Received just a frame length data.
        if ($connection->websocketCurrentFrameLength === $recv_len) {
            static::decode($buffer, $connection);
            $connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
            $connection->websocketCurrentFrameLength = 0;
            return 0;
        } // The length of the received data is greater than the length of a frame.
        elseif ($connection->websocketCurrentFrameLength < $recv_len) {
            static::decode(substr($buffer, 0, $connection->websocketCurrentFrameLength), $connection);
            $connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
            $current_frame_length                    = $connection->websocketCurrentFrameLength;
            $connection->websocketCurrentFrameLength = 0;
            // Continue to read next frame.
            return static::input(substr($buffer, $current_frame_length), $connection);
        } // The length of the received data is less than the length of a frame.
        else {
            return 0;
        }
    }
566185
public static function len(string $string): int
    {
        if (false === $encoding = \mb_detect_encoding($string, null, true)) {
            return \strlen($string);
        }

        return \mb_strwidth($string, $encoding);
    }
220955
public function length($str, $encoding = null)
	{
		$encoding or $encoding = $this->encoding;

		return function_exists('mb_strlen')
			? mb_strlen($str, $encoding)
			: strlen($str);
	}
393815
public function length($min, $max = PHP_INT_MAX)
    {
        return $this->markErrorIf(strlen($this->value) < $min || strlen($this->value) > $max);
    }
1353386
public function consumeDecimalValue(Buffer $buffer)
    {
        $scale = $buffer->consumeUint8();
        $value = $buffer->consumeUint32();
        return $value * pow(10, $scale);
    }
995770
private function _getActualLength ( $text ) {
        $convertedText = $this->_convertTagsToEscapeSequences($text);
        $strippedText = $this->_stripEscapeSequences($convertedText);
        $length = mb_strlen($strippedText, 'utf-8');
        return $length;
    }
1123992
public function getLength(): int
    {
        switch (\gettype($this->data)) {
            case 'array':
            case 'object':
                if (\is_array($this->data) || $this->data instanceof \Countable) {
                    return \count($this->data);
                }
                break;

            case 'string':
                return \strlen($this->data);
                break;
        }

        return -1;
    }
735121
public static function input($buffer, TcpConnection $connection)
    {
        // Judge whether the package length exceeds the limit.
        if (strlen($buffer) >= $connection->maxPackageSize) {
            $connection->close();
            return 0;
        }
        //  Find the position of  "\n".
        $pos = strpos($buffer, "\n");
        // No "\n", packet length is unknown, continue to wait for the data so return 0.
        if ($pos === false) {
            return 0;
        }
        // Return the current package length.
        return $pos + 1;
    }
450667
private function getLength(string $string) : ?int
    {
        if (extension_loaded('mbstring') && ! defined('NO_PHP_EXTENSIONS')) { // constant used for tests
            if (! mb_check_encoding($string, 'UTF-8')) {
                return null;
            }

            return mb_strlen($string, 'UTF-8');
        }

        $charLength = 0;

        $length = strlen($string);

        for ($i = 0; $i < $length; $i++) {
            $charLength++;

            $char = ord($string[$i]);

            if ($char < 0x80) { // 0bbbbbbb
                continue;
            }

            if (($char & 0xE0) === 0xC0) { // 110bbbbb
                $n = 1;
            } elseif (($char & 0xF0) === 0xE0) { // 1110bbbb
                $n = 2;
            } elseif (($char & 0xF0) === 0xF0) { // 11110bbb
                $n = 3;
            } else { // invalid char
                return null;
            }

            for ($j = 0; $j < $n; $j++) {
                if (++$i === $length) { // unexpected end of string
                    return null;
                }

                if ((ord($string[$i]) & 0xC0) !== 0x80) { // does not match 10bbbbbb
                    return null;
                }
            }
        }

        return $charLength;
    }
11716
public static long length(DataBuffer buffer) {
        long ret = 1;
        val rr = buffer.asLong();
        DataBuffer shape = Shape.shapeOf(buffer);
        int rank = Shape.rank(buffer);
        for (int i = 0; i < rank; i++)
            ret *= shape.getLong(i);

        return ret;
    }
785577
protected function openSslIvLength(string $method): int
    {
        $ivLength = $this->openSslIvLengthImpl($method);

        $ivLength !== false ?: $this->throwException(new CryptException($this->getErrorMessage()));

        return $ivLength;
    }
973342
public static function length($str)
    {
        if (empty($str)) {
            return '0';
        }

        if ((string)$str === '0') {
            return '1';
        }

        if (\function_exists('mb_strlen')) {
            return mb_strlen($str, 'utf-8');
        }

        preg_match_all('/./u', $str, $arr);

        return \count($arr[0]);
    }
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;
    }