Callback used to save the first bytes of the body content

@param resource $connection
@param string   $string

return integer
969577
public function writeCallback($connection, $string)
    {
        $this->content .= $string;

        if (!$this->mime) {
            $this->mime = finfo_buffer($this->finfo, $this->content);

            if (!in_array($this->mime, static::$mimetypes, true)) {
                $this->mime = null;

                return -1;
            }
        }

        if (!($info = getimagesizefromstring($this->content))) {
            return strlen($string);
        }

        $this->info = [
            'width' => $info[0],
            'height' => $info[1],
            'size' => $info[0] * $info[1],
            'mime' => $this->mime,
        ];

        return -1;
    }
640202
public function setConnection(Connection $connection)
    {
        if (! in_array($connection, $this->_connections, true)) {
            $this->_connections[] = $connection;
        }
    }
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;
        }
    }
386297
function (connection) {
            var headerStr = connection.getAllResponseHeaders(), headers = {};

            if (headerStr) {
                var headerLines = headerStr.split("\n");
                for (var i = 0; i < headerLines.length; i++) {
                    var delimitPos = headerLines[i].indexOf(":");
                    if (delimitPos != -1) {
                        // Trime headers
                        headers[headerLines[i].substring(0, delimitPos)] = headerLines[i].substring(delimitPos + 2).replace(/^\s+|\s+$/g, "");
                    }
                }
            }

            var response = {
                statusText : (connection.status == 1223) ? "No Content" : connection.statusText,
                getResponseHeader : headers,
                getAllResponseHeaders : headerLines,
                responseText : connection.responseText,
                responseXML : connection.responseXML
            };

            return response;
        }
1013551
public function setConnection($connection)
	{
		if (is_string($connection)) {
			$connection = Yii::$app->{$connection};
		}
		$this->_connection = $connection;
	}
760656
public function onMessage($connection, $data)
    {
        $uri  = parse_url($_SERVER['REQUEST_URI']);
        $path = isset($uri['path']) ? $uri['path'] : '/';

        $file = $this->root . $path;

        if (!is_file($file)) {
            $this->app->worker($connection, $data);
        } else {
            $this->sendFile($connection, $file);
        }
    }
488598
public function handshakeInput($buffer, $connection) 
    {
        $len = parent::input($buffer, $connection);
        
        if(!$len)  return 0;
        
        $req = new HttpReqeust();
        $req->loadRequest($buffer);
        
        if($req->headers->get('Connection') !== 'Upgrade'){
            throw new \Exception("Bad Connection", 412);
        }
        
        if($req->headers->get('Upgrade') !== 'websocket'){
            throw new \Exception("Bad Upgrade", 412);
        }
        
        $seckey = $req->headers->get('Sec-Websocket-Key');
        if(!$seckey ||  base64_encode(base64_decode($seckey)) !== $seckey){
            throw new \Exception("Bad Websocket-Key", 412);
        }
        
        return $len;
    }
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;
    }
360877
public static function input($recv_buffer, TcpConnection $connection)
    {
        if (!strpos($recv_buffer, "\r\n\r\n")) {
            // Judge whether the package length exceeds the limit.
            if (strlen($recv_buffer) >= $connection->maxPackageSize) {
                $connection->close();
                return 0;
            }
            return 0;
        }

        list($header,) = explode("\r\n\r\n", $recv_buffer, 2);
        $method = substr($header, 0, strpos($header, ' '));

        if(in_array($method, static::$methods)) {
            return static::getRequestSize($header, $method);
        }else{
            $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n", true);
            return 0;
        }
    }
1117435
public function restoreBackup(Connection $connection, $hash)
    {
        $platform     = $connection->getDatabasePlatform();
        $filename     = $this->getBackupFile($hash);
        $database     = $connection->getDatabase();
        $params       = $connection->getParams();
        $platformName = $platform->getName();

        $this->getPlatformBackup($platformName)->restore($database, $filename, $params);
    }
1096575
protected static function _checkConnection( &$parameters = array(), &$connection = null )
    {
        //	Allow laziness
        if ( $parameters instanceof \PDO )
        {
            $connection = $parameters;
            $parameters = array();
        }

        self::setConnection( $_db = $connection ?: self::$_connection );

        //	Connect etc...
        if ( empty( $_db ) || !( ( $_db instanceof \PDO ) && $_db->getAttribute( \PDO::ATTR_CONNECTION_STATUS ) ) )
        {
            throw new \Kisma\Core\Exceptions\StorageException(
                'Cannot proceed until a database connection has been established. Try setting the "connection" property.'
            );
        }

        return $_db;
    }
172305
public function write(string $data): int
    {
        $length = fputs($this->resource, $data, strlen($data));
        if (false === $length) {
            if (stream_get_meta_data($this->resource)['timed_out']) {
                throw new Timeout(
                        'Writing of ' . strlen($data) . ' bytes failed:'
                        . ' timeout of ' . $this->timeout . ' seconds exceeded'
                );
            }

            throw new ConnectionFailure(
                    'Writing of ' . strlen($data) . ' bytes failed.'
            );
        }

        return $length;
    }
968995
public static function write(String $file, String $data) : Int
    {
        return file_put_contents(Info::rpath($file), $data);
    }
172071
private function setPreferredCharsetCollation(Connection $connection)
    {
        // Let's get the currently configured connection charset and collation
        $connectionParams = $connection->getParams();
        $connectionCharset = isset($connectionParams['character_set']) ? $this->characterSetCollationResolver->normalizeCharacterSet($connectionParams['character_set']) : '';
        $connectionCollation = isset($connectionParams['collation']) ? $this->characterSetCollationResolver->normalizeCollation($connectionParams['collation']) : '';
        try {
            list($characterSet, $collation) = $this->characterSetCollationResolver->resolveCharacterSetAndCollation($connection);
        } catch (CharacterSetCollationException $x) {
            // Unsupported character set and/or collation
            return $connection;
        }
        if ($connectionCharset === $characterSet && $connectionCollation === $collation) {
            // No changes required
            return $connection;
        }

        return $this->reconfigureCharacterSetCollation($connection, $characterSet, $collation);
    }
270629
public function initConnection(Connection $connection)
    {
        /** @var $pdo PDO */
        $pdo = $connection->getWrappedConnection();
        $this->fkSupported = version_compare('3.6.19', $pdo->getAttribute(PDO::ATTR_SERVER_VERSION)) < 0;
        $pdo->exec($this->buildEnableForeignKeysQuery());
    }
328765
private void initSavepoints(final Connection connection) {
		for (String savepointName : savepointNames) {
			try {
				savepointMap.put(savepointName, connection.setSavepoint(savepointName));
			} catch (SQLException e) {
				throw new UroborosqlSQLException(e);
			}
		}
	}
937372
private function writeStringToStream(string $string, $target) : void
    {
        if (@fwrite($target, $string) === false) {
            throw new DB2Exception('Could not write string to temporary file: ' . error_get_last()['message']);
        }
    }