craftcms / element-api

Create a JSON API/Feed for your elements in Craft.
MIT License
498 stars 56 forks source link

Update for craft 5 #186

Closed kristoffeys closed 3 months ago

kristoffeys commented 4 months ago
thisisablock commented 4 months ago

@kristoffeys thanks for your work - just tested out your PR but got some issues. Due to the type changes i can reproduce multiple errors caused bey accessing uninitialized properties:

Typed property craft\elementapi\Plugin::$_defaultResourceAdapterConfig must not be accessed before initialization

This can be fixed with on craft\elementapi\Plugin:72 by changing if ($this->_defaultResourceAdapterConfig !== null) { to if (isset($this->_defaultResourceAdapterConfig) && $this->_defaultResourceAdapterConfig !== null) {

Typed property craft\elementapi\resources\ElementResource::$resourceKey must not be accessed before initialization Typed property craft\elementapi\resources\ElementResource::$meta must not be accessed before initialization

These errors will occur because the default values wont be set on craft\elementapi\resources\ElementResource.

Hotfix is to set the defaults in the config files:

'defaults' => [
        'resourceKey' => 'data',
        'meta' => null,
],

but may its better to fix that in the class to

    public string $resourceKey = 'data';
    public array $meta = [];

Used the 5.0.0-beta1 with an really simple config

<?php

use craft\elements\Entry;

return [
    'defaults' => [
        'resourceKey' => 'data',
        'meta' => null,
    ],
    'endpoints' => [
        'homepage.json' => function() {
            return [
                'elementType' => Entry::class,
                'cache' => false,
                'transformer' => function(Entry $entry) {
                    return [
                        'title' => 'Cool Page'
                    ];
                },
            ];
        }
    ]
];
kristoffeys commented 4 months ago

Thanks for the feedback, for some reason i didn't have this issue in earlier versions. I have added the fixes you indicated.

brandonkelly commented 3 months ago

Thanks for the PR! I’ve just tagged Element API with these changes, however I brought Craft 4 compatibility back as well, as nothing here actually requires changes in Craft 5.