libasynql  3.2.0
Asynchronous MySQL access library for PocketMine plugins.
MysqlCredentials.php
Go to the documentation of this file.
1 <?php
2 
3 /*
4  * libasynql
5  *
6  * Copyright (C) 2018 SOFe
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  */
20 
21 declare(strict_types=1);
22 
23 namespace poggit\libasynql\mysqli;
24 
26 use mysqli;
29 use function strlen;
30 
33  private $host;
35  private $username;
37  private $password;
39  private $schema;
41  private $port;
43  private $socket;
44 
61  public static function fromArray(array $array, ?string $defaultSchema = null) : MysqlCredentials{
62  if(!isset($defaultSchema, $array["schema"])){
63  throw new ConfigException("The attribute \"schema\" is missing in the MySQL settings");
64  }
65  return new MysqlCredentials($array["host"] ?? "127.0.0.1", $array["username"] ?? "root",
66  $array["password"] ?? "", $array["schema"] ?? $defaultSchema, $array["port"] ?? 3306, $array["socket"] ?? "");
67  }
68 
79  public function __construct(string $host, string $username, string $password, string $schema, int $port = 3306, string $socket = ""){
80  $this->host = $host;
81  $this->username = $username;
82  $this->password = $password;
83  $this->schema = $schema;
84  $this->port = $port;
85  $this->socket = $socket;
86  }
87 
95  public function newMysqli() : mysqli{
96  $mysqli = @new mysqli($this->host, $this->username, $this->password, $this->schema, $this->port, $this->socket);
97  if($mysqli->connect_error){
98  throw new SqlError(SqlError::STAGE_CONNECT, $mysqli->connect_error);
99  }
100  return $mysqli;
101  }
102 
108  public function __toString() : string{
109  return "$this->username@$this->host:$this->port/schema,$this->socket";
110  }
111 
117  public function __debugInfo(){
118  return [
119  "host" => $this->host,
120  "username" => $this->username,
121  "password" => str_repeat("*", strlen($this->password)),
122  "schema" => $this->schema,
123  "port" => $this->port,
124  "socket" => $this->socket
125  ];
126  }
127 
128  public function jsonSerialize() : array{
129  return [
130  "host" => $this->host,
131  "username" => $this->username,
132  "password" => $this->password,
133  "schema" => $this->schema,
134  "port" => $this->port,
135  "socket" => $this->socket
136  ];
137  }
138 }
static fromArray(array $array, ?string $defaultSchema=null)
__construct(string $host, string $username, string $password, string $schema, int $port=3306, string $socket="")