Sha256: 2a1a6a57e4c8648149bc28baec308bfb1987c4bf777e5f132d8971a9e7617852

Contents?: true

Size: 1.37 KB

Versions: 29

Compression:

Stored size: 1.37 KB

Contents

# frozen_string_literal: true

module Cocina
  module Models
    module Validators
      # Validates that only a single CatalogLink has refresh set to true
      class CatalogLinksValidator
        MAX_REFRESH_CATALOG_LINKS = 1

        def self.validate(clazz, attributes)
          new(clazz, attributes).validate
        end

        def initialize(clazz, attributes)
          @clazz = clazz
          @attributes = attributes
        end

        def validate
          return unless meets_preconditions?

          return if refresh_catalog_links.length <= MAX_REFRESH_CATALOG_LINKS

          raise ValidationError, "Multiple catalog links have 'refresh' property set to true " \
                                 "(only one allowed) #{refresh_catalog_links}"
        end

        private

        attr_reader :clazz, :attributes

        def meets_preconditions?
          (dro? || collection?) && Array(attributes.dig(:identification, :catalogLinks)).any?
        end

        def refresh_catalog_links
          attributes.dig(:identification, :catalogLinks).select { |catalog_link| catalog_link[:refresh] }
        end

        def dro?
          (clazz::TYPES & DRO::TYPES).any?
        rescue NameError
          false
        end

        def collection?
          (clazz::TYPES & Collection::TYPES).any?
        rescue NameError
          false
        end
      end
    end
  end
end

Version data entries

29 entries across 29 versions & 1 rubygems

Version Path
cocina-models-0.74.0 lib/cocina/models/validators/catalog_links_validator.rb
cocina-models-0.73.6 lib/cocina/models/validators/catalog_links_validator.rb
cocina-models-0.73.5 lib/cocina/models/validators/catalog_links_validator.rb
cocina-models-0.73.4 lib/cocina/models/validators/catalog_links_validator.rb
cocina-models-0.73.3 lib/cocina/models/validators/catalog_links_validator.rb
cocina-models-0.73.2 lib/cocina/models/validators/catalog_links_validator.rb
cocina-models-0.73.1 lib/cocina/models/validators/catalog_links_validator.rb
cocina-models-0.73.0 lib/cocina/models/validators/catalog_links_validator.rb
cocina-models-0.72.0 lib/cocina/models/validators/catalog_links_validator.rb