public function add($type, $key, $settings = null, $pkg = null)
    {
        if (is_string($type)) {
            $typeFactory = $this->application->make(TypeFactory::class);
            /* @var TypeFactory $typeFactory */
            $type = $typeFactory->getByHandle($type);
        }

        // Legacy array support for $key
        $asID = false;
        if (is_array($key)) {
            $handle = $key['akHandle'];
            $name = $key['akName'];
            if (isset($key['asID'])) {
                $asID = $key['asID'];
            }
            $key = $this->createAttributeKey();
            $key->setAttributeKeyHandle($handle);
            $key->setAttributeKeyName($name);
        }

        // Legacy support for third parameter which used to be package
        if ($settings instanceof Package || $settings instanceof \Concrete\Core\Package\Package) {
            $pkg = $settings;
            $settings = null;
        }

        if (!$settings) {
            $settings = $type->getController()->getAttributeKeySettings();
        }

        $key->setAttributeType($type);
        $this->entityManager->persist($key);
        $this->entityManager->flush();

        $settings->setAttributeKey($key);
        $key->setAttributeKeySettings($settings);

        $this->entityManager->persist($settings);
        $this->entityManager->flush();

        if (is_object($pkg)) {
            $key->setPackage($pkg);
        }

        // Modify the category's search indexer.
        $indexer = $this->getSearchIndexer();
        if (is_object($indexer)) {
            $indexer->updateRepositoryColumns($this, $key);
        }

        $this->entityManager->persist($key);
        $this->entityManager->flush();

        /* legacy support, attribute set */

        if ($asID) {
            $manager = $this->getSetManager();
            $factory = new SetFactory($this->entityManager);
            $set = $factory->getByID($asID);
            if ($set !== null) {
                $manager->addKey($set, $key);
            }
        }

        return $key;
    }