Install the default pagepart configuration.

@param BundleInterface $bundle
772333
protected function installDefaultPagePartConfiguration($bundle)
    {
        // Pagepart configuration
        if ($this->isSymfony4()) {
            $dirPath = $this->container->getParameter('kernel.project_dir') . '/config/kunstmaancms/pageparts/';
        } else {
            $dirPath = sprintf('%s/Resources/config/pageparts/', $bundle->getPath());
        }

        $skeletonDir = sprintf('%s/Resources/config/pageparts/', GeneratorUtils::getFullSkeletonPath('/common'));

        // Only copy when folder does not exist yet
        if (!$this->filesystem->exists($dirPath)) {
            $files = array('footer.yml', 'main.yml', 'left-sidebar.yml', 'right-sidebar.yml');
            foreach ($files as $file) {
                $this->filesystem->copy($skeletonDir . $file, $dirPath . $file, false);
            }
        }
    }
1070110
protected function getAvailablePages(BundleInterface $bundle)
    {
        $pages = [];
        $counter = 1;

        // Get the available pages from disc
        $dir = $bundle->getPath().'/Entity/Pages/';
        if (file_exists($dir) && is_dir($dir)) {
            $finder = new Finder();
            $finder->files()->in($dir)->depth('== 0');
            foreach ($finder as $file) {
                $pages[$counter++] = [
                    'name' => substr($file->getFileName(), 0, strlen($file->getFileName()) - 4),
                    'path' => $file->getPathName(),
                ];
            }
        }

        return $pages;
    }
1144457
private function generatePageTemplateConfiguration()
    {
        $this->installDefaultPageTemplates($this->bundle);
        $this->installDefaultPagePartConfiguration($this->bundle);

        $this->assistant->writeLine('Generating template configuration : <info>OK</info>');
    }
637413
public function setBundle(AbstractBundle $bundle)
    {
        $data = $bundle->getValues();
        foreach ($data as $name => $value) {
            $query = $this->getNewQuery();
            $query = $bundle->makeQueryFiltered($query);
            $setting = $query->firstOrNew(['name' => $name]);
            $setting->value = $value;
            $setting->save();
        }
    }
1217231
public function generate(BundleInterface $bundle, $prefix, $rootDir, $demosite = false)
    {
        $this->bundle = $bundle;
        $this->prefix = GeneratorUtils::cleanPrefix($prefix);
        $this->rootDir = $rootDir;
        $this->demosite = $demosite;

        $parameters = array(
            'namespace' => $this->bundle->getNamespace(),
            'bundle' => $this->bundle,
            'bundle_name' => $this->bundle->getName(),
            'prefix' => $this->prefix,
            'demosite' => $this->demosite,
            'multilanguage' => $this->isMultiLangEnvironment(),
            'isV4' => $this->isSymfony4(),
        );

        $this->generateControllers($parameters);
        $this->generateAdminLists($parameters);
        $this->generateEntities($parameters);
        $this->generateFormTypes($parameters);
        $this->generateTwigExtensions($parameters);
        $this->generateMenuAdaptors($parameters);
        $this->generateFixtures($parameters);
        $this->generatePagepartConfigs($parameters);
        $this->generatePagetemplateConfigs($parameters);
        $this->generateConfig();
        $this->generateRouting($parameters);
        $this->generateTemplates($parameters);
    }
260158
private function findTemplatesInThemes(BundleInterface $bundle, $theme)
    {
        $templates = $this->findTemplatesInFolder($bundle->getPath().'/Resources/themes/'.$theme);
        $name = $bundle->getName();

        foreach ($templates as $i => $template) {
            $templates[$i] = $template->set('bundle', $name);
        }

        return $templates;
    }
700937
private function copyTemplateConfig()
    {
        $dirPath = $this->bundle->getPath();
        $pagepartFile = $dirPath.'/Resources/config/pageparts/'.$this->template.'.yml';
        $namespace = $this->generateFormPageParts ? $this->bundle->getNamespace() : 'Kunstmaan\FormBundle';
        $this->filesystem->copy($this->skeletonDir.'/Resources/config/pageparts/formpage.yml', $pagepartFile, false);
        GeneratorUtils::replace('~~~ENTITY~~~', $this->entity, $pagepartFile);
        GeneratorUtils::replace('~~~FORM_BUNDLE~~~', $namespace, $pagepartFile);

        $pagetemplateFile = $dirPath.'/Resources/config/pagetemplates/'.$this->template.'.yml';
        $this->filesystem->copy($this->skeletonDir.'/Resources/config/pagetemplates/formpage.yml', $pagetemplateFile, false);
        GeneratorUtils::replace('~~~BUNDLE~~~', $this->bundle->getName(), $pagetemplateFile);
        GeneratorUtils::replace('~~~ENTITY~~~', $this->entity, $pagetemplateFile);
    }
