PHP code example of scriptua / magento2-base
1. Go to this page and download the library: Download scriptua/magento2-base library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
scriptua / magento2-base example snippets
/** @var Magento\Framework\View\Element\Template $block */
/** @var Hryvinskyi\Base\Model\ViewModelRegistry $viewModels */
// Get any view model by class name
$productViewModel = $viewModels->ire(\Vendor\Module\ViewModel\Esi::class, $block);
// Use the view model
echo $productViewModel->getProductName();
// Main page - cache tags collected normally
$viewModel = $viewModels->lution
$viewModel = $viewModels->
use Hryvinskyi\Base\Helper\ArrayHelper;
// Dot notation access
$username = ArrayHelper::getValue($_POST, 'user.profile.username', 'guest');
ArrayHelper::setValue($config, 'database.host', 'localhost');
// Array merging with smart handling
$merged = ArrayHelper::merge(
['items' => ['apple', 'banana']],
['items' => ['cherry']]
);
// Result: ['items' => ['apple', 'banana', 'cherry']]
// Indexing and grouping
$users = [
['id' => 1, 'name' => 'John', 'role' => 'admin'],
['id' => 2, 'name' => 'Jane', 'role' => 'user'],
['id' => 3, 'name' => 'Bob', 'role' => 'admin'],
];
$indexed = ArrayHelper::index($users, 'id');
// Result: [1 => [...], 2 => [...], 3 => [...]]
$grouped = ArrayHelper::index($users, null, 'role');
// Result: ['admin' => [[...], [...]], 'user' => [[...]]]
// Column extraction
$ids = ArrayHelper::getColumn($users, 'id');
// Result: [1, 2, 3]
// Multi-key sorting
ArrayHelper::multisort($users, ['role', 'name'], [SORT_ASC, SORT_DESC]);
// Object conversion with custom property mapping
$array = ArrayHelper::toArray($object, [
'id',
'username' => 'name',
'fullName' => function($obj) { return $obj->firstName . ' ' . $obj->lastName; }
]);
// Filtering with conditions
$filtered = ArrayHelper::filter($users, [
'id' => [1, 2], // Include only these IDs
'role' => 'admin' // Only admins
]);
// Map creation
$nameMap = ArrayHelper::map($users, 'id', 'name');
// Result: [1 => 'John', 2 => 'Jane', 3 => 'Bob']
// Force replacement in merge
use Hryvinskyi\Base\Helper\ReplaceArrayValue;
$merged = ArrayHelper::merge(
['items' => ['a', 'b']],
['items' => new ReplaceArrayValue(['c', 'd'])]
);
// Result: ['items' => ['c', 'd']] (replaced, not merged)
use Hryvinskyi\Base\Helper\Html;
// Generate links
echo Html::a('Visit site', 'https://example.com', ['class' => 'external-link', 'target' => '_blank']);
echo Html::mailto('Contact us', '[email protected] ');
// Create forms
echo Html::beginForm('/checkout/submit', 'post', $formKey, ['id' => 'checkout-form']);
echo Html::textInput('email', '', ['class' => 'form-control', 'nited Kingdom'
], ['class' => 'country-select']);
// Checkbox/radio lists
echo Html::checkboxList('features', ['wifi', 'parking'], [
'wifi' => 'WiFi',
'parking' => 'Parking',
'pool' => 'Swimming Pool'
]);
// Lists
echo Html::ul(['Apple', 'Banana', 'Cherry'], [
'class' => 'fruit-list',
'item' => function($item, $index) {
return Html::tag('span', $item, ['data-index' => $index]);
}
]);
// CSS class manipulation
$options = ['class' => 'btn'];
Html::addCssClass($options, 'btn-primary btn-lg');
Html::removeCssClass($options, 'btn-lg');
// Result: ['class' => 'btn btn-primary']
// Style manipulation
$options = [];
Html::addCssStyle($options, 'color: red');
Html::addCssStyle($options, ['font-size' => '14px', 'margin' => '10px']);
// Result: ['style' => 'color: red; font-size: 14px; margin: 10px;']
// Asset tags with IE conditional comments
echo Html::cssFile('/css/style.css', ['media' => 'screen']);
echo Html::cssFile('/css/ie8.css', ['condition' => 'lt IE 9']);
echo Html::jsFile('/js/script.js', ['async' => true]);
// Custom tags with data attributes
echo Html::tag('div', 'Content', [
'class' => 'container',
'data-module' => 'carousel',
'data-options' => ['autoplay' => true, 'delay' => 3000]
]);
use Hryvinskyi\Base\Helper\Json;
// Basic encoding
$json = Json::encode(['name' => 'John', 'age' => 30]);
// Pretty printing
Json::$prettyPrint = true;
$prettyJson = Json::encode(['name' => 'John', 'age' => 30]);
/*
{
"name": "John",
"age": 30
}
*/
// HTML-safe encoding for embedding in attributes
$safeJson = Json::htmlEncode(['alert' => '<script>alert("xss")</script>']);
echo '<div data-config="' . $safeJson . '">'; // Safely embedded
// Object type preservation
Json::$keepObjectType = true;
$json = Json::encode((object)['test']);
// Result: {"0":"test"} instead of ["test"]
// Decoding with error handling
try {
$data = Json::decode($jsonString);
} catch (\Hryvinskyi\Base\Helper\InvalidParamException $e) {
// Handle JSON decode error
echo "Invalid JSON: " . $e->getMessage();
}
// Decode as object instead of array
$object = Json::decode($jsonString, false);
use Hryvinskyi\Base\Helper\VarDumper;
// Basic dumping
VarDumper::dump($complexObject);
// With depth limit and syntax highlighting
VarDumper::dump($deeplyNestedArray, 10, true);
// Get dump as string for logging
$debugInfo = VarDumper::dumpAsString($data, 5);
$logger->debug($debugInfo);
// Export as PHP code
$code = VarDumper::export(['name' => 'John', 'items' => [1, 2, 3]]);
// Result: "['name' => 'John', 'items' => [1, 2, 3,],]"
// Export complex objects (uses serialize/unserialize)
$code = VarDumper::export($product);
// Result: "unserialize('...')"
// Export closures (extracts source code)
$closure = function($x) { return $x * 2; };
$code = VarDumper::export($closure);
// Result: "function($x) { return $x * 2; }"
// Handle circular references safely
$a = ['x' => 1];
$a['self'] = &$a;
VarDumper::dump($a); // Safely handles the circular reference
use Hryvinskyi\Base\Helper\ConsoleHelper;
ConsoleHelper::moveCursorUp(2); // Move cursor up 2 rows
ConsoleHelper::moveCursorDown(1); // Move cursor down 1 row
ConsoleHelper::moveCursorForward(5); // Move cursor right 5 columns
ConsoleHelper::moveCursorBackward(3); // Move cursor left 3 columns
ConsoleHelper::moveCursorNextLine(2); // Move to beginning of 2nd line down
ConsoleHelper::moveCursorPrevLine(1); // Move to beginning of 1 line up
ConsoleHelper::moveCursorTo(10, 5); // Move to column 10, row 5
ConsoleHelper::saveCursorPosition(); // Save current position
ConsoleHelper::restoreCursorPosition(); // Restore saved position
ConsoleHelper::hideCursor(); // Hide cursor
ConsoleHelper::showCursor(); // Show cursor
ConsoleHelper::clearScreen(); // Clear entire screen
ConsoleHelper::clearScreenBeforeCursor(); // Clear from cursor to top
ConsoleHelper::clearScreenAfterCursor(); // Clear from cursor to bottom
ConsoleHelper::clearLine(); // Clear current line
ConsoleHelper::clearLineBeforeCursor(); // Clear line before cursor
ConsoleHelper::clearLineAfterCursor(); // Clear line after cursor
ConsoleHelper::scrollUp(3); // Scroll up 3 lines
ConsoleHelper::scrollDown(2); // Scroll down 2 lines
// Foreground colors
ConsoleHelper::FG_BLACK, FG_RED, FG_GREEN, FG_YELLOW
ConsoleHelper::FG_BLUE, FG_PURPLE, FG_CYAN, FG_GREY
// Background colors
ConsoleHelper::BG_BLACK, BG_RED, BG_GREEN, BG_YELLOW
ConsoleHelper::BG_BLUE, BG_PURPLE, BG_CYAN, BG_GREY
// Text styles
ConsoleHelper::BOLD, ITALIC, UNDERLINE, BLINK
ConsoleHelper::NEGATIVE, CONCEALED, CROSSED_OUT
ConsoleHelper::FRAMED, ENCIRCLED, OVERLINED
// Apply formatting
ConsoleHelper::beginAnsiFormat([ConsoleHelper::FG_RED, ConsoleHelper::BOLD]);
echo "Error message";
ConsoleHelper::endAnsiFormat();
// Format string
$formatted = ConsoleHelper::ansiFormat('Warning', [ConsoleHelper::FG_YELLOW, ConsoleHelper::BOLD]);
// xterm 256 colors
$fgColor = ConsoleHelper::xtermFgColor(208); // Orange
$bgColor = ConsoleHelper::xtermBgColor(235); // Dark gray
echo ConsoleHelper::ansiFormat('Text', [$fgColor, $bgColor]);
// Color codes in strings (irssi-style)
$text = ConsoleHelper::renderColoredString('%R[ERROR]%n %yWarning message', true);
// %R = red bold, %n = reset, %y = yellow
// Convert ANSI to HTML
$html = ConsoleHelper::ansiToHtml($ansiString);
// Strip ANSI codes
$plain = ConsoleHelper::stripAnsiFormat($ansiString);
$length = ConsoleHelper::ansiStrlen($ansiString); // Length without codes
// Output
ConsoleHelper::stdout("Message"); // Print to STDOUT
ConsoleHelper::stderr("Error"); // Print to STDERR
ConsoleHelper::output("Line"); // Print line to STDOUT
ConsoleHelper::error("Error"); // Print line to STDERR
// Input
$input = ConsoleHelper::stdin(); // Read from STDIN
$input = ConsoleHelper::input("Name: "); // Prompt and read
// Prompt with validation
$email = ConsoleHelper::prompt("Email: ", [
'hoose action:", [
'c' => 'Create',
'r' => 'Read',
'u' => 'Update',
'd' => 'Delete'
]);
// Simple progress bar
ConsoleHelper::startProgress(0, 1000);
for ($i = 1; $i <= 1000; $i++) {
usleep(1000);
ConsoleHelper::updateProgress($i, 1000);
}
ConsoleHelper::endProgress();
// With prefix
ConsoleHelper::startProgress(0, 100, 'Processing: ');
// ... update progress ...
ConsoleHelper::endProgress("Done!\n");
// Git-style (status only, no bar)
ConsoleHelper::startProgress(0, 1000, 'Counting objects: ', false);
// ... update progress ...
ConsoleHelper::endProgress("done.\n");
// Custom width
ConsoleHelper::startProgress(0, 100, '', 0.5); // 50% of screen width
ConsoleHelper::startProgress(0, 100, '', 80); // 80 characters wide
// Platform detection
if (ConsoleHelper::isRunningOnWindows()) {
// Windows-specific code
}
// ANSI support detection
if (ConsoleHelper::streamSupportsAnsiColors(STDOUT)) {
// Use colored output
}
// Screen size
list($width, $height) = ConsoleHelper::getScreenSize();
list($width, $height) = ConsoleHelper::getScreenSize(true); // Force refresh
// Text wrapping with indentation
$wrapped = ConsoleHelper::wrapText($longText, 4);
/*
Lorem ipsum
dolor sit
amet.
*/
// Escape color codes
$escaped = ConsoleHelper::escape("String with %y color codes");
use Hryvinskyi\Base\Helper\ConsoleHelper;
class MyCommand extends \Symfony\Component\Console\Command\Command
{
protected function execute($input, $output)
{
// Header
ConsoleHelper::output(ConsoleHelper::ansiFormat('=== Deployment Script ===', [
ConsoleHelper::FG_GREEN,
ConsoleHelper::BOLD
]));
// Confirmation
if (!ConsoleHelper::confirm("Deploy to production?", false)) {
ConsoleHelper::output(ConsoleHelper::ansiFormat('Cancelled', [ConsoleHelper::FG_YELLOW]));
return 0;
}
// Progress
$tasks = ['compile', 'test', 'deploy', 'cleanup'];
ConsoleHelper::startProgress(0, count($tasks), 'Progress: ');
foreach ($tasks as $i => $task) {
sleep(1);
ConsoleHelper::updateProgress($i + 1, count($tasks));
}
ConsoleHelper::endProgress(ConsoleHelper::ansiFormat('✓ Completed!', [
ConsoleHelper::FG_GREEN
]) . "\n");
return 0;
}
}