VOOZH about

URL: https://deepwiki.com/hypervel/support/5.3-javascript-integration

⇱ JavaScript Integration | hypervel/support | DeepWiki


Loading...
Menu

JavaScript Integration

Purpose and Scope

The Js class converts PHP data to JavaScript expressions that can be safely embedded in HTML. It applies mandatory XSS protection flags during JSON encoding and intelligently wraps complex structures with JSON.parse(). For view rendering and Blade templating, see page 5.1.


System Overview

The Hypervel\Support\Js class src/Js.php16 provides secure PHP-to-JavaScript data conversion. It implements Htmlable and Stringable interfaces for seamless integration with view rendering contexts.

Key Components:

ComponentLocationPurpose
Jssrc/Js.php16Main conversion class implementing Htmlable, Stringable
Js::from()src/Js.php45-48Static factory method
Js::encode()src/Js.php79-90JSON encoding with REQUIRED_FLAGS
convertDataToJavaScriptExpression()src/Js.php55-72Primary conversion logic
convertJsonToJavaScriptExpression()src/Js.php97-108Wraps JSON in JSON.parse()
REQUIRED_FLAGSsrc/Js.php28Security flags: `JSON_HEX_TAG

Sources: src/Js.php1-126


Class Structure


Interfaces Implemented:

InterfaceMethodLocationPurpose
HtmlabletoHtml()src/Js.php113-116Returns JavaScript expression as HTML-safe string
Stringable__toString()src/Js.php121-124Enables string casting, delegates to toHtml()

Sources: src/Js.php16 src/Js.php113-124


Conversion Pipeline

Conversion Pipeline Diagram


Sources: src/Js.php35-108


Type-Specific Processing

Type Handling in convertDataToJavaScriptExpression()

Input TypeCheck LocationProcessingOutput
Js instancesrc/Js.php57-59Return $data->toHtml() directlyJavaScript expression string
BackedEnumsrc/Js.php61-63Extract $data->valueContinue with enum value
Jsonablesrc/Js.php81-83Cast to string: (string) $dataJSON string
Arrayable (non-JsonSerializable)src/Js.php85-87Call $data->toArray()Array for encoding
String inputsrc/Js.php67-69Wrap in single quotes: '...'JavaScript string literal
Other typessrc/Js.php89Pass to json_encode()JSON representation

Processing Flow in encode()


Sources: src/Js.php55-90


Security: REQUIRED_FLAGS

The REQUIRED_FLAGS constant src/Js.php28 enforces XSS protection through mandatory JSON encoding flags:


Flag Breakdown:

FlagHex EscapePurposeExample
JSON_HEX_TAG<\u003C, >\u003EPrevents HTML tag injection<script>\u003Cscript\u003E
JSON_HEX_APOS'\u0027Prevents single-quote escapes'alert'\u0027alert\u0027
JSON_HEX_AMP&\u0026Prevents entity injectiona&ba\u0026b
JSON_HEX_QUOT"\u0022Prevents double-quote escapes"test"\u0022test\u0022
JSON_THROW_ON_ERRORN/AThrows JsonException on failureEnsures encoding success

Application Points:

MethodLocationUsage
encode()src/Js.php89json_encode($data, $flags | static::REQUIRED_FLAGS, $depth)
convertJsonToJavaScriptExpression()src/Js.php104json_encode($json, $flags | static::REQUIRED_FLAGS)

The flags are combined with user-provided flags using bitwise OR, ensuring security flags are always applied.

Sources: src/Js.php28 src/Js.php89 src/Js.php104


Output Formatting

convertJsonToJavaScriptExpression() Logic

The method src/Js.php97-108 determines JavaScript output format based on JSON structure:

Output Decision Table

JSON PatternCondition CheckJavaScript OutputExample Input → Output
[] or {}$json === '[]' || $json === '{}'Raw JSON[][]
Starts with "Str::startsWith($json, '"')JSON.parse('...')"text"JSON.parse('"text"')
Starts with {Str::startsWith($json, '{')JSON.parse('...'){"a":1}JSON.parse('{"a":1}')
Starts with [Str::startsWith($json, '[')JSON.parse('...')[1,2,3]JSON.parse('[1,2,3]')
PrimitivesOtherRaw JSONtruetrue, 123123, nullnull

JSON.parse() Wrapping Process src/Js.php104:

  1. JSON string is re-encoded with REQUIRED_FLAGS: json_encode($json, $flags | static::REQUIRED_FLAGS)
  2. Outer quotes stripped: substr(..., 1, -1)
  3. Wrapped: "JSON.parse('" . $strippedJson . "')"

This double-encoding ensures XSS protection for complex structures.

String Literal Conversion

For string inputs src/Js.php67-69:

  1. JSON encode with REQUIRED_FLAGS: $json = static::encode($data, $flags, $depth)
  2. Strip outer double quotes: substr($json, 1, -1)
  3. Wrap in single quotes: "'" . $stripped . "'"

Example: "hello" → JSON: "\"hello\"" → Strip: \"hello\" → Wrap: '\"hello\"'

Sources: src/Js.php67-69 src/Js.php97-108


Factory Method and Constructor

Js::from() Static Factory

The static factory method src/Js.php45-48 provides a convenient instantiation interface:































ParameterTypeDefaultDescription
$datamixedRequiredPHP data to convert to JavaScript
$flagsint0Additional JSON flags (combined with REQUIRED_FLAGS)
$depthint512Maximum recursion depth for json_encode()

Returns a new Js instance by delegating to the constructor.

Constructor

The constructor src/Js.php35-38 initializes the instance:


Calls convertDataToJavaScriptExpression() and stores result in the $js property src/Js.php37

Throws: JsonException if encoding fails src/Js.php33

Sources: src/Js.php35-48


Usage with View Layer

Integration Interfaces

The Js class implements interfaces for view integration src/Js.php16:

InterfaceMethodImplementation
HtmlabletoHtml()src/Js.php113-116 - Returns $this->js
Stringable__toString()src/Js.php121-124 - Delegates to toHtml()

Both methods return the same JavaScript expression stored in the $js property, enabling direct output in views and templates.

Usage Pattern

Typical workflow:


The Blade facade src/Facades/Blade.php compiles templates, while Js ensures secure data transfer from PHP to JavaScript contexts within those templates.

Sources: src/Js.php16 src/Js.php113-124 src/Facades/Blade.php1-54


Error Handling

The class enforces strict error handling through the JSON_THROW_ON_ERROR flag src/Js.php28:

  • All JSON encoding operations throw JsonException on failure
  • Constructor declares @throws JsonException src/Js.php33
  • Factory method declares @throws JsonException src/Js.php43
  • Encode method declares @throws JsonException src/Js.php77
  • Conversion method declares @throws JsonException src/Js.php53

This ensures that encoding failures are immediately visible rather than silently producing incorrect JavaScript expressions.

Sources: src/Js.php28 src/Js.php33 src/Js.php43 src/Js.php53 src/Js.php77


Dependencies

The Js class depends on several framework components:

DependencyNamespaceUsage
BackedEnumPHP 8.1+Enum value extraction src/Js.php7
ArrayableHyperf\ContractArray conversion src/Js.php8
JsonableHyperf\ContractJSON serialization src/Js.php9
StrHyperf\StringableString operations src/Js.php10
HtmlableHyperf\ViewEngine\ContractHTML-safe output src/Js.php11
JsonSerializablePHPJSON serialization interface src/Js.php13
StringablePHPString casting src/Js.php14

Sources: src/Js.php7-14