354646
private function generateForm(BundleInterface $bundle, $document, $metadata)
    {
        try {
            $this->getFormGenerator()->generate($bundle, $document, $metadata);
        } catch (\RuntimeException $e) {
            // form already exists
        }
    }
639130
private function parseBundles(array $bundles, array &$configs): void
    {
        foreach ($bundles as $options) {
            // Only one value given, must be class name
            if (!\is_array($options)) {
                $options = ['bundle' => $options];
            }

            if (!isset($options['bundle'])) {
                throw new \RuntimeException(
                    sprintf('Missing class name for bundle config (%s)', json_encode($options))
                );
            }

            if (!empty($options['optional']) && !class_exists($options['bundle'])) {
                continue;
            }

            $config = new BundleConfig($options['bundle']);

            if (isset($options['replace'])) {
                $config->setReplace($options['replace']);
            }

            if (isset($options['development'])) {
                if (true === $options['development']) {
                    $config->setLoadInProduction(false);
                } elseif (false === $options['development']) {
                    $config->setLoadInDevelopment(false);
                }
            }

            if (isset($options['load-after'])) {
                $config->setLoadAfter($options['load-after']);
            }

            $configs[] = $config;
        }
    }
1157262
private function registerModule(Bundle $bundle)
    {
        $params = $this->getModule($this->rootDir.$bundle->getPath().DIRECTORY_SEPARATOR.'campaignchain.yml');

        // General installation routine.
        if (!is_array($params['modules']) || !count($params['modules'])) {
            return;
        }

        foreach ($params['modules'] as $identifier => $moduleParams) {
            $module = null;

            if ($bundle->getStatus()) {
                $status = $bundle->getStatus();
            } else {
                $status = $this->bundleConfigService->isRegisteredBundle($bundle);
            }

            /*
             * TODO: Detect whether a module has previously been registered
             * for this bundle, but the module is not anymore defined in
             * its campaignchain.yml.
             */
            if ($status == self::STATUS_REGISTERED_OLDER) {
                /** @var Module $module */
                $module = $this->em
                    ->getRepository('CampaignChainCoreBundle:Module')
                    ->findOneBy(
                        [
                            'bundle' => $bundle,
                            'identifier' => strtolower($identifier),
                        ]
                    );
            }

            switch ($bundle->getType()) {
                case 'campaignchain-channel':
                    $moduleEntity = 'ChannelModule';
                    break;
                case 'campaignchain-location':
                    $moduleEntity = 'LocationModule';
                    break;
                case 'campaignchain-campaign':
                    $moduleEntity = 'CampaignModule';
                    break;
                case 'campaignchain-milestone':
                    $moduleEntity = 'MilestoneModule';
                    break;
                case 'campaignchain-activity':
                    $moduleEntity = 'ActivityModule';
                    break;
                case 'campaignchain-operation':
                    $moduleEntity = 'OperationModule';
                    break;
                case 'campaignchain-report':
                case 'campaignchain-report-analytics':
                case 'campaignchain-report-budget':
                case 'campaignchain-report-sales':
                    $moduleEntity = 'ReportModule';
                    break;
                case 'campaignchain-security':
                    $moduleEntity = 'SecurityModule';
                    break;
            }

            if (!$module) {
                $entityClass = 'CampaignChain\\CoreBundle\\Entity\\'.$moduleEntity;
                /** @var Module $module */
                $module = new $entityClass();
                $module->setIdentifier(strtolower($identifier));
                $module->setBundle($bundle);
            }

            $module->setDisplayName($moduleParams['display_name']);

            /*
             * Tracking alias which allows the CTA tracking to match the
             * Location Identifier provided by the tracking script to a module.
             */
            if (isset($moduleParams['tracking_alias']) && strlen($moduleParams['tracking_alias'])) {
                $module->setTrackingAlias($moduleParams['tracking_alias']);
            }

            if (isset($moduleParams['description'])) {
                $module->setDescription($moduleParams['description']);
            }

            // Verify routes.
            if (in_array(
                $bundle->getType(),
                ['campaignchain-activity', 'campaignchain-channel', 'campaignchain-campaign', 'campaignchain-milestone']
            )) {
                // Throw error if no routes defined.
                if (
                    !isset($moduleParams['routes'])
                    || !is_array($moduleParams['routes'])
                    || !count($moduleParams['routes'])
                ) {
                    throw new \Exception(
                        'The module "'.$identifier
                        .'" in bundle "'.$bundle->getName().'"'
                        .' does not provide any of the required routes.'
                    );
                } else {
                    // Throw error if one or more routes are missing.
                    $hasMissingRoutes = false;
                    $missingRoutes = '';

                    foreach ($this->requiredRoutes[$bundle->getType()] as $requiredRoute) {
                        if (!array_key_exists($requiredRoute, $moduleParams['routes'])) {
                            $hasMissingRoutes = true;
                            $missingRoutes .= $requiredRoute.', ';
                        }
                    }

                    if ($hasMissingRoutes) {
                        throw new \Exception(
                            'The module "'.$identifier
                            .'" in bundle "'.$bundle->getName().'"'
                            .' must define the following route(s): '
                            .rtrim($missingRoutes, ', ').'.'
                        );
                    } else {
                        $module->setRoutes($moduleParams['routes']);
                    }
                }
            } elseif (isset($moduleParams['routes']) && is_array($moduleParams['routes']) && count(
                    $moduleParams['routes']
                )
            ) {
                $module->setRoutes($moduleParams['routes']);
            }

            if (isset($moduleParams['services']) && is_array($moduleParams['services']) && count(
                    $moduleParams['services']
                )
            ) {
                $module->setServices($moduleParams['services']);
            }
            if (isset($moduleParams['hooks']) && is_array($moduleParams['hooks']) && count($moduleParams['hooks'])) {
                // TODO: Check that there's only 1 trigger hook included.
                $module->setHooks($moduleParams['hooks']);
            }
            if (isset($moduleParams['system']) && is_array($moduleParams['system']) && count($moduleParams['system'])) {
                $this->systemParams[] = $moduleParams['system'];
            }
            // Are metrics for the reports defined?
            if (isset($moduleParams['metrics']) && is_array($moduleParams['metrics']) && count(
                    $moduleParams['metrics']
                )
            ) {
                foreach ($moduleParams['metrics'] as $metricType => $metricNames) {
                    switch ($metricType) {
                        case 'activity':
                            $metricClass = 'ReportAnalyticsActivityMetric';
                            break;
                        case 'location':
                            $metricClass = 'ReportAnalyticsLocationMetric';
                            break;
                        default:
                            throw new \Exception(
                                "Unknown metric type '".$metricType."'."
                                ."Pick 'activity' or 'location' instead."
                            );
                            break;
                    }
                    foreach ($metricNames as $metricName) {
                        $metric = $this->em->getRepository('CampaignChainCoreBundle:'.$metricClass)
                            ->findOneBy(
                                [
                                    'name' => $metricName,
                                    'bundle' => $bundle->getName(),
                                ]
                            );

                        // Does the metric already exist?
                        if ($metric) {
                            /*
                             * Throw error if bundle is new and metric
                             * has already been registered.
                             */
                            if ($status == self::STATUS_REGISTERED_NO) {
                                throw new \Exception(
                                    "Metric '".$metricName."' of type '".$metricType."'"
                                    .' already exists for bundle '.$bundle->getName().'. '
                                    .'Please define another name '
                                    .'in campaignchain.yml of '.$bundle->getName().'.'
                                );
                            }
                            // Skip if same or older version of bundle.
                            continue;
                        } else {
                            // Create new metric.
                            $metricNamespacedClass = 'CampaignChain\\CoreBundle\\Entity\\'.$metricClass;
                            $metric = new $metricNamespacedClass();
                            $metric->setName($metricName);
                            $metric->setBundle($bundle->getName());
                            $this->em->persist($metric);
                        }
                    }
                }
            }

            // Process the params specific to a module type.

            // Params that must be defined for Operation modules
            if ($bundle->getType() == 'campaignchain-operation' && !isset($moduleParams['params']['owns_location'])) {
                throw new \Exception(
                    "You must set the 'owns_location' parameter in campaignchain.yml to 'true' or 'false' for module '".$identifier."' in bundle '".$bundle->getName(
                    )."'."
                );
            }

            if (isset($moduleParams['params'])) {
                $module->setParams($moduleParams['params']);
            }

            // Add new module to new bundle.
            $reflect = new \ReflectionClass($module);
            $addModuleMethod = 'add'.$reflect->getShortName();
            $bundle->$addModuleMethod($module);

            // If a campaign module, remember the conversion to other campaign types.
            if (
                $bundle->getType() == 'campaignchain-campaign' &&
                isset($moduleParams['conversions']) &&
                is_array($moduleParams['conversions']) &&
                count($moduleParams['conversions'])
            ) {
                $this->campaignConversions[$bundle->getName()][$module->getIdentifier()] = $moduleParams['conversions'];
            }

            // If an activity or Location module, remember the related channels.
            if (
                isset($moduleParams['channels']) && is_array($moduleParams['channels']) && count($moduleParams['channels'])
            ) {
                $this->channelRelationships[$moduleEntity][$bundle->getName()][$module->getIdentifier()] = $moduleParams['channels'];
            }
        }
    }
