- array_flip: documentation ( source)
<?php
enum ProductCategories: string
{
case TSHIRT = 't_shirt';
case SHOES = 'shoes';
}
abstract class Base
{
protected static array $categoryMappings;
public static function getLocalCategoryId(ProductCategories $category): ?string
{
// Use $category->value to access the scalar value of the enum
return static::$categoryMappings[$category->value] ?? null;
}
public static function getCategoryFromLocalId(string $categoryId): ?ProductCategories
{
// Flip the array to find the original enum based on categoryId
$inverted = array_flip(static::$categoryMappings);
if (array_key_exists($categoryId, $inverted)) {
// Use ProductCategories::from to create enum from the string value
return ProductCategories::from($inverted[$categoryId]);
}
return null;
}
abstract public function getByCategory(ProductCategories $category);
}
class A extends Base
{
protected static array $categoryMappings = [
ProductCategories::TSHIRT->value => '1',
ProductCategories::SHOES->value => '2',
];
public function getByCategory(ProductCategories $category) {
$localCategory = static::getLocalCategoryId($category);
// Makes API call and returns results
return $localCategory;
}
}
class B extends Base
{
protected static array $categoryMappings = [
ProductCategories::TSHIRT->value => 't-shirt',
ProductCategories::SHOES->value => 'mens-shoes',
];
public function getByCategory(ProductCategories $category) {
$localCategory = static::getLocalCategoryId($category);
// Makes API call and returns results
return $localCategory;
}
}
// Test cases
echo A::getLocalCategoryId(ProductCategories::TSHIRT); // 1
echo "\n";
echo B::getLocalCategoryId(ProductCategories::TSHIRT); // t-shirt
echo "\n";
echo A::getCategoryFromLocalId('1') === B::getCategoryFromLocalId('t-shirt') ? 'Same' : 'Not same';
echo "\n";
echo A::getLocalCategoryId(ProductCategories::SHOES); // 2
echo "\n";
echo B::getLocalCategoryId(ProductCategories::SHOES); // mens-shoes
echo "\n";
echo "\n\n\n";
$aClass = new A();
echo $aClass->getByCategory(ProductCategories::TSHIRT);
echo "\n";
$bClass = new B();
echo $bClass->getByCategory(ProductCategories::TSHIRT);