*/ private static $cache = array(); /** * Folder that holds the schema files. * * @return string */ public static function dir() { if ( defined( 'AHA_IS_WOOCOMMERCE_CONTRACT_DIR' ) ) { return AHA_IS_WOOCOMMERCE_CONTRACT_DIR; } return dirname( __DIR__, 2 ) . '/docs/contract/'; } /** * Load a schema by file name. * * @param string $file File name, for example 'status-event.schema.json'. * @return Aha_Is_Woocommerce_Json_Schema|null */ public static function schema( $file ) { if ( ! array_key_exists( $file, self::$cache ) ) { self::$cache[ $file ] = Aha_Is_Woocommerce_Json_Schema::from_file( self::dir() . $file ); } return self::$cache[ $file ]; } /** * Schema of the order create request. * * @return Aha_Is_Woocommerce_Json_Schema|null */ public static function request_schema() { return self::schema( 'order-create.request.schema.json' ); } /** * Whether this plugin speaks a payload version. * * @param string $version Value of schema_version. * @return bool */ public static function is_supported_version( $version ) { $parts = explode( '.', (string) $version ); return isset( $parts[0] ) && self::SUPPORTED_MAJOR === $parts[0]; } /** * Check an outbound payload before it leaves the store. * * A payload that does not match the contract is a bug in this plugin. It is * logged and dropped, because sending it would only make Aha reject it. * * @param array $payload Payload as an associative array. * @param string $schema_file Schema file name. * @return bool */ public static function validate_outbound( array $payload, $schema_file ) { $schema = self::schema( $schema_file ); if ( ! $schema ) { // The schema file is missing. Do not block the push for that. Aha_Is_Woocommerce_Logger::warning( 'contract_schema_missing', array( 'schema' => $schema_file ) ); return true; } $as_object = json_decode( (string) wp_json_encode( $payload ) ); if ( $schema->is_valid( $as_object ) ) { return true; } Aha_Is_Woocommerce_Logger::error( 'outbound_payload_invalid', array( 'schema' => $schema_file, 'error' => $schema->get_first_error(), ) ); return false; } }