Skip to content

Commit

Permalink
增加权限类
Browse files Browse the repository at this point in the history
  • Loading branch information
limingxinleo committed Jul 14, 2024
1 parent 04f90b2 commit ced9bde
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
54 changes: 54 additions & 0 deletions src/Privilege.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/

namespace Fan\SqlImport;

use Hyperf\Database\Connectors\ConnectionFactory;
use Psr\Container\ContainerInterface;

class Privilege
{
protected ConnectionFactory $factory;

public function __construct(protected ContainerInterface $container)
{
$this->factory = $this->container->get(ConnectionFactory::class);
}

public function createUser(string $name, string $host, string $password, array $config): bool
{
$pdo = $this->factory->make($config)->getPdo();

$sql = sprintf("CREATE USER '%s'@'%s' IDENTIFIED BY '%s';", $name, $host, $password);

if ($pdo->exec($sql) !== false) {
$pdo->exec('FLUSH PRIVILEGES;');
return true;
}

return false;
}

public function grant(string $name, string $host, string $database, string $table, array $config): bool
{
$pdo = $this->factory->make($config)->getPdo();

$sql = sprintf("GRANT ALL PRIVILEGES ON %s.%s TO '%s'@'%s';", $database, $table, $name, $host);

if ($pdo->exec($sql) !== false) {
$pdo->exec('FLUSH PRIVILEGES;');
return true;
}

return false;
}
}
23 changes: 23 additions & 0 deletions tests/Cases/ImportTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
namespace HyperfTest\Cases;

use Fan\SqlImport\Importer;
use Fan\SqlImport\Privilege;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Database\Connectors\ConnectionFactory;
use Hyperf\Database\Connectors\MySqlConnector;
Expand Down Expand Up @@ -66,6 +67,28 @@ public function testLoadPath()
$this->assertTrue($res->isSuccess);
}

public function testPrivilegeCreateUser()
{
$config = [
'driver' => 'mysql',
'host' => '127.0.0.1',
'port' => 3307,
'database' => 'test',
'username' => 'root',
'password' => '',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
];

$pri = new Privilege($this->getContainer());
$res = $pri->createUser('test', '%', '', $config);
$this->assertTrue($res);

$res = $pri->grant('test', '%', '*', '*', $config);
$this->assertTrue($res);
}

public function getContainer()
{
$container = Mockery::mock(ContainerInterface::class);
Expand Down

0 comments on commit ced9bde

Please sign in to comment.