libcruft-util/json/schema/properties.cpp

82 lines
2.3 KiB
C++
Raw Normal View History

/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2018 Danny Robson <danny@nerdcruft.net>
*/
#include "properties.hpp"
#include "../tree.hpp"
using util::json::schema::constraint::properties;
///////////////////////////////////////////////////////////////////////////////
properties::properties (::json::tree::node const &def)
{
if (!def.is_object ())
throw constraint_error<properties> (def);
for (auto const &[key,val]: def.as_object ()) {
m_properties.emplace (key, *val);
}
}
///////////////////////////////////////////////////////////////////////////////
properties::output_iterator
properties::validate (output_iterator res, ::json::tree::node &target) const noexcept
{
if (!target.is_object ())
return *res++ = { .rule = *this, .target = target };
auto &obj = target.as_object ();
// validate the keys that are present against the property schemas
for (const auto &[key,val]: obj) {
auto const pos = m_properties.find (key);
if (pos == m_properties.end ())
continue;
res = pos->second.validate (res, *val);
}
// check if there's a key in the schema that isn't present but has a default
for (auto const &[key,doc]: m_properties) {
if (!doc.has_default ())
continue;
auto pos = obj.find (key);
if (pos == obj.end ())
obj.insert (key, doc.default_value ());
}
return res;
}
///////////////////////////////////////////////////////////////////////////////
std::ostream&
properties::describe (std::ostream &os) const
{
os << "{ properties: [ ";
for (auto const &[key,val]: m_properties) {
os << key << ": ";
val.describe (os);
os << ", ";
}
return os << " ] }";
}