Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
matronator committed May 22, 2024
1 parent 078028e commit a22853d
Show file tree
Hide file tree
Showing 8 changed files with 298 additions and 79 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
"symfony/validator": "^6.2 || ^7.0",
"nette/finder": "^3.0",
"opis/json-schema": "^2.3",
"matronator/parsem": "^3.0",
"matronator/parsem": "^3.1",
"guzzlehttp/guzzle": "^7.5"
},
"minimum-stability": "dev",
Expand Down
117 changes: 56 additions & 61 deletions src/Mtrgen/Registry/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
use GuzzleHttp\Exception\RequestException;
use Matronator\Mtrgen\Store\Path;
use Matronator\Mtrgen\Store\Storage;
use Matronator\Mtrgen\Template;
use Matronator\Mtrgen\Template\ClassicGenerator;
use Matronator\Mtrgen\Template\Generator;
use Matronator\Parsem\Parser;
use Symfony\Component\Console\Output\OutputInterface;

Expand Down Expand Up @@ -59,34 +62,12 @@ public function login(string $username, string $password, int $duration = 24): ?
public function getTemplate(string $identifier): object
{
[$vendor, $name] = explode('/', $identifier);

$url = $this->apiUrl . "/templates/$vendor/$name/get";

$client = new Client();
$response = $client->get($url, [
'headers' => [
'X-Requested-By' => 'cli',
],
]);
$contentType = $response->getHeaderLine('Content-Type');

switch ($contentType) {
case 'application/json':
case 'text/json':
$extension = 'json';
case 'text/x-yaml':
case 'application/x-yaml':
case 'text/yaml':
$extension = 'yaml';
case 'application/x-neon':
case 'text/x-neon':
case 'text/neon':
$extension = 'neon';
default:
$filename = $response->getHeaderLine('X-Template-Filename');
$parts = explode('.', $filename);
$extension = end($parts);
}
['client' => $client,
'extension' => $extension,
'contentType' => $contentType,
'response' => $response ] = $this->getTemplateDetails($url);

$typeUrl = $this->apiUrl . "/templates/$vendor/$name/type";
$typeResponse = $client->get($typeUrl);
Expand All @@ -103,34 +84,11 @@ public function getTemplate(string $identifier): object
public function getTemplateFromBundle(string $identifier, string $templateName): object
{
[$vendor, $name] = explode('/', $identifier);

$url = $this->apiUrl . "/bundles/$vendor/$name/$templateName/get";

$client = new Client();
$response = $client->get($url, [
'headers' => [
'X-Requested-By' => 'cli',
],
]);
$contentType = $response->getHeaderLine('Content-Type');

switch ($contentType) {
case 'application/json':
case 'text/json':
$extension = 'json';
case 'text/x-yaml':
case 'application/x-yaml':
case 'text/yaml':
$extension = 'yaml';
case 'application/x-neon':
case 'text/x-neon':
case 'text/neon':
$extension = 'neon';
default:
$filename = $response->getHeaderLine('X-Template-Filename');
$parts = explode('.', $filename);
$extension = end($parts);
}
['extension' => $extension,
'contentType' => $contentType,
'response' => $response ] = $this->getTemplateDetails($url);

return (object) [
'filename' => "$name.template.$extension",
Expand All @@ -145,12 +103,8 @@ public function postTemplate(string $path, ?OutputInterface $io = null): mixed
if (!$profile->authenticate())
return '<fg=red>You must login first.</>';

$matched = preg_match('/^(.+\/)?(.+?\.(json|yml|yaml|neon))$/', $path, $matches);
if (!$matched)
return "Couldn't get filename from path '$path'.";

$filename = $matches[2];
$template = Parser::decodeByExtension($path, file_get_contents($path));
$matches = explode(DIRECTORY_SEPARATOR, $path);
$filename = end($matches);

$profileObject = $profile->loadProfile();

Expand All @@ -161,6 +115,7 @@ public function postTemplate(string $path, ?OutputInterface $io = null): mixed
return '<fg=red>Invalid bundle.</>';

$templates = [];
$template = Parser::decodeByExtension($path, file_get_contents($path));
foreach ($template->templates as $item) {
$templates[] = (object) [
'name' => $item->name,
Expand All @@ -177,14 +132,17 @@ public function postTemplate(string $path, ?OutputInterface $io = null): mixed
];
$url = $this->apiUrl . '/bundles';
} else {
if (!Parser::isValid(Path::makeAbsolute($path), file_get_contents(Path::makeAbsolute($path))))
$contents = file_get_contents(Path::makeAbsolute($path));
$isLegacy = Template::isLegacy($path);
$name = $isLegacy ? ClassicGenerator::getName($path, $contents) : Generator::getName($contents);
if ($isLegacy && !Parser::isValid(Path::makeAbsolute($path), $contents))
return '<fg=red>Invalid template.</>';

$body = [
'username' => $profileObject->username,
'filename' => $filename,
'name' => strtolower($template->name),
'contents' => file_get_contents(Path::makeAbsolute($path)),
'name' => strtolower($name),
'contents' => $contents,
];
$url = $this->apiUrl . '/templates';
}
Expand Down Expand Up @@ -213,4 +171,41 @@ public static function isDebug()

return $config->debug ?? false;
}

private function getTemplateDetails(string $url): array
{
$client = new Client();
$response = $client->get($url, [
'headers' => [
'X-Requested-By' => 'cli',
],
]);
$contentType = $response->getHeaderLine('Content-Type');

switch ($contentType) {
case 'application/json':
case 'text/json':
$extension = 'json';
case 'text/x-yaml':
case 'text/yaml':
case 'application/x-yaml':
case 'application/yaml':
$extension = 'yaml';
case 'application/x-neon':
case 'text/x-neon':
case 'text/neon':
$extension = 'neon';
default:
$filename = $response->getHeaderLine('X-Template-Filename');
$parts = explode('.', $filename);
$extension = end($parts);
}

return [
'client' => $client,
'extension' => $extension,
'contentType' => $contentType,
'response' => $response,
];
}
}
16 changes: 8 additions & 8 deletions src/Mtrgen/Store/Storage.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ public function __construct()
* @return boolean True if save is successful, false otherwise
* @param string $filename
* @param string|null $alias Alias to save the template under instead of the name defined inside the template
* @param string|null $bundle Name of the bundle or null if not a bundle
* @param string|null $parentBundle Name of the bundle if the template belongs to a bundle or null if not a bundle
*/
public function save(string $filename, ?string $alias = null, ?string $bundle = null): bool
public function save(string $filename, ?string $alias = null, ?string $parentBundle = null): bool
{
$file = Path::canonicalize($filename);

Expand All @@ -62,12 +62,12 @@ public function save(string $filename, ?string $alias = null, ?string $bundle =
$name = Generator::getName(path: $file);
}

$basename = $bundle ? $bundle . DIRECTORY_SEPARATOR . basename($file) : basename($file);
if ($bundle && !ClassicFileGenerator::folderExist($this->templateDir . DIRECTORY_SEPARATOR . $bundle) && !mkdir($concurrentDirectory = $this->templateDir . DIRECTORY_SEPARATOR . $bundle, 0777, true) && !is_dir($concurrentDirectory)) {
$basename = $parentBundle ? $parentBundle . DIRECTORY_SEPARATOR . basename($file) : basename($file);
if ($parentBundle && !ClassicFileGenerator::folderExist($this->templateDir . DIRECTORY_SEPARATOR . $parentBundle) && !mkdir($concurrentDirectory = $this->templateDir . DIRECTORY_SEPARATOR . $parentBundle, 0777, true) && !is_dir($concurrentDirectory)) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
}

$this->saveEntry($alias ?? ($bundle ? "$bundle:" . $name : $name), $basename);
$this->saveEntry($alias ?? ($parentBundle ? $parentBundle . ':' . $name : $name), $basename);
copy($file, Path::canonicalize($this->templateDir . DIRECTORY_SEPARATOR . $basename));

return true;
Expand All @@ -90,7 +90,7 @@ public function saveBundle(object $bundleObject, string $format = 'json'): bool
$contents = Neon::encode($bundleObject, true);
break;
default:
throw new InvalidArgumentException('Unsupported format.');
throw new InvalidArgumentException('Unsupported bundle format.');
}

$filename = "$name.bundle.$format";
Expand Down Expand Up @@ -164,10 +164,10 @@ public function saveFolder(string $path): ?int

$store = $this->loadStore();

$files = Finder::findFiles('*.template.yaml', '*.template.json', '*.template.neon')->in($path);
$files = Finder::findFiles('*.template.*', '*.mtr.*', '*.mtr')->in($path);
$added = 0;
foreach ($files as $key => $file) {
if (!Parser::isValid($key)) continue;
if (!Parser::isValid($key, $file->read())) continue;

$store = $this->entry($store, ClassicGenerator::getName($key), $key);
$added++;
Expand Down
4 changes: 1 addition & 3 deletions src/Mtrgen/Template.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ public static function isLegacy(string $path): bool
if (!$contents) {
throw new TemplateNotFoundException($path);
}
if (Parser::isValid($path, $contents)) {
return true;
} else if (Parser::isValidBundle($path, $contents)) {
if (Parser::isValid($path, $contents) || Parser::isValidBundle($path, $contents)) {
return true;
}
}
Expand Down
10 changes: 4 additions & 6 deletions src/Mtrgen/Template/Generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,13 @@

class Generator
{
public const RESERVED_KEYWORDS = ClassicGenerator::RESERVED_KEYWORDS;
public const RESERVED_CONSTANTS = ClassicGenerator::RESERVED_CONSTANTS;

public const HEADER_PATTERN = '/^\S+ --- MTRGEN ---.(.+)\s\S+ --- MTRGEN ---/ms';

public const COMMENT_PATTERN = '/\/\*\s?([a-zA-Z0-9_]+)\|?(([a-zA-Z0-9_]+?)(?:\:(?:(?:\'|")?\w(?:\'|")?,?)+?)*?)?\s?\*\//m';

public static function parseAnyFile(string $path, array $arguments = [], bool $useCommentSyntax = false): GenericFileObject
{
$file = file_get_contents($path);
$file = ltrim(file_get_contents($path));

if (!$file) {
throw new \RuntimeException(sprintf('File "%s" was not found', $path));
Expand Down Expand Up @@ -57,7 +54,8 @@ private static function write(GenericFileObject $file): void
}

file_put_contents(Path::safe(str_ends_with($file->directory, DIRECTORY_SEPARATOR)
? $file->directory . $file->filename : $file->directory . DIRECTORY_SEPARATOR . $file->filename), $file->contents);
? $file->directory . $file->filename
: $file->directory . DIRECTORY_SEPARATOR . $file->filename), $file->contents);
}

/**
Expand All @@ -73,7 +71,7 @@ public static function getName(?string $content = null, ?string $path = null): s
throw new \RuntimeException('Either content or path must be provided.');
}
if (!$content && $path) {
$content = file_get_contents($path);
$content = file_get_contents(Path::canonicalize($path));
}
return static::getTemplateHeader($content)->name;
}
Expand Down
Loading

0 comments on commit a22853d

Please sign in to comment.