Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ The MageForge Inspector lets you inspect Magento blocks, templates, and performa
**Features:**

- Template paths, block classes, and module names
- 1-click **Open in IDE** (PhpStorm, VS Code, Cursor, Zed, Sublime Text, or custom URL) with browser-saved Docker/DDEV host path mapping
- 1-click **Override & Open** directly into any editable `app/design/frontend` theme, including automatic cache cleaning
- PHP render times and cache status (lifetime, tags)
- Web Vitals: LCP, CLS, INP per element
- Accessibility checks: ARIA roles, contrast ratios, alt text
Expand Down
117 changes: 117 additions & 0 deletions src/Block/Inspector.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,19 @@

namespace OpenForgeProject\MageForge\Block;

use Magento\Framework\App\Area;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\State;
use Magento\Framework\Component\ComponentRegistrar;
use Magento\Framework\Component\ComponentRegistrarInterface;
use Magento\Framework\View\DesignInterface;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use OpenForgeProject\MageForge\Model\Config\Inspector as InspectorConfig;
use OpenForgeProject\MageForge\Model\ThemeList;
use OpenForgeProject\MageForge\Service\DeveloperAccessChecker;
use OpenForgeProject\MageForge\Service\Inspector\OverrideTokenManager;

/**
* Block for MageForge Inspector
Expand All @@ -23,6 +30,11 @@
* @param State $state
* @param ScopeConfigInterface $scopeConfig
* @param DeveloperAccessChecker $developerAccessChecker
* @param OverrideTokenManager $overrideTokenManager
* @param ThemeList $themeList
* @param ComponentRegistrarInterface $componentRegistrar
* @param DirectoryList $directoryList
* @param DesignInterface $design
* @param array $data
* @phpstan-param array<string, mixed> $data
*/
Expand All @@ -31,6 +43,11 @@
private readonly State $state,
private readonly ScopeConfigInterface $scopeConfig,
private readonly DeveloperAccessChecker $developerAccessChecker,
private readonly OverrideTokenManager $overrideTokenManager,
private readonly ThemeList $themeList,
private readonly ComponentRegistrarInterface $componentRegistrar,
private readonly DirectoryList $directoryList,
private readonly DesignInterface $design,
array $data = [],
) {
parent::__construct($context, $data);
Expand Down Expand Up @@ -188,6 +205,106 @@
return is_string($value) && $value !== '' ? $value : InspectorConfig::DEFAULT_INSPECTOR_SHORTCUT;
}

/**
* Get URL for the 1-click template override endpoint
*
* @return string
*/
public function getOverrideUrl(): string
{
return $this->getUrl('mageforge/inspector/override');
}

/**
* Get HMAC security token for 1-click template override requests
*
* @return string
*/
public function getOverrideToken(): string
{
return $this->overrideTokenManager->generate();
}

/**
* Get normalized Magento root path on the server
*
* @return string
*/
public function getMagentoRoot(): string
{
return rtrim(str_replace('\\', '/', $this->directoryList->getRoot()), '/');
}

/**
* Get currently active frontend theme code
*
* @return string
*/
public function getActiveThemeCode(): string
{
return $this->design->getDesignTheme()->getCode();
}

