Skip to content

Commit

Permalink
Add verification code manager
Browse files Browse the repository at this point in the history
  • Loading branch information
zingimmick committed Aug 2, 2020
1 parent 5226e05 commit 0af02cc
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 0 deletions.
4 changes: 4 additions & 0 deletions config/sms.php
Original file line number Diff line number Diff line change
Expand Up @@ -176,4 +176,8 @@
'app_id' => env('SMS_YUNZHIXUN_APP_ID'),
],
],
'verification' => [
'prefix' => 'sms_code_',
'length' => 5,
],
];
41 changes: 41 additions & 0 deletions src/VerificationCodeManager.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

declare(strict_types=1);

namespace Zing\LaravelSms;

use Illuminate\Contracts\Cache\Factory;

class VerificationCodeManager
{
protected $cacheManager;

/**
* VerificationCodeManager constructor.
*
* @param $cacheManager
*/
public function __construct(Factory $cacheManager)
{
$this->cacheManager = $cacheManager;
}

protected function getPrefixedKey($number)
{
return config('sms.verification.prefix') . $number;
}

public function verify($number, $code)
{
return $code === $this->cacheManager->get($this->getPrefixedKey($number));
}

public function issue($number)
{
$length = config('sms.verification.length');
$code = random_int(10 ** ($length - 1), (10 ** $length) - 1);
$this->cacheManager->set($this->getPrefixedKey($number), $code, 600);

return $code;
}
}
36 changes: 36 additions & 0 deletions tests/VerificationCodeManagerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

declare(strict_types=1);

namespace Zing\LaravelSms\Tests;

use Zing\LaravelSms\SmsNumber;
use Zing\LaravelSms\VerificationCodeManager;

class VerificationCodeManagerTest extends TestCase
{
protected $manager;

protected function getEnvironmentSetUp($app): void
{
}

protected function setUp(): void
{
parent::setUp();

$this->manager = app(VerificationCodeManager::class);
}

public function testIssue(): void
{
$code = $this->manager->issue('18888888888');
self::assertSame(config('sms.verification.length'), strlen((string) $code));
}

public function testVerify(): void
{
$code = $this->manager->issue(new SmsNumber('18888888888'));
self::assertTrue($this->manager->verify(new SmsNumber('18888888888'), $code));
}
}

0 comments on commit 0af02cc

Please sign in to comment.