PHP code example of madison-solutions / enum

1. Go to this page and download the library: Download madison-solutions/enum library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

madison-solutions / enum example snippets


class ShippingMethod extends \MadisonSolutions\Enum\Enum
{
    public static function definitions() : array
    {
        return [
            'collection' => [
                'label' => 'Collection',
                'description' => 'Collect in person from our store.',
                'fixed_charge' => 0,
                'charge_per_kg' => 0,
            ],
            'van' => [
                'label' => 'Local van delivery',
                'description' => 'Local delivery by our own vans.',
                'fixed_charge' => 10,
                'charge_per_kg' => 0,
            ],
            'courier' => [
                'label' => 'Nationwide delivery',
                'description' => 'Nationwide delivery by courier service.',
                'fixed_charge' => 5,
                'charge_per_kg' => 3,
            ],
        ];
    }

    public function charge($weight) {
        return $this->fixed_charge + $weight * $this->charge_per_kg;
    }
}

foreach (ShippingMethods::members() as $method) {
    echo $method->label . ': ' . $method->charge($weight) . "\n";
}

$freeMethods = ShippingMethods::subset(function ($method) {
    return $method->fixed_charge === 0 && $method->charge_per_kg === 0;
});

if ($method == ShippingMethods::collection()) {
    echo "You are collecting in person.";
}
// or
if ($method->name == 'collection') {
    echo "You are collecting in person.";
}
// or
switch ($method) {
    case ShippingMethods::collection():
        echo "You are collecting in person.";
        break;
}

function validateShippingMethod($order, ShippingMethod $method) {
    if ($method === ShippingMethods::van()) {
        if (! $order->address->isLocal()) {
            die("Van delivery is only available for local addresses");
        }
    }
}