/**
* Get registered frontend themes as JSON metadata for the target theme selector
*
* Editable themes (outside vendor/, e.g. app/design/frontend/...) are sorted first.
*
* @return string
*/
public function getFrontendThemesJson(): string
{
$root = $this->getMagentoRoot();
$editable = [];
$readOnly = [];

foreach ($this->themeList->getAllThemes() as $theme) {
if ($theme->getArea() !== Area::AREA_FRONTEND) {
continue;
}

$code = $theme->getCode();
if ($code === '') {
continue;
}

$fullPath = $theme->getFullPath();
$themePath = is_string($fullPath) && $fullPath !== ''

Check warning on line 272 in src/Block/Inspector.php

View workflow job for this annotation

GitHub Actions / Mutation Tests (Infection)

Escaped Mutant for Mutator "LogicalAnd": @@ @@ } $fullPath = $theme->getFullPath(); - $themePath = is_string($fullPath) && $fullPath !== '' + $themePath = is_string($fullPath) || $fullPath !== '' ? $this->componentRegistrar->getPath(ComponentRegistrar::THEME, $fullPath) : null; $relativePath = '';
? $this->componentRegistrar->getPath(ComponentRegistrar::THEME, $fullPath)
: null;
$relativePath = '';
if (is_string($themePath) && $themePath !== '') {

Check warning on line 276 in src/Block/Inspector.php

View workflow job for this annotation

GitHub Actions / Mutation Tests (Infection)

Escaped Mutant for Mutator "LogicalAnd": @@ @@ ? $this->componentRegistrar->getPath(ComponentRegistrar::THEME, $fullPath) : null; $relativePath = ''; - if (is_string($themePath) && $themePath !== '') { + if (is_string($themePath) || $themePath !== '') { $normalizedPath = rtrim(str_replace('\\', '/', $themePath), '/'); $relativePath = $root !== '' && str_starts_with($normalizedPath, $root . '/') ? substr($normalizedPath, strlen($root) + 1)
$normalizedPath = rtrim(str_replace('\\', '/', $themePath), '/');

Check warning on line 277 in src/Block/Inspector.php

View workflow job for this annotation

GitHub Actions / Mutation Tests (Infection)

Escaped Mutant for Mutator "UnwrapRtrim": @@ @@ : null; $relativePath = ''; if (is_string($themePath) && $themePath !== '') { - $normalizedPath = rtrim(str_replace('\\', '/', $themePath), '/'); + $normalizedPath = str_replace('\\', '/', $themePath); $relativePath = $root !== '' && str_starts_with($normalizedPath, $root . '/') ? substr($normalizedPath, strlen($root) + 1) : $normalizedPath;

Check warning on line 277 in src/Block/Inspector.php

View workflow job for this annotation

GitHub Actions / Mutation Tests (Infection)

Escaped Mutant for Mutator "UnwrapStrReplace": @@ @@ : null; $relativePath = ''; if (is_string($themePath) && $themePath !== '') { - $normalizedPath = rtrim(str_replace('\\', '/', $themePath), '/'); + $normalizedPath = rtrim($themePath, '/'); $relativePath = $root !== '' && str_starts_with($normalizedPath, $root . '/') ? substr($normalizedPath, strlen($root) + 1) : $normalizedPath;
$relativePath = $root !== '' && str_starts_with($normalizedPath, $root . '/')

Check warning on line 278 in src/Block/Inspector.php

View workflow job for this annotation

GitHub Actions / Mutation Tests (Infection)

Escaped Mutant for Mutator "LogicalAnd": @@ @@ $relativePath = ''; if (is_string($themePath) && $themePath !== '') { $normalizedPath = rtrim(str_replace('\\', '/', $themePath), '/'); - $relativePath = $root !== '' && str_starts_with($normalizedPath, $root . '/') + $relativePath = $root !== '' || str_starts_with($normalizedPath, $root . '/') ? substr($normalizedPath, strlen($root) + 1) : $normalizedPath; }

Check warning on line 278 in src/Block/Inspector.php

View workflow job for this annotation

GitHub Actions / Mutation Tests (Infection)

Escaped Mutant for Mutator "ConcatOperandRemoval": @@ @@ $relativePath = ''; if (is_string($themePath) && $themePath !== '') { $normalizedPath = rtrim(str_replace('\\', '/', $themePath), '/'); - $relativePath = $root !== '' && str_starts_with($normalizedPath, $root . '/') + $relativePath = $root !== '' && str_starts_with($normalizedPath, $root) ? substr($normalizedPath, strlen($root) + 1) : $normalizedPath; }

Check warning on line 278 in src/Block/Inspector.php

View workflow job for this annotation

GitHub Actions / Mutation Tests (Infection)

Escaped Mutant for Mutator "ConcatOperandRemoval": @@ @@ $relativePath = ''; if (is_string($themePath) && $themePath !== '') { $normalizedPath = rtrim(str_replace('\\', '/', $themePath), '/'); - $relativePath = $root !== '' && str_starts_with($normalizedPath, $root . '/') + $relativePath = $root !== '' && str_starts_with($normalizedPath, '/') ? substr($normalizedPath, strlen($root) + 1) : $normalizedPath; }
? substr($normalizedPath, strlen($root) + 1)
: $normalizedPath;
}

$isEditable = $relativePath !== '' && !str_starts_with($relativePath, 'vendor/');
$entry = [
'code' => $code,
'path' => $relativePath,
'editable' => $isEditable,
];

if ($isEditable) {
$editable[$code] = $entry;
} else {
$readOnly[$code] = $entry;
}
}

ksort($editable);
ksort($readOnly);

Check warning on line 298 in src/Block/Inspector.php

View workflow job for this annotation

GitHub Actions / Mutation Tests (Infection)

Escaped Mutant for Mutator "FunctionCallRemoval": @@ @@ } ksort($editable); - ksort($readOnly); + $encoded = json_encode( array_values([...$editable, ...$readOnly]),

$encoded = json_encode(
array_values([...$editable, ...$readOnly]),
JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,

Check warning on line 302 in src/Block/Inspector.php

View workflow job for this annotation

GitHub Actions / Mutation Tests (Infection)

Escaped Mutant for Mutator "BitwiseOr": @@ @@ $encoded = json_encode( array_values([...$editable, ...$readOnly]), - JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE, + JSON_UNESCAPED_SLASHES & JSON_UNESCAPED_UNICODE, ); return $encoded !== false ? $encoded : '[]';
);

return $encoded !== false ? $encoded : '[]';
}

/**
* Render block HTML
*
Expand Down
4 changes: 2 additions & 2 deletions src/Console/Command/System/CheckCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -659,7 +659,7 @@ private function getImportantPhpExtensions(): array
*/
private function getPhpMemoryLimit(): string
{
return (string) ini_get('memory_limit');
return ini_get('memory_limit') ?: '';
}

/**
Expand Down Expand Up @@ -810,7 +810,7 @@ private function getSystemEnvironmentValue(string $name): ?string
{
// Use ini_get for certain system variables as a safer alternative
if (in_array($name, ['memory_limit', 'max_execution_time'], true)) {
$value = (string) ini_get($name);
$value = ini_get($name) ?: '';
if ($value !== '') {
return $value;
}
Expand Down
208 changes: 208 additions & 0 deletions src/Controller/Inspector/Override.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
<?php

declare(strict_types=1);

namespace OpenForgeProject\MageForge\Controller\Inspector;

use InvalidArgumentException;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\App\Request\InvalidRequestException;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\State;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\Result\JsonFactory;
use OpenForgeProject\MageForge\Model\Config\Inspector as InspectorConfig;
use OpenForgeProject\MageForge\Service\DeveloperAccessChecker;
use OpenForgeProject\MageForge\Service\Inspector\OverrideTokenManager;
use OpenForgeProject\MageForge\Service\TemplateOverride\BrowserTemplateOverrider;
use Throwable;

/**
* Developer-only AJAX endpoint for 1-click template overrides from the frontend Inspector
*/
class Override implements HttpPostActionInterface, CsrfAwareActionInterface
{
public const SIGNATURE_HEADER = 'X-MageForge-Token';

/**
* @param RequestInterface $request
* @param JsonFactory $jsonFactory
* @param State $state
* @param ScopeConfigInterface $scopeConfig
* @param DeveloperAccessChecker $developerAccessChecker
* @param OverrideTokenManager $tokenManager
* @param BrowserTemplateOverrider $templateOverrider
*/
public function __construct(
private readonly RequestInterface $request,
private readonly JsonFactory $jsonFactory,
private readonly State $state,
private readonly ScopeConfigInterface $scopeConfig,
private readonly DeveloperAccessChecker $developerAccessChecker,
private readonly OverrideTokenManager $tokenManager,
private readonly BrowserTemplateOverrider $templateOverrider,
) {
}

/**
* Create a JSON 403 error response when CSRF/token validation fails
*
* @param RequestInterface $request
* @return InvalidRequestException|null
* @SuppressWarnings("PHPMD.UnusedFormalParameter")
*/
public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException
{
return new InvalidRequestException($this->createJsonResponse(403, [
'success' => false,
'message' => 'Invalid or missing security token.',
]));
}

/**
* Require POST, XHR header, and a valid installation HMAC token
*
* @param RequestInterface $request
* @return bool|null
*/
public function validateForCsrf(RequestInterface $request): ?bool
{
return $this->isAuthorizedRequest($request);
}

/**
* Execute the 1-click template override action
*
* @return Json
*/
public function execute(): Json
{
if (!$this->isInspectorAvailable()) {
return $this->createJsonResponse(403, [
'success' => false,
'message' => 'MageForge Inspector is not available.',
]);
}

if (!$this->isAuthorizedRequest($this->request)) {
return $this->createJsonResponse(403, [
'success' => false,
'message' => 'Invalid or missing security token.',
]);
}

[$template, $theme] = $this->extractPayload();

try {
$result = $this->templateOverrider->override($template, $theme);

return $this->createJsonResponse(200, [
'success' => true,
'created' => $result->created,
'targetPath' => $result->targetPath,
'sourcePath' => $result->sourcePath,
'themeCode' => $result->themeCode,
'templateId' => $result->templateId,
]);
} catch (InvalidArgumentException $e) {
return $this->createJsonResponse(400, [
'success' => false,
'message' => $e->getMessage(),
]);
} catch (Throwable $e) {
return $this->createJsonResponse(500, [
'success' => false,
'message' => $e->getMessage(),
]);
}
}

/**
* Check developer mode, Inspector config flag, and allowed IP
*
* @return bool
*/
private function isInspectorAvailable(): bool
{
if ($this->state->getMode() !== State::MODE_DEVELOPER) {
return false;
}

if (!$this->scopeConfig->isSetFlag(InspectorConfig::XML_PATH_ENABLED, InspectorConfig::SCOPE_STORE)) {
return false;
}

return $this->developerAccessChecker->isDevAllowed();
}

/**
* Verify HTTP method, AJAX header, and HMAC token header
*
* @param RequestInterface $request
* @return bool
*/
private function isAuthorizedRequest(RequestInterface $request): bool
{
if (!$request instanceof HttpRequest || !$request->isPost() || !$request->isXmlHttpRequest()) {
return false;
}

$token = $request->getHeader(self::SIGNATURE_HEADER);
if (!is_string($token)) {
return false;
}

return $this->tokenManager->isValid(trim($token));
}

/**
* Extract template and theme fields from JSON body or request params
*
* @return array{0: string, 1: string}
*/
private function extractPayload(): array
{
if ($this->request instanceof HttpRequest) {
$rawContent = $this->request->getContent();
if ($rawContent !== '') {
$decoded = json_decode($rawContent, true);
if (is_array($decoded)) {
$template = isset($decoded['template']) && is_string($decoded['template'])
? $decoded['template']
: '';
$theme = isset($decoded['theme']) && is_string($decoded['theme']) ? $decoded['theme'] : '';

return [$template, $theme];
}
}
}

$templateParam = $this->request->getParam('template');
$themeParam = $this->request->getParam('theme');

return [
is_string($templateParam) ? $templateParam : '',
is_string($themeParam) ? $themeParam : '',
];
}

/**
* Build a JSON result with status code and payload
*
* @param int $statusCode
* @param array $payload
* @phpstan-param array<string, bool|string> $payload
* @return Json
*/
private function createJsonResponse(int $statusCode, array $payload): Json
{
$result = $this->jsonFactory->create();
$result->setHttpResponseCode($statusCode);
$result->setData($payload);

return $result;
}
}
Loading
Loading