Skip to content

Instantly share code, notes, and snippets.

@msangel
Last active October 24, 2019 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msangel/74c6cec96ea4a4ecc01187e465fdeb14 to your computer and use it in GitHub Desktop.
Save msangel/74c6cec96ea4a4ecc01187e465fdeb14 to your computer and use it in GitHub Desktop.
ToLiquid PropertyResolverAdapter
package liqp;
/**
* Provide alternative to :to_liquid
* Used in some liquid transformation.
*/
public interface ToLiquid {
Object toLiquid();
}
package liqp.filters.where;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import liqp.LValue;
import liqp.ToLiquid;
import java.util.Map;
import java.util.regex.Pattern;
public class ToLiquidPropertyResolverAdapter extends LValue implements PropertyResolverAdapter {
@Override
public Object getItemProperty(ObjectMapper mapper, Object input, Object property) {
Object startValue = ((ToLiquid) input).toLiquid();
String[] parts = asString(property).split(Pattern.quote("."));
return reduceByDigging(mapper, parts, startValue);
}
@Override
public boolean support(Object target) {
return target instanceof ToLiquid;
}
private Object reduceByDigging(ObjectMapper mapper, String[] path, Object target) {
Object topProperty = getRawProperty(mapper, target, path[0]);
if (path.length == 1) {
return topProperty;
} else {
path = shiftArray(path);
return reduceByDigging(mapper, path, topProperty);
}
}
/* package */ String[] shiftArray(String[] in) {
String[] res = new String[in.length - 1];
System.arraycopy(in, 1, res, 0, res.length);
return res;
}
private Object getRawProperty(ObjectMapper mapper, Object target, String property) {
Map<String, Object> mapRepresentation = mapper.convertValue(target, new TypeReference<Map<String, Object>>() {
});
return mapRepresentation.get(property);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment