session; return $session instanceof \WC_Session ? $session : null; } /** * All selections keyed by extra id. * * @return array */ public function all(): array { $session = $this->session(); if ( ! $session ) { return array(); } $raw = $session->get( self::SESSION_KEY, array() ); if ( ! is_array( $raw ) ) { return array(); } $selections = array(); foreach ( $raw as $extra_id => $data ) { if ( is_string( $extra_id ) && is_array( $data ) ) { $selections[ $extra_id ] = Selection::from_array( $extra_id, $data ); } } return $selections; } /** * One selection. * * @param string $extra_id Extra id. */ public function get( string $extra_id ): ?Selection { return $this->all()[ $extra_id ] ?? null; } /** * Replaces every selection. * * @param array $selections Selections. */ public function replace( array $selections ): void { $session = $this->session(); if ( ! $session ) { return; } $raw = array(); foreach ( $selections as $selection ) { if ( $selection instanceof Selection ) { $raw[ $selection->extra_id ] = $selection->to_array(); } } $session->set( self::SESSION_KEY, $raw ); } /** * Clears every selection (cart emptied). */ public function clear(): void { $session = $this->session(); if ( $session ) { $session->set( self::SESSION_KEY, array() ); } } }