1041569
public function install(PluginBundleInterface $plugin)
    {
        $this->checkInstallationStatus($plugin, false);
        $this->validatePlugin($plugin);
        $this->log('Saving plugin configuration...');
        $this->recorder->register($plugin, $this->validator->getPluginConfiguration());
        $this->baseInstaller->install($plugin);
    }
545611
private function patchRouting(AbstractResourceBundle $bundle)
    {
        $routingPath = $bundle->getPath() . '/Resources/config/routing/';
        $prefix = $this->getBundlePrefix();
        $namePrefix = strtolower($this->getBundlePrefix($bundle) . '_' . $this->model);
        $bundleName = $bundle->getName();
        $entityClass = $this->getContainer()->get('doctrine')->getAliasNamespace($this->bundle->getName()) . '\\' . $this->model;

        $identifier = $this->getContainer()->get('doctrine')
            ->getManager()
            ->getClassMetadata($entityClass)
            ->getIdentifier();

        $this->renderFile('controller/routing/routing.yml.twig',
            $routingPath . strtolower($this->model) . '.yml',
            array(
                'route_name_prefix' => $namePrefix,
                'bundle' => $prefix,
                'entity' => $this->model,
                'identifier' => $identifier[0],
                'resource' => $bundle->getName(),
                'actions' => $this->configuration['actions']
            )
        );

        $path = $routingPath . 'main.yml';
        if (!file_exists($path)) {
            $path = $this->getContainer()->get('kernel')->getRootDir() . '/config/routing.yml';
        }

        $prefixName = strtolower($this->model);
        $nodeDeclaration = <<<EOF
$namePrefix:
    resource: @$bundleName/Resources/config/routing/$prefixName.yml
    prefix: /$prefixName
EOF;

        if (!$this->refExist($path, $namePrefix)) {
            $this->dumpFile($path, "\n" . $nodeDeclaration, false, false);
        }

        return null;
    }
1296030
private function generatePageTemplateConfiguration()
    {
        $this->copyTemplates();
        $this->installDefaultPagePartConfiguration($this->bundle);
        $this->copyTemplateConfig();
        $this->assistant->writeLine('Generating template configuration : <info>OK</info>');
    }
679475
protected function installEntryFiles(PackageInterface $package)
    {
        foreach ($this->getEntryFileLocations($package) as $src => $dest) {
            $copied = $this->filesystem->copyFile($src, $dest);

            $this->io->notice(
                sprintf(
                    '    <fg=default>Copying <fg=magenta>%1$s</> to <fg=magenta>%2$s</> -</> %3$s',
                    $src,
                    $dest,
                    $copied ? '<fg=green>OK</>' : '<fg=red>FAILED</>'
                )
            );

            if (! $copied) {
                throw new RuntimeException(sprintf('Cannot copy %s to %s', $src, $dest));
            }
        }
    }
1118173
private function addBundle($bundle)
    {
        if (!in_array($bundle, $this->finalBundles)) {
            if ($bundle instanceof GravitonBundleInterface) {
                $this->bundleStack = array_merge(
                    $this->bundleStack,
                    $bundle->getBundles()
                );
            }

            $this->finalBundles[] = $bundle;
        }
    }
1167566
public void startBundle(Bundle bundle)
    {
        if (bundle != null)
            if ((bundle.getState() != Bundle.ACTIVE) && (bundle.getState() != Bundle.STARTING))
        {
            try {
                bundle.start();
            } catch (BundleException e) {
                e.printStackTrace();
            }
        }
    }
375735
public function setBundle(\CampaignChain\CoreBundle\Entity\Bundle $bundle = null)
    {
        $this->bundle = $bundle;

        return $this;
    }