Skip to content

Query or ContextSerializer should be aware of "\" #74

@756D61

Description

@756D61

Laravel Settings

3.4

Laravel Version

11

Bug description

The query should escape the slashes in the context values. I'm passing a class name as value in a Context, which works in saving, but during retrieval it returns empty because it contains slashes. The following is an example query made by this library, which doesn't work because the SQL parameter for LIKE contains slashes

select `value` from `settings` where `key` = ? and `settings`.`team_id` is null limit 1 ["settings:c:::parameterizable_type:App\Models\IpHasPort"]

For now, as workaround I wrote my ContextSerializer by replacing \ with dot. I hope there is more robust solution that handles all special SQL characters. I believe it is better to handle it at the query level by escaping .

<?php

namespace App\Serializers;

use Illuminate\Support\Str;
use Rawilk\Settings\Contracts\ContextSerializer;
use Rawilk\Settings\Support\Context;

class SettingsContextSerializer implements ContextSerializer
{
    public function serialize(?Context $context = null): string
    {
        if (is_null($context)) {
            return '';
        }

        return collect($context->toArray())
            ->map(function ($value, string $key) {
                // Use the model's morph class when possible.
                $value = match ($key) {
                    'model' => rescue(fn() => app($value)->getMorphClass(), $value),

                    // CHANGED THIS
                    default => Str::of($value)->replace("\\", ".")->toString(),


                };

                if ($value === false) {
                    $value = 0;
                }

                return "{$key}:{$value}";
            })
            ->implode('::');
    }
}

Steps to reproduce

No response

Relevant log output

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions