1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10:
11:
12: namespace Chromabits\Nucleus\Support;
13:
14: use Chromabits\Nucleus\Exceptions\CoreException;
15: use Chromabits\Nucleus\Foundation\StaticObject;
16: use Chromabits\Nucleus\Meditation\Arguments;
17: use Chromabits\Nucleus\Meditation\Boa;
18: use Chromabits\Nucleus\Meditation\Exceptions\InvalidArgumentException;
19: use Chromabits\Nucleus\Meditation\TypeHound;
20: use Chromabits\Nucleus\View\Interfaces\SafeHtmlProducerInterface;
21: use Chromabits\Nucleus\View\SafeHtmlWrapper;
22:
23: 24: 25: 26: 27: 28: 29: 30:
31: class Html extends StaticObject
32: {
33: 34: 35: 36: 37: 38: 39: 40: 41:
42: public static function escape($string)
43: {
44: Arguments::define(
45: Boa::either(
46: Boa::either(
47: Boa::instance(SafeHtmlWrapper::class),
48: Boa::instance(SafeHtmlProducerInterface::class)
49: ),
50: Boa::string()
51: )
52: )->check($string);
53:
54: if ($string instanceof SafeHtmlWrapper) {
55: return $string;
56: } elseif ($string instanceof SafeHtmlProducerInterface) {
57: $result = $string->getSafeHtml();
58:
59: if ($result instanceof SafeHtmlWrapper) {
60: return $result;
61: } elseif ($result instanceof SafeHtmlProducerInterface) {
62: return static::escape($result);
63: }
64:
65: throw new CoreException(vsprintf(
66: 'Object of class %s implements SafeHtmlProducerInterface'
67: . ' but it returned an unsafe type: %s',
68: [get_class($string), TypeHound::fetch($result)]
69: ));
70: }
71:
72: return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
73: }
74:
75: 76: 77: 78: 79: 80: 81:
82: public static function safe($string)
83: {
84: if ($string instanceof SafeHtmlWrapper) {
85: return $string;
86: }
87:
88: return new SafeHtmlWrapper($string);
89: }
90: }
91: