master

laravel/framework

Last updated at: 29/12/2023 09:22

InteractsWithDictionary.php

TLDR

This file contains a trait called InteractsWithDictionary that provides a method getDictionaryKey(). This method is used to get a dictionary key attribute by casting it to a string if necessary.

Methods

getDictionaryKey($attribute)

This method takes an attribute as input and returns the dictionary key attribute, casting it to a string if necessary. It performs the following steps:

  • If the attribute is an object, it checks if the object has a __toString() method. If it does, it calls the method and returns the result as the dictionary key attribute.
  • If the attribute is an instance of the UnitEnum class, it returns the value of the attribute if it is an instance of BackedEnum, or returns the name of the attribute otherwise.
  • If none of the above conditions are met, it throws an InvalidArgumentException with a message stating that the model attribute value is an object but does not have a __toString() method.
  • If the attribute is not an object, it returns the attribute as is.

It is important to note that this file does not contain any classes.

<?php

namespace Illuminate\Database\Eloquent\Relations\Concerns;

use BackedEnum;
use InvalidArgumentException;
use UnitEnum;

trait InteractsWithDictionary
{
    /**
     * Get a dictionary key attribute - casting it to a string if necessary.
     *
     * @param  mixed  $attribute
     * @return mixed
     *
     * @throws \InvalidArgumentException
     */
    protected function getDictionaryKey($attribute)
    {
        if (is_object($attribute)) {
            if (method_exists($attribute, '__toString')) {
                return $attribute->__toString();
            }

            if ($attribute instanceof UnitEnum) {
                return $attribute instanceof BackedEnum ? $attribute->value : $attribute->name;
            }

            throw new InvalidArgumentException('Model attribute value is an object but does not have a __toString method.');
        }

        return $attribute;
    }
}