<?php

namespace Autogedal\Labels\Model\Config\Source;

use Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory;
use Magento\Framework\Data\OptionSourceInterface;

class ProductAttribute implements OptionSourceInterface
{
    /**
     * @var CollectionFactory
     */
    private $attributeCollectionFactory;

    public function __construct(CollectionFactory $attributeCollectionFactory)
    {
        $this->attributeCollectionFactory = $attributeCollectionFactory;
    }

    /**
     * Return list of product attributes for dropdown
     *
     * @return array
     */
    public function toOptionArray()
    {
        $options = [
            [
                'label' => __('-- Please Select --'),
                'value' => '',
            ],
        ];

        $collection = $this->attributeCollectionFactory->create();
        // Filter out system/internal attributes that don't make sense for labels
        $collection->addVisibleFilter();

        foreach ($collection as $attribute) {
            $code = (string)$attribute->getAttributeCode();
            $label = (string)$attribute->getFrontendLabel();
            if ($label === '') {
                $label = $code;
            } else {
                $label = sprintf('%s (%s)', $label, $code);
            }

            $options[] = [
                'label' => $label,
                'value' => $code,
            ];
        }

        return $options;
    }
}

