<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Relations\MorphMany;
use ReflectionClass;

trait CascadeDeletesPolymorphics
{
    protected static function bootCascadeDeletesPolymorphics()
    {
        static::deleting(function ($model) {
            $relationships = self::getMorphManyRelationships($model);

            foreach ($relationships as $relationship) {
                if ($model->$relationship()->exists()) {
                    $model->$relationship()->delete();
                }
            }
        });
    }

    private static function getMorphManyRelationships($model)
    {
        $reflector = new ReflectionClass($model);
        $methods = $reflector->getMethods(\ReflectionMethod::IS_PUBLIC);
        $relationships = [];

        foreach ($methods as $method) {
            if ($method->class == get_class($model) && $method->getNumberOfParameters() == 0) {
                $returnType = $method->getReturnType();

                if ($returnType && $returnType->getName() == MorphMany::class) {
                    $relationships[] = $method->name;
                }
            }
        }

        return $relationships;
    }
}
