Skip to content

Commit

Permalink
feat: allow npc spawn and despawn events to be canceled
Browse files Browse the repository at this point in the history
  • Loading branch information
AIPTU committed Jul 1, 2024
1 parent adad9f8 commit 2aebf5f
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
16 changes: 13 additions & 3 deletions src/aiptu/smaccer/entity/SmaccerHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -408,11 +408,16 @@ public function spawnNPC(

$entity->setVisibility($visibility);

$ev = new NPCSpawnEvent($entity);
$ev->call();
if ($ev->isCancelled()) {
$resolver->reject(new \RuntimeException('NPC spawn event was cancelled'));
return $promise;
}

$entityId = $entity->getId();
$this->playerNPCs[$playerId][$entityId] = $entity;

(new NPCSpawnEvent($entity))->call();

$resolver->resolve($entity);
return $promise;
}
Expand All @@ -431,7 +436,12 @@ public function despawnNPC(string $creatorId, Entity $entity) : Promise {
return $promise;
}

(new NPCDespawnEvent($entity))->call();
$ev = new NPCDespawnEvent($entity);
$ev->call();
if ($ev->isCancelled()) {
$resolver->reject(new \RuntimeException('NPC despawn event was cancelled'));
return $promise;
}

$entity->flagForDespawn();
unset($this->playerNPCs[$creatorId][$entityId]);
Expand Down
6 changes: 5 additions & 1 deletion src/aiptu/smaccer/event/NPCDespawnEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,15 @@
namespace aiptu\smaccer\event;

use pocketmine\entity\Entity;
use pocketmine\event\Cancellable;
use pocketmine\event\CancellableTrait;
use pocketmine\event\entity\EntityEvent;

/**
* @phpstan-extends EntityEvent<Entity>
*/
class NPCDespawnEvent extends EntityEvent {
class NPCDespawnEvent extends EntityEvent implements Cancellable {
use CancellableTrait;

public function __construct(protected Entity $entity) {}
}
6 changes: 5 additions & 1 deletion src/aiptu/smaccer/event/NPCSpawnEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,15 @@
namespace aiptu\smaccer\event;

use pocketmine\entity\Entity;
use pocketmine\event\Cancellable;
use pocketmine\event\CancellableTrait;
use pocketmine\event\entity\EntityEvent;

/**
* @phpstan-extends EntityEvent<Entity>
*/
class NPCSpawnEvent extends EntityEvent {
class NPCSpawnEvent extends EntityEvent implements Cancellable {
use CancellableTrait;

public function __construct(protected Entity $entity) {}
}

0 comments on commit 2aebf5f

Please sign in to comment.