Last active
October 24, 2019 22:39
-
-
Save msangel/74c6cec96ea4a4ecc01187e465fdeb14 to your computer and use it in GitHub Desktop.
ToLiquid PropertyResolverAdapter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package liqp; | |
/** | |
* Provide alternative to :to_liquid | |
* Used in some liquid transformation. | |
*/ | |
public interface ToLiquid { | |
Object toLiquid(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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