ext-ds
ext-ds copied to clipboard
Testing for Equality
I would like to posit an idea based on this statement from the docs in Map:
Keys of type object are supported. If an object implements Ds\Hashable, equality will be determined by the object's equals function. If an object does not implement Ds\Hashable, objects must be references to the same instance to be considered equal.
Would it be possible to test for any equals function and at least try it? What's my use case I hear you ask...
I use MyClabs\Enum\Enum a lot, at least I did until I started using DS a lot more. Now I have had to re-implement a library for Enum because I need it for keys in Maps, and I can't reliably use MyClabs\Enum\Enum as it doesn't implement Hashable.
It's ok I suppose to use my implementation, but I would rather not have to so that I can take easy advantage of updates and fixes.
I'm copying in @benjaminbertin, @valentin-claras and @mnapoli as the MyClabs team, as maybe there may be a way they'd consider supporting Ds somehow.
It's ok I suppose to use my implementation, but I would rather not have to so that I can take easy advantage of updates and fixes.
Would an extension of MyClabs\Enum\Enum which implements Hashable not also benefit from updates and fixes upstream?
Sadly the equals method in that class is final.
It is unfortunate that we do have a base equals method. I think checking for an exists function and calling it is a reasonable idea, can't see why not.
This works just fine for me:
<?php declare(strict_types = 1);
namespace App\Library\Enum;
use Ds\Hashable;
use MyCLabs\Enum\Enum as BaseEnum;
/**
* @psalm-immutable
* @extends BaseEnum<string>
*/
abstract class Enum extends BaseEnum implements Hashable
{
public function hash(): string
{
return $this->getValue();
}
}
The point is you don't need to override the equals method since the base Enum class already implements it and it is compatible with Hashable.
That said I do agree that being able to provide a custom equality function could be beneficial in some cases. It's not necessary for MyCLabs enums though.