Repository: lunarphp/lunar (php)

Issue:
Cannot update `meta` of existing `OrderLine` instance
<!-- DO NOT THROW THIS AWAY -->
<!-- Fill out the FULL versions with patch versions -->

- Lunar version: 1.0.0-beta.1
- Laravel Version: 11.22.0
- PHP Version: 8.3.11
- Database Driver & Version: MySQL 8.0.32

### Expected Behaviour:

Successfully save the updated meta data to database.

### Actual Behaviour:

Gets error "class_implements(): Class product_variant does not exist and could not be loaded".

### Steps To Reproduce:

When creating the order line object, I followed the [docs](https://docs.lunarphp.io/core/reference/orders.html#order-lines) and set `purchasable_type` to `product_variant`.

```
$item = new OrderLine;
$item->purchasable_type = 'product_variant';
// ... Setting other attributes
$item->save();

// ... Do something else
$item->meta = [
  'key' => 'value',
]
$item->save();
```

Currently my workaround to make it works is to set `purchasable_type` to either `\Lunar\Models\ProductVariant::class` or `get_class($variant)`.


Pull request:
Fix extended model resolving
This PR looks to solve some anomalies that have been discovered with model extending.

## Problem A

When replacing a Lunar model, there are instances where the model provided by Lunar is still used for example, if you replace the model like so

```php
\Lunar\Facades\ModelManifest::replace(
    \Lunar\Models\Contracts\Order::class,
    \App\Models\Order::class
);
```

Later in the Lunar core, we are still referencing `Lunar\Models\Order::first()` or via relationships `$orderLine->order()`. We attempted to resolve these queries to their concrete replacements by overriding the `newModelQuery` method, however there were issues with castable attributes which caused them to be cast multiple times, resulting in errors.

### Solution

This has been rewritten so Lunar doesn't try to `fill` the extended instance of the model from the Lunar base class anymore and instead just populates the attributes as they are. Since this should just be a simple class swap it should no longer result in duplicate calls to attribute casters.

There are some additional checks to see if we are actually working with a model that hasn't been extended to ensure we are not getting into a situation where we try and rehydrate with the same class.

### Affected issues

This change should resolve #1942 #1930 

## Problem B

If your own custom model was named something other than it's counterpart, for example:

```php
\Lunar\Facades\ModelManifest::replace(
    \Lunar\Models\Contracts\Order::class,
    \App\Models\MyCustomOrder::class
);
```

This would result in the table name and subsequent foreign key naming to be incorrect i.e. `my_custom_order` and `my_custom_order_id`. This would mean developers would need to add their own methods to override this in order for the naming to resolve properly, which is a bit of a maintenance burden and easily missed when encountering errors.


### Solution

The `HasModelExtending` trait now provides its own `getTable` and `getForeignKey` methods which will check which class within Lunar we are extending and return the appropriate table name and foreign key.

## How this slipped through testing

Looks like there was an oversight and although there were tests for extending models, the tests themselves didn't use any extending when performing more complex tasks, like creating orders from carts.

This PR has now added some model extending to tests which were affected by the issues referenced above to hopefully keep this in check and make for a more "real world" test environment.

Patch:
diff --git a/packages/core/src/Base/Traits/HasModelExtending.php b/packages/core/src/Base/Traits/HasModelExtending.php
index 7cafe6c0..a8e0f2a6 100644
--- a/packages/core/src/Base/Traits/HasModelExtending.php
+++ b/packages/core/src/Base/Traits/HasModelExtending.php
@@ -3,25 +3,71 @@
 namespace Lunar\Base\Traits;
 
 use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Database\Eloquent\Model;
 use Illuminate\Database\Eloquent\Relations\Relation;
 use Illuminate\Support\Arr;
+use Illuminate\Support\Str;
+use Lunar\Base\BaseModel;
 use Lunar\Facades\ModelManifest;
 
 trait HasModelExtending
 {
     public function newModelQuery(): Builder
     {
-        $realClass = static::modelClass();
+        $concreteClass = static::modelClass();
+        $parentClass = get_parent_class($concreteClass);
 
         // If they are both the same class i.e. they haven't changed
         // then just call the parent method.
-        if ($this instanceof $realClass) {
+        if ($parentClass == BaseModel::class || $this instanceof $concreteClass) {
             return parent::newModelQuery();
         }
 
         return $this->newEloquentBuilder(
             $this->newBaseQueryBuilder()
-        )->setModel(new $realClass($this->toArray()));
+        )->setModel(
+            static::withoutEvents(
+                fn () => $this->replicateInto($concreteClass)
+            )
+        );
+    }
+
+    public function replicateInto($newClass)
+    {
+        $defaults = array_values(array_filter([
+            $this->getKeyName(),
+            $this->getCreatedAtColumn(),
+            $this->getUpdatedAtColumn(),
+            ...$this->uniqueIds(),
+            'laravel_through_key',
+        ]));
+
+        $attributes = Arr::except(
+            $this->getAttributes(), $defaults
+        );
+
+        return tap(new $newClass, function ($instance) use ($attributes): Model {
+            $instance->setRawAttributes($attributes);
+
+            $instance->setRelations($this->relations);
+
+            return $instance;
+        });
+    }
+
+    public function getForeignKey(): string
+    {
+        $parentClass = get_parent_class($this);
+
+        return $parentClass == BaseModel::class ? parent::getForeignKey() : Str::snake(class_basename($parentClass)).'_'.$this->getKeyName();
+
+    }
+
+    public function getTable()
+    {
+        $parentClass = get_parent_class($this);
+
+        return $parentClass == BaseModel::class ? parent::getTable() : (new $parentClass)->table;
     }
 
     public static function __callStatic($method, $parameters)
@@ -50,10 +96,11 @@ public static function modelClass(): string
     /**
      * Returns the model alias registered in the model relation morph map.
      */
-    public static function morphName():string{
+    public static function morphName(): string
+    {
         return (new (static::modelClass()))->getMorphClass();
     }
-    
+
     public function getMorphClass(): string
     {
         $morphMap = Relation::morphMap();


Test patch:
diff --git a/tests/core/Stubs/Models/CustomOrder.php b/tests/core/Stubs/Models/CustomOrder.php
new file mode 100644
index 00000000..7cf7db04
--- /dev/null
+++ b/tests/core/Stubs/Models/CustomOrder.php
@@ -0,0 +1,5 @@
+<?php
+
+namespace Lunar\Tests\Core\Stubs\Models;
+
+class CustomOrder extends \Lunar\Models\Order {}
diff --git a/tests/core/Stubs/Models/Order.php b/tests/core/Stubs/Models/Order.php
new file mode 100644
index 00000000..f6497b82
--- /dev/null
+++ b/tests/core/Stubs/Models/Order.php
@@ -0,0 +1,5 @@
+<?php
+
+namespace Lunar\Tests\Core\Stubs\Models;
+
+class Order extends \Lunar\Models\Order {}
diff --git a/tests/core/Unit/Actions/Carts/CreateOrderTest.php b/tests/core/Unit/Actions/Carts/CreateOrderTest.php
index 097c254c..aeba64af 100644
--- a/tests/core/Unit/Actions/Carts/CreateOrderTest.php
+++ b/tests/core/Unit/Actions/Carts/CreateOrderTest.php
@@ -21,6 +21,8 @@
 use Lunar\Models\TaxClass;
 use Lunar\Models\TaxRateAmount;
 
+use function Pest\Laravel\{assertDatabaseHas};
+
 uses(\Illuminate\Foundation\Testing\RefreshDatabase::class);
 
 it('cant create order if already has complete and multiple disabled', function () {
@@ -107,6 +109,10 @@ function can_update_draft_order()
 }
 
 test('can create order', function () {
+    \Lunar\Facades\ModelManifest::replace(
+        \Lunar\Models\Contracts\Order::class,
+        \Lunar\Tests\Core\Stubs\Models\CustomOrder::class
+    );
     CustomerGroup::factory()->create([
         'default' => true,
     ]);
@@ -223,8 +229,8 @@ function can_update_draft_order()
         ->and($order->shippingAddress)->toBeInstanceOf(OrderAddress::class)
         ->and($order->billingAddress)->toBeInstanceOf(OrderAddress::class);
 
-    $this->assertDatabaseHas((new Order)->getTable(), $datacheck);
-    $this->assertDatabaseHas((new OrderLine)->getTable(), [
+    assertDatabaseHas((new Order)->getTable(), $datacheck);
+    assertDatabaseHas((new OrderLine)->getTable(), [
         'identifier' => $shippingOption->getIdentifier(),
     ]);
 
diff --git a/tests/core/Unit/Base/Traits/HasModelExtendingTest.php b/tests/core/Unit/Base/Traits/HasModelExtendingTest.php
index da758ad9..24f55d3e 100644
--- a/tests/core/Unit/Base/Traits/HasModelExtendingTest.php
+++ b/tests/core/Unit/Base/Traits/HasModelExtendingTest.php
@@ -38,6 +38,13 @@ function () {
     expect($sizeOption->sizes)->toHaveCount(1);
 });
 
+test('extended model returns correct table name', function () {
+    expect((new \Lunar\Tests\Core\Stubs\Models\CustomOrder)->getTable())
+        ->toBe(
+            (new \Lunar\Models\Order)->getTable()
+        );
+});
+
 test('can forward static method calls to extended model', function () {
     /** @see \Lunar\Tests\Core\Stubs\Models\ProductOption::getSizesStatic() */
     $newStaticMethod = ProductOption::getSizesStatic();