Skip to content

Commit 020cefd

Browse files
committed
add registery pattern and test
1 parent 809908b commit 020cefd

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php namespace App\Factory\Structural\RegisteryPattern\Exam;
2+
3+
class Application
4+
{
5+
public function run()
6+
{
7+
$registery = ExamRegistery::getInstance();
8+
$registery->set(ExamRegistery::MID_TERM_EXAM, ['math', 'physics', 'optional subject']);
9+
$registery->set(ExamRegistery::FINAL_EXAM, ['math', 'physics']);
10+
11+
$subjects = $registery->get(ExamRegistery::FINAL_EXAM);
12+
echo "<pre>Final exam subject: ";print_r($subjects);
13+
}
14+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<?php namespace App\Factory\Structural\RegisteryPattern\Exam;
2+
3+
class ExamRegistery
4+
{
5+
const MID_TERM_EXAM = 'mid_term';
6+
const FINAL_EXAM = 'final_exam';
7+
private static $_services = [];
8+
private static $_allowedExams = [self::MID_TERM_EXAM, self::FINAL_EXAM];
9+
private static $_instance = null;
10+
11+
public static function getInstance()
12+
{
13+
if(self::$_instance === null) {
14+
return new static;
15+
}
16+
return self::$_instance;
17+
}
18+
19+
public static function setExam($key, $value)
20+
{
21+
if(!\in_array($key, self::$_allowedExams)) {
22+
throw new \InvalidArgumentException();
23+
}
24+
self::$_services[$key] = $value;
25+
}
26+
27+
public static function getExam($key)
28+
{
29+
if(!\array_key_exists($key, self::$_services)) {
30+
throw new \InvalidArgumentException();
31+
}
32+
return self::$_services[$key];
33+
}
34+
}

tests/RegisteryPatternTest.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?php
2+
3+
use App\Factory\Structural\RegisteryPattern\Exam\ExamRegistery;
4+
use PHPUnit\Framework\TestCase;
5+
6+
class RegisteryPatternTest extends TestCase {
7+
private static $registery;
8+
9+
public function setUp(): void
10+
{
11+
self::$registery = ExamRegistery::getInstance();
12+
}
13+
14+
public function testCanAddAllowedKeys()
15+
{
16+
$final_exam_subjects = ['math', 'abc'];
17+
self::$registery->setExam(ExamRegistery::FINAL_EXAM, $final_exam_subjects);
18+
19+
$this->assertSame($final_exam_subjects, self::$registery->getExam(ExamRegistery::FINAL_EXAM));
20+
}
21+
22+
public function testCanThrowExceptionForInvalidKeys()
23+
{
24+
$this->expectException(\InvalidArgumentException::class);
25+
26+
self::$registery->setExam('test', '');
27+
}
28+
29+
public function tearDown(): void
30+
{
31+
self::$registery = null;
32+
}
33+
}

0 commit comments

Comments
 (0)