1+ <?php
2+
3+ declare (strict_types=1 );
4+
5+ namespace imperazim \vendor \customies \item \component ;
6+
7+ use Closure ;
8+ use pocketmine \player \Player ;
9+ use pocketmine \item \Item ;
10+ use imperazim \vendor \customies \item \ItemComponents ;
11+
12+ final class ItemTaskComponent implements ItemComponents {
13+
14+ public const FILTER_HAND = 'hand ' ;
15+ public const FILTER_INVENTORY = 'inventory ' ;
16+
17+ private string $ itemClass ;
18+ private Closure $ callback ;
19+ private string $ filter ;
20+
21+ /**
22+ * Creates a new ItemTaskComponent to define a task that checks for specific items in a player's inventory.
23+ *
24+ * @param string $itemClass The class of the item to check for (e.g., DiamondSword::class).
25+ * @param Closure $callback The action to execute when the item is found. Receives the Player and Item as parameters.
26+ * @param string $filter The location to check for the item. Use FILTER_HAND to check the main hand or FILTER_INVENTORY to check the entire inventory.
27+ */
28+ public function __construct (string $ itemClass , Closure $ callback , string $ filter = self ::FILTER_INVENTORY ) {
29+ $ this ->itemClass = $ itemClass ;
30+ $ this ->callback = $ callback ;
31+ $ this ->filter = $ filter ;
32+ }
33+
34+ public function getName (): string {
35+ return "minecraft:item_task " ;
36+ }
37+
38+ public function getValue (): array {
39+ return [
40+ 'item_class ' => $ this ->itemClass ,
41+ 'filter ' => $ this ->filter ,
42+ ];
43+ }
44+
45+ public function isProperty (): bool {
46+ return false ;
47+ }
48+
49+ public function checkCondition (Player $ player ): ?Item {
50+ $ inventory = $ player ->getInventory ();
51+ switch ($ this ->filter ) {
52+ case self ::FILTER_HAND :
53+ $ item = $ inventory ->getItemInHand ();
54+ return $ item instanceof $ this ->itemClass ? $ item : null ;
55+ default :
56+ foreach ($ inventory ->getContents () as $ item ) {
57+ if ($ item instanceof $ this ->itemClass ) {
58+ return $ item ;
59+ }
60+ }
61+ return null ;
62+ }
63+ }
64+
65+ public function execute (Player $ player , Item $ item ): void {
66+ ($ this ->callback )($ player , $ item );
67+ }
68+ }
0 commit comments