Skip to content

Commit 8cdcaf4

Browse files
committed
Code helper class introduced
1 parent 8a48ee6 commit 8cdcaf4

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

src/AbraFlexi/Code.php

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of the SpojeNet\AbraFlexi package.
7+
*
8+
* (c) 2019-2024 SpojeNet s.r.o. <http://spoje.net/>
9+
* (c) 2025 SpojeNetIT s.r.o. <http://spojenet.cz/>
10+
*
11+
* For the full copyright and license information, please view the LICENSE
12+
* file that was distributed with this source code.
13+
*/
14+
15+
namespace AbraFlexi;
16+
17+
/**
18+
* Description of Code.
19+
*
20+
* @author Vitex <[email protected]>
21+
*/
22+
class Code
23+
{
24+
/**
25+
* Pure code string.
26+
*/
27+
private string $code = '';
28+
29+
public function __construct(mixed $subject)
30+
{
31+
$this->set(self::extract($subject));
32+
}
33+
34+
public function __toString(): string
35+
{
36+
return 'code:'.$this->get();
37+
}
38+
39+
public static function extract(mixed $subject): string
40+
{
41+
$code = '';
42+
43+
if (\is_array($subject) && isset($subject['kod'])) {
44+
$code = $subject['kod'];
45+
} elseif (\is_object($subject) && method_exists($subject, 'getRecordCode')) {
46+
$code = $subject->getRecordCode();
47+
} elseif (\is_object($subject) && method_exists($subject, '__toString')) {
48+
$code = (string) $subject;
49+
}
50+
51+
return $code;
52+
}
53+
54+
public function get(): string
55+
{
56+
return $this->code;
57+
}
58+
59+
public function set(string $code): self
60+
{
61+
$code = self::strip($code);
62+
63+
if (mb_strlen($code) > 20) {
64+
throw new \InvalidArgumentException('Code must be at most 20 characters.');
65+
}
66+
67+
$this->code = $code;
68+
69+
return $this;
70+
}
71+
72+
public static function ensure(string $code): string
73+
{
74+
return (substr($code, 0, 4) === 'ext:') ? $code : 'code:'.strtoupper(self::strip($code));
75+
}
76+
77+
/**
78+
* Returns CODE without code: prefix.
79+
*/
80+
public static function strip(string $code): string
81+
{
82+
return str_replace(['code:', 'code%3A'], '', $code);
83+
}
84+
}

0 commit comments

Comments
 (0)