1:  2:  3:  4:  5:  6:  7:  8:  9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 
<?php
namespace Omeka\Form\Element;

use Omeka\Api\Manager as ApiManager;
use Omeka\Api\Representation\UserRepresentation;
use Zend\Form\Element\Select;

abstract class AbstractGroupByOwnerSelect extends Select
{
    /**
     * @var ApiManager
     */
    protected $apiManager;

    /**
     * @param ApiManager $apiManager
     */
    public function setApiManager(ApiManager $apiManager)
    {
        $this->apiManager = $apiManager;
    }

    /**
     * @return ApiManager
     */
    public function getApiManager()
    {
        return $this->apiManager;
    }

    /**
     * Get the resource name.
     *
     * @return string
     */
    abstract public function getResourceName();

    /**
     * Get the value label from a resource.
     *
     * @param $resource
     * @return string
     */
    abstract public function getValueLabel($resource);

    public function getValueOptions()
    {
        $query = $this->getOption('query');
        if (!is_array($query)) {
            $query = [];
        }

        // Group alphabetically by owner email.
        $resourceOwners = [];
        $response = $this->getApiManager()->search($this->getResourceName(), $query);
        foreach ($response->getContent() as $resource) {
            $owner = $resource->owner();
            $index = $owner ? $owner->email() : null;
            $resourceOwners[$index]['owner'] = $owner;
            $resourceOwners[$index]['resources'][] = $resource;
        }
        ksort($resourceOwners);

        $valueOptions = [];
        foreach ($resourceOwners as $resourceOwner) {
            $options = [];
            foreach ($resourceOwner['resources'] as $resource) {
                $options[$resource->id()] = $this->getValueLabel($resource);
                if (!$options) {
                    continue;
                }
            }
            $owner = $resourceOwner['owner'];
            if ($owner instanceof UserRepresentation) {
                $label = sprintf('%s (%s)', $owner->name(), $owner->email());
            } else {
                $label = '[No owner]';
            }
            $valueOptions[] = ['label' => $label, 'options' => $options];
        }

        $prependValueOptions = $this->getOption('prepend_value_options');
        if (is_array($prependValueOptions)) {
            $valueOptions = $prependValueOptions + $valueOptions;
        }
        return $valueOptions;
    }
}