attribute code => rule. */ final class AttributeMap { /** * Rules as arrays: category ID => attribute code => rule data. * * @var array> */ private $rules = array(); /** * Constructor. * * @param array $rules Category ID => attribute code => rule data. */ public function __construct( array $rules = array() ) { foreach ( $rules as $category => $by_code ) { foreach ( (array) $by_code as $code => $data ) { $this->set_rule( (int) $category, (string) $code, new AttributeRule( (array) $data ) ); } } } /** * The rules of one channel (or account) out of the stored setting (key => rules). * * @param array $setting Stored setting. * @param int|string $key Channel ID, or an account ID. */ public static function from_setting( array $setting, $key = 0 ): self { return new self( (array) ( $setting[ $key ] ?? $setting[ (string) $key ] ?? array() ) ); } /** * The stored setting with this map for one channel (or account). * * @param array $setting Stored setting. * @param int|string $key Channel ID, or an account ID. */ public function to_setting( array $setting, $key = 0 ): array { $setting[ $key ] = $this->rules; return $setting; } /** * Sets a rule. * * @param int $category_id marketplace category ID. * @param string $code marketplace attribute code. * @param AttributeRule $rule Rule. */ public function set_rule( int $category_id, string $code, AttributeRule $rule ): void { if ( $category_id > 0 && '' !== $code ) { $this->rules[ $category_id ][ $code ] = $rule->to_array(); } } /** * Removes all rules of a category. * * @param int $category_id marketplace category ID. */ public function clear_category( int $category_id ): void { unset( $this->rules[ $category_id ] ); } /** * Whether a category has any rules. * * @param int $category_id marketplace category ID. */ public function has_category( int $category_id ): bool { return ! empty( $this->rules[ $category_id ] ); } /** * One rule. * * @param int $category_id marketplace category ID. * @param string $code Attribute code. */ public function rule( int $category_id, string $code ): ?AttributeRule { return isset( $this->rules[ $category_id ][ $code ] ) ? new AttributeRule( $this->rules[ $category_id ][ $code ] ) : null; } /** * All rules of a category. * * @param int $category_id marketplace category ID. * @return array */ public function rules_for( int $category_id ): array { $out = array(); foreach ( (array) ( $this->rules[ $category_id ] ?? array() ) as $code => $data ) { $out[ (string) $code ] = new AttributeRule( $data ); } return $out; } }