silverstripe-ideannotator icon indicating copy to clipboard operation
silverstripe-ideannotator copied to clipboard

Suggestion: typehinting MyObject::get()

Open tractorcow opened this issue 7 years ago • 6 comments

I've established that this works and gives you typehinting for dataobjects.

/**
 * @method static DataList|Location[] get()
 */
class Loction extends DataObject {}

Do with this what you will :)

tractorcow avatar Aug 01 '18 05:08 tractorcow

Well, besides your typo... That is actually a pretty good idea to add the common static methods to the docblock

Firesphere avatar Aug 01 '18 05:08 Firesphere

Actually I just realised we can add that to DataObject directly.

just DataList|static[]

tractorcow avatar Aug 02 '18 21:08 tractorcow

What typo?

tractorcow avatar Aug 02 '18 21:08 tractorcow

@tractorcow this isn't working for me:

diff --git a/src/ORM/DataObject.php b/src/ORM/DataObject.php
index 928576fca..beb8cdf45 100644
--- a/src/ORM/DataObject.php
+++ b/src/ORM/DataObject.php
@@ -3030,7 +3030,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
      *
      * @todo $containerClass is Ignored, why?
      *
-     * @return DataList The objects matching the filter, in the class specified by $containerClass
+     * @return DataList|static[] The objects matching the filter, in the class specified by $containerClass
      */
     public static function get(
         $callerClass = null,

static on its own works correctly, but it's obviously incorrect for that method

I notice PSR-5 (back in draft again) supports collections e.g. DataList<static> (presumably static would work) but that's not working in my PHPStorm right now.

robbieaverill avatar Sep 13 '18 18:09 robbieaverill

maybe this is not as relevant with silverstripe 5.2 being released?

lekoala avatar Apr 26 '24 10:04 lekoala

@lekoala it looks like they still recommend developers write their own type hints, which this module would assist with: https://docs.silverstripe.org/en/5/changelogs/5.2.0/#generics-return-lists

In your project code, any time you return an instance of SS_List (such as a DataList or ArrayList), you can add a generic typehint to declare what kind of object the returned list contains. This example will hint to the IDE that it returns a DataList containing CarouselItem records:

use App\Model\CarouselItem;
use SilverStripe\ORM\DataList;

/**
 * @return DataList<CarouselItem>
 */
function getCarouselItems(): DataList
{
    return CarouselItem::get();
}

robbieaverill avatar Apr 28 '24 23:04 robbieaverill