protected function encode($value)
    {
        if (is_object($value) && method_exists($value, 'getJs')) {
            return new JsExpression($value->getJs());
        } elseif (is_bool($value)) {
            return new JsExpression(($value ? 'true' : 'false'));
        } elseif (is_array($value)) {
            $parsed = [];
            foreach ($value as $child) {
                $parsed[] = $this->encode($child);
            }
            return $parsed;
        }
        try {
            // a value may contain a valid JSON string
            return Json::decode($value);
        } catch (InvalidParamException $e) {
        }
        return $value;
    }