Class: PhcStringFormat::PhcString

Inherits:
Object
  • Object
show all
Includes:
Validations
Defined in:
lib/phc_string_format/phc_string.rb

Overview

Parser for parsing PHC-string-format.

Defined Under Namespace

Modules: Parameters

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Validations

included

Constructor Details

#initialize(id, version_string, params_string, encoded_salt, encoded_hash) ⇒ PhcString

Returns a new instance of PhcString.



58
59
60
61
62
63
64
65
66
# File 'lib/phc_string_format/phc_string.rb', line 58

def initialize(id, version_string, params_string, encoded_salt, encoded_hash)
  @id = id
  @version_string = version_string
  @params_string = params_string
  @encoded_salt = encoded_salt
  @encoded_hash = encoded_hash

  self.class.do_validate self
end

Class Method Details

.create(id:, version: nil, params: nil, salt: nil, hash: nil, hint: {}) ⇒ Object



28
29
30
31
32
33
34
35
# File 'lib/phc_string_format/phc_string.rb', line 28

def self.create(id:, version: nil, params: nil, salt: nil, hash: nil, hint: {})
  PhcString.new \
    id,
    (Parameters.to_s(v: version) if version),
    (Parameters.to_s(params) if params),
    hint.dig(:salt, :encoding) == '7bit' ? salt : B64.encode(salt),
    B64.encode(hash)
end

.parse(string) ⇒ Object



8
9
10
11
12
13
# File 'lib/phc_string_format/phc_string.rb', line 8

def self.parse(string)
  string ||= ''
  PhcString.new(*split(string))
rescue StandardError => exception
  raise ParseError, exception.message
end

Instance Method Details

#==(other) ⇒ Object



92
93
94
95
# File 'lib/phc_string_format/phc_string.rb', line 92

def ==(other)
  instance_variable_values = other.instance_variables.map { |name| other.instance_variable_get(name) }
  instance_variable_values == instance_variables.map { |name| instance_variable_get(name) }
end

#to_h(pick: nil, hint: {}) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/phc_string_format/phc_string.rb', line 78

def to_h(pick: nil, hint: {})
  pick ||= %i[id version params salt hash]
  {
    id: (@id if pick.include?(:id)),
    version: (Parameters.to_h(@version_string)['v'] if pick.include?(:version)),
    params: (Parameters.to_h(@params_string) if pick.include?(:params)),
    salt:
      if pick.include?(:salt)
        hint.dig(:salt, :encoding) == '7bit' ? @encoded_salt : B64.decode(@encoded_salt)
      end,
    hash: (B64.decode(@encoded_hash) if pick.include?(:hash))
  }.select { |_, value| value }
end

#to_sObject



68
69
70
71
72
73
74
75
76
# File 'lib/phc_string_format/phc_string.rb', line 68

def to_s
  '$' + [
    @id,
    @version_string,
    @params_string,
    @encoded_salt,
    @encoded_hash
  ].compact.join('$')
end