|
1
|
|
|
<?php |
|
2
|
|
|
namespace Germania\Coupons; |
|
3
|
|
|
|
|
4
|
|
|
class PdoCouponFactory |
|
5
|
|
|
{ |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* @var string |
|
9
|
|
|
*/ |
|
10
|
|
|
public $php_class; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* @var callable |
|
14
|
|
|
*/ |
|
15
|
|
|
public $coupon_sheet_factory; |
|
16
|
|
|
|
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* @var PDOStatement |
|
20
|
|
|
*/ |
|
21
|
|
|
public $stmt; |
|
22
|
|
|
|
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @var string[] |
|
26
|
|
|
*/ |
|
27
|
|
|
protected static $coupon_fields_default = array( |
|
28
|
|
|
'id', |
|
29
|
|
|
'code', |
|
30
|
|
|
'coupon_sheet_id AS coupon_sheet', |
|
31
|
|
|
); |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* @var string[] |
|
35
|
|
|
*/ |
|
36
|
|
|
public static $coupon_fields = array(); |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* @param \PDO $pdo |
|
40
|
|
|
* @param string $coupons_table |
|
41
|
|
|
* @param callable $coupon_sheet_factory |
|
42
|
|
|
* @param string $php_class |
|
43
|
|
|
*/ |
|
44
|
|
|
public function __construct( \PDO $pdo, $coupons_table, callable $coupon_sheet_factory, $php_class = null) |
|
45
|
|
|
{ |
|
46
|
|
|
$this->coupon_sheet_factory = $coupon_sheet_factory; |
|
47
|
|
|
$this->php_class = $php_class ?: Coupon::class; |
|
48
|
|
|
|
|
49
|
|
|
if (!is_subclass_of($this->php_class, CouponInterface::class )) |
|
|
|
|
|
|
50
|
|
|
throw new \InvalidArgumentException("Class name or instance of CouponInterface expected."); |
|
51
|
|
|
|
|
52
|
|
|
$sql_fields = join(",", array_merge(static::$coupon_fields_default, static::$coupon_fields)); |
|
53
|
|
|
|
|
54
|
|
|
$sql = "SELECT |
|
55
|
|
|
{$sql_fields} |
|
56
|
|
|
FROM `{$coupons_table}` |
|
57
|
|
|
|
|
58
|
|
|
WHERE code = :code |
|
59
|
|
|
LIMIT 1"; |
|
60
|
|
|
|
|
61
|
|
|
$this->stmt = $pdo->prepare( $sql ); |
|
|
|
|
|
|
62
|
|
|
$this->stmt->setFetchMode( \PDO::FETCH_CLASS, $this->php_class ); |
|
63
|
|
|
|
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
/** |
|
67
|
|
|
* @param string|CouponInterface $code |
|
68
|
|
|
* @return CouponInterface[] |
|
69
|
|
|
*/ |
|
70
|
|
|
public function __invoke( $code ) |
|
71
|
|
|
{ |
|
72
|
|
|
if ($code instanceOf CouponInterface) |
|
73
|
|
|
$code = $code->getCode(); |
|
74
|
|
|
|
|
75
|
|
|
if (!$this->stmt->execute([ |
|
76
|
|
|
'code' => $code |
|
77
|
|
|
])) { |
|
78
|
|
|
throw new \RuntimeException("Could not execute PDOStatement."); |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
|
|
$coupon = $this->stmt->fetch(); |
|
82
|
|
|
|
|
83
|
|
|
if ($coupon and $this->coupon_sheet_factory): |
|
84
|
|
|
$coupon_sheet_factory = $this->coupon_sheet_factory; |
|
85
|
|
|
$coupon->coupon_sheet = $coupon_sheet_factory( $coupon->coupon_sheet ); |
|
86
|
|
|
endif; |
|
87
|
|
|
|
|
88
|
|
|
return $coupon; |
|
89
|
|
|
} |
|
90
|
|
|
|
|
91
|
|
|
} |
|
92
|
|
|
|
|
93
|
|
|
|