|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace App\Services\Categorization; |
|
4
|
|
|
|
|
5
|
|
|
use App\Models\Category; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Value object representing the result of a categorization attempt. |
|
9
|
|
|
*/ |
|
10
|
|
|
class CategorizationResult |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* @param int $categoryId The determined category ID |
|
14
|
|
|
* @param float $confidence Confidence level (0.0 to 1.0) |
|
15
|
|
|
* @param string $matchedBy Description of what matched |
|
16
|
|
|
* @param array $debug Additional debug information |
|
17
|
|
|
*/ |
|
18
|
|
|
public function __construct( |
|
19
|
|
|
public readonly int $categoryId = Category::OTHER_MISC, |
|
20
|
|
|
public readonly float $confidence = 0.0, |
|
21
|
|
|
public readonly string $matchedBy = 'none', |
|
22
|
|
|
public readonly array $debug = [] |
|
23
|
|
|
) {} |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Check if this result represents a successful categorization. |
|
27
|
|
|
*/ |
|
28
|
|
|
public function isSuccessful(): bool |
|
29
|
|
|
{ |
|
30
|
|
|
return $this->categoryId !== Category::OTHER_MISC && $this->confidence > 0; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* Check if this result should take precedence over another. |
|
35
|
|
|
*/ |
|
36
|
|
|
public function shouldOverride(CategorizationResult $other): bool |
|
37
|
|
|
{ |
|
38
|
|
|
// Higher confidence always wins |
|
39
|
|
|
if ($this->confidence > $other->confidence) { |
|
40
|
|
|
return true; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
// If same confidence, prefer non-misc categories |
|
44
|
|
|
if ($this->confidence === $other->confidence) { |
|
45
|
|
|
return $this->categoryId !== Category::OTHER_MISC && $other->categoryId === Category::OTHER_MISC; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
return false; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* Create a failed/empty result. |
|
53
|
|
|
*/ |
|
54
|
|
|
public static function noMatch(): self |
|
55
|
|
|
{ |
|
56
|
|
|
return new self(Category::OTHER_MISC, 0.0, 'no_match'); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* Create a result with debug info merged. |
|
61
|
|
|
*/ |
|
62
|
|
|
public function withDebug(array $additionalDebug): self |
|
63
|
|
|
{ |
|
64
|
|
|
return new self( |
|
65
|
|
|
$this->categoryId, |
|
66
|
|
|
$this->confidence, |
|
67
|
|
|
$this->matchedBy, |
|
68
|
|
|
array_merge($this->debug, $additionalDebug) |
|
69
|
|
|
); |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
|