Skip to content

Instantly share code, notes, and snippets.

@nklatt
Last active July 7, 2021 18:34
Show Gist options
  • Save nklatt/9e060d8d42884e5698f5bea6c302f81c to your computer and use it in GitHub Desktop.
Save nklatt/9e060d8d42884e5698f5bea6c302f81c to your computer and use it in GitHub Desktop.
Magento 2 CLI product attribute value checker
I needed a way to check the value of a product attribute so whipped up this
little command line interface tool to do it. It accepts a SKU and a product
attribute code and outputs the value of that attribute for that product.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Framework\Console\CommandListInterface">
<arguments>
<argument name="commands" xsi:type="array">
<item name="hutman_get_product_attribute_value" xsi:type="object">Hutman\Utilities\Console\Command\GetProductAttributeValue</item>
</argument>
</arguments>
</type>
<type name="Hutman\Utilities\Console\Command\GetProductAttributeValue">
<arguments>
<argument name="productRepository" xsi:type="object">Magento\Catalog\Model\ProductRepository</argument>
</arguments>
</type>
</config>
<?php
namespace Hutman\Utilities\Console\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class GetProductAttributeValue extends Command
{
protected $productRepository;
public function __construct(\Magento\Catalog\Model\ProductRepository $productRepository) {
$this->productRepository = $productRepository;
parent::__construct();
}
protected function configure() {
$options = array(
new InputOption('sku', null, InputOption::VALUE_REQUIRED, 'Product SKU'),
new InputOption('att', null, InputOption::VALUE_REQUIRED, 'Product Attribute Code'),
);
$this
->setName('hutman:get-product-attribute-value')
->setDescription('Get the value for the specified attribute for product with specified sku.')
->setDefinition($options);
parent::configure();
}
protected function execute(InputInterface $input, OutputInterface $output) {
$retval = \Magento\Framework\Console\Cli::RETURN_FAILURE;
$sku = $input->getOption('sku');
$att = $input->getOption('att');
$product = $this->productRepository->get($sku);
if ($product) {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product_data = $objectManager->create('\Magento\Catalog\Model\Product')->load($product->getId());
$value = $product_data->getData($att);
$output->writeln(var_export($value,1));
$retval = \Magento\Framework\Console\Cli::RETURN_SUCCESS;
}
return $retval;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment