1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

PHP Stan error with return Union type in PHP v7, laravel

Discussão em 'Outras Linguagens' iniciado por ClusterH, Novembro 5, 2024 às 00:52.

  1. ClusterH

    ClusterH Guest

    According to some conditions, I need to return int or Collection (the table data from mysql query or his count), Here is code what I did implemented.

    public function myMethod(
    Term $term,
    int $id,
    ?bool $includeRecords = false,
    ?int $page = 1,
    ?int $count = 100
    ) {
    $currentDefaultSegment = Segment::DEFAULT_SEGMENTS[$id];
    $filterFieldName = $currentDefaultSegment['type'] === 'opener' ? 'lastOpenDate' : 'lastClickDate';

    $query = DB::connection(MYSQL_DB)
    ->table("my_table")
    ->where('status', 1)
    ->where('id', $term->getId())
    ->whereRaw("{$filterFieldName} > CURDATE() - INTERVAL {$currentDefaultSegment['duration']} DAY");

    if ($includeRecords) {
    return $query->limit($count)->offset(($page - 1) * $count)->get(); // It return Collection
    }

    return $query->count(); // It return int
    }


    But when I use this method, php-stan complain and seems like it does not recognize when would be Collection or Int. Error message: Cannot call method transform() on Illuminate\Support\Collection|int.

    Here is code that is calling above method. $this->myMethod(prams here)->transform(....) // In this case myMethod return type should be Collection instead of Int.

    Question: How to determine & force return type is only Collection or only Int according to the Use cases?

    I've tried make 2 methods instead of One according to the conditions, but Almost method body is the same, so I dont think it is good idea to make 2 methods. But have no idea how to solve the problem.

    Continue reading...

Compartilhe esta Página