spatie / laravel-settings

Store strongly typed application settings
MIT License
1.23k stars 114 forks source link

Declare strict types #287

Closed karinarastsinskagia closed 2 months ago

karinarastsinskagia commented 2 months ago

✏️ Describe the bug Recently, I started to use the package to implement my application's settings. My first approach was to define my setting class with some properties (take a look at the example below).

<?php

use Spatie\LaravelSettings\Settings;

class GeneralSettings extends Settings
{
    public string $name;
    public bool $is_active;

    public static function group(): string
    {
        return 'general';
    }
}

After that, I wrote some tests to check the properties types and their casts. Here, I dealt with some issues. Despite that fact of defining explicitly the properties types, I noticed that the things did not work as I expected.  More specifically, in case of boolean types ($is_active), when a different value type is assigned, I would expect a TypeError exception raise. However, this did not happen.

Example 

Screenshot 2024-08-20 142014 Screenshot 2024-08-20 142026

As you can see, I passed a string to a boolean property type and it saved it as boolean, at the end.

This is reasonable, as according to the PHP  rules,  any non-empty string is considered true when casts to a boolean. Therefore, when I assign 'bar' to a boolean property, PHP will convert 'bar' to true. The same happens for any non-zero integer, non-zero float, non-null object.

Finally, I tried to figure out with the above, enforcing strict typing in abstract Settingclass (pr #286 )

<?php
declare (strict_types =1);
namespace Spatie\LaravelSettings;

Defining the statement above, each child of Setting class, can not accept a value which is not comprised with its properties types.

I hope you find this helpful!

Thank you.

🖥️ Versions

Laravel: ^11 Laravel settings: 3.3.3 PHP: 8.3

rubenvanassche commented 2 months ago

This is default PHP behavior and I think we're going to keep it as is since we don't use strict typing here at Spatie.