| 1 |
<?php namespace TierPricingTable\Addons\TierLabels; |
| 2 |
|
| 3 |
class TierLabelsManager { |
| 4 |
|
| 5 |
const LABELS_KEY = 'tiered_pricing_table/features/tier-labels/labels'; |
| 6 |
|
| 7 |
protected static $instance = null; |
| 8 |
protected $labels = array(); |
| 9 |
|
| 10 |
public static function getInstance(): self { |
| 11 |
if ( self::$instance === null ) { |
| 12 |
self::$instance = new self(); |
| 13 |
} |
| 14 |
|
| 15 |
return self::$instance; |
| 16 |
} |
| 17 |
|
| 18 |
private function __construct() {} |
| 19 |
|
| 20 |
public function saveLabels( array $labels ) { |
| 21 |
$labelsAsArray = array_map( function ( $label ) { |
| 22 |
return $label->toArray(); |
| 23 |
}, $labels ); |
| 24 |
|
| 25 |
update_option( self::LABELS_KEY, $labelsAsArray ); |
| 26 |
} |
| 27 |
|
| 28 |
public function getLabels( $force = false ): array { |
| 29 |
|
| 30 |
if ( empty( $this->labels ) || $force ) { |
| 31 |
$customLabels = get_option( self::LABELS_KEY, array() ); |
| 32 |
$instances = array(); |
| 33 |
|
| 34 |
foreach ( $customLabels as $label ) { |
| 35 |
$instances[] = TierLabel::fromArray( $label ); |
| 36 |
} |
| 37 |
|
| 38 |
$this->labels = $instances; |
| 39 |
} |
| 40 |
|
| 41 |
return $this->labels; |
| 42 |
} |
| 43 |
|
| 44 |
public function getLabel( $id ): ?TierLabel { |
| 45 |
$labels = $this->getLabels(); |
| 46 |
|
| 47 |
foreach ( $labels as $label ) { |
| 48 |
if ( $label->getId() === $id ) { |
| 49 |
return $label; |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
return null; |
| 54 |
} |
| 55 |
} |