Skip to content

Commit

Permalink
Use Cycle ORM (#23)
Browse files Browse the repository at this point in the history
Co-authored-by: roxblnfk <[email protected]>
  • Loading branch information
samdark and roxblnfk authored Jan 22, 2020
2 parents 70433e3 + 4ebc30a commit 08bb6ad
Show file tree
Hide file tree
Showing 7 changed files with 162 additions and 38 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@
"yiisoft/var-dumper": "^3.0@dev",
"yiisoft/view": "^3.0@dev",
"yiisoft/yii-console": "^3.0@dev",
"yiisoft/yii-web": "^3.0@dev"
"yiisoft/yii-web": "^3.0@dev",
"yiisoft/yii-cycle": "^3.0@dev"
},
"require-dev": {
},
Expand Down
4 changes: 4 additions & 0 deletions config/common.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
use App\Factory\MailerFactory;
use App\Parameters;
use Psr\Log\LoggerInterface;
use Yiisoft\Aliases\Aliases;
use Yiisoft\Cache\ArrayCache;
use Yiisoft\Cache\Cache;
use Yiisoft\Cache\CacheInterface;
Expand All @@ -16,6 +17,9 @@
*/

return [
Aliases::class => $params['aliases'],
Psr\SimpleCache\CacheInterface::class => ArrayCache::class,
CacheInterface::class => Cache::class,
Parameters::class => static function () use ($params) {
return new Parameters($params);
},
Expand Down
38 changes: 37 additions & 1 deletion config/params.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

use App\Command\User\CreateCommand;

return [
'mailer' => [
'host' => 'smtp.example.com',
Expand All @@ -20,5 +22,39 @@

'session' => [
'options' => ['cookie_secure' => 0],
]
],

'commands' => [
'user/create' => CreateCommand::class,
],

// cycle DBAL config
'cycle.dbal' => [
'default' => 'default',
'aliases' => [],
'databases' => [
'default' => ['connection' => 'sqlite']
],
'connections' => [
'sqlite' => [
'driver' => \Spiral\Database\Driver\SQLite\SQLiteDriver::class,
'connection' => 'sqlite:@runtime/database.db',
'username' => '',
'password' => '',
]
],
],
// cycle common config
'cycle.common' => [
'entityPaths' => [
'@src/Entity'
],
],
// cycle migration config
'cycle.migrations' => [
'directory' => '@root/migrations',
'namespace' => 'App\\Migration',
'table' => 'migration',
'safe' => false,
],
];
59 changes: 59 additions & 0 deletions src/Command/User/CreateCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

namespace App\Command\User;

use App\Entity\User;
use Cycle\ORM\ORMInterface;
use Cycle\ORM\Transaction;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class CreateCommand extends Command
{
private const EXIT_CODE_FAILED_TO_PERSIST = 1;

private $orm;

protected static $defaultName = 'user/create';

public function __construct(ORMInterface $orm)
{
parent::__construct();
$this->orm = $orm;
}

public function configure(): void
{
$this
->setDescription('Creates a user')
->setHelp('This command allows you to create a user')
->addArgument('login', InputArgument::REQUIRED, 'Login')
->addArgument('password', InputArgument::REQUIRED, 'Password');
}

protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output);

$login = $input->getArgument('login');
$password = $input->getArgument('password');

$user = new User();
$user->setLogin($login);
$user->setPassword($password);

try {
$transaction = new Transaction($this->orm);
$transaction->persist($user);
$transaction->run();
$io->success('User created');
} catch (\Throwable $t) {
$io->error($t->getMessage());
return self::EXIT_CODE_FAILED_TO_PERSIST;
}
}
}
58 changes: 49 additions & 9 deletions src/Entity/User.php
Original file line number Diff line number Diff line change
@@ -1,20 +1,55 @@
<?php

namespace App\Entity;

use Cycle\Annotated\Annotation\Column;
use Cycle\Annotated\Annotation\Entity;
use Cycle\Annotated\Annotation\Table;
use Cycle\Annotated\Annotation\Table\Index;
use Yiisoft\Security\PasswordHasher;
use Yiisoft\Security\Random;
use Yiisoft\Auth\IdentityInterface;

/**
* @Entity(repository="App\Repository\UserRepository")
* @Table(
* indexes={
* @Index(columns={"login"}, unique=true),
* @Index(columns={"token"}, unique=true)
* }
* )
*/
class User implements IdentityInterface
{
private string $id;
private ?string $token = null;
private string $login;
private ?string $passwordHash = null;
/**
* @Column(type="primary")
* @var int
*/
private $id;

/**
* @Column(type="string(128)")
* @var string
*/
private $token;

/**
* @Column(type="string(48)")
* @var string
*/
private $login;

public function __construct(string $id, string $login)
/**
* @Column(type="string")
* @var string
*/
private $passwordHash;

public function __construct()
{
$this->id = $id;
$this->login = $login;
if (!isset($this->token)) {
$this->resetToken();
}
}

public function getId(): ?string
Expand All @@ -27,16 +62,21 @@ public function getToken(): ?string
return $this->token;
}

public function setToken(string $token): void
public function resetToken(): void
{
$this->token = $token;
$this->token = Random::string(128);
}

public function getLogin(): string
{
return $this->login;
}

public function setLogin(string $login): void
{
$this->login = $login;
}

public function validatePassword(string $password): bool
{
if ($this->passwordHash === null) {
Expand Down
1 change: 1 addition & 0 deletions src/Factory/AppRouterFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public function __invoke(ContainerInterface $container)
Route::get('/test/{id:\w+}')
->to(new ActionCaller(SiteController::class, 'testParameter', $container))
->name('site/test'),

Route::methods([Method::GET, Method::POST], '/login')
->to(new ActionCaller(AuthController::class, 'login', $container))
->name('site/login'),
Expand Down
37 changes: 10 additions & 27 deletions src/Repository/UserRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,51 +3,34 @@
namespace App\Repository;

use App\Entity\User;
use Cycle\ORM\ORMInterface;
use Cycle\ORM\Select;
use Yiisoft\Auth\IdentityInterface;
use Yiisoft\Auth\IdentityRepositoryInterface;

class UserRepository implements IdentityRepositoryInterface
class UserRepository extends Select\Repository implements IdentityRepositoryInterface
{
private const IDENTITIES = [
[
'id' => '1',
'token' => 'test1',
'login' => 'samdark',
'password' => 'qwerty',
],
[
'id' => '2',
'token' => 'test2',
'login' => 'hiqsol',
'password' => 'qwerty',
],
];
public function __construct(ORMInterface $orm, $role = User::class)
{
parent::__construct(new Select($orm, $role));
}

private function findIdentityBy(string $field, string $value): ?IdentityInterface
{
foreach (self::IDENTITIES as $identity) {
if ($identity[$field] === $value) {
$user = new User($identity['id'], $identity['login']);
$user->setToken($identity['token']);
$user->setPassword($identity['password']);
return $user;
}
}

return null;
return $this->findOne([$field => $value]);
}

public function findIdentity(string $id): ?IdentityInterface
{
return $this->findIdentityBy('id', $id);
return $this->findByPK($id);
}

public function findIdentityByToken(string $token, string $type): ?IdentityInterface
{
return $this->findIdentityBy('token', $token);
}

public function findByLogin(string $login): ?User
public function findByLogin(string $login): ?IdentityInterface
{
return $this->findIdentityBy('login', $login);
}
Expand Down

0 comments on commit 08bb6ad

Please sign in to comment.