Generate the pagepart entity.
175448
private function generatePagePartEntity()
    {
        $params = array(
            'bundle' => $this->bundle->getName(),
            'namespace' => $this->bundle->getNamespace(),
            'pagepart' => $this->entity,
            'pagepartname' => str_replace('PagePart', '', $this->entity),
            'adminType' => '\\' . $this->bundle->getNamespace(
                ) . '\\Form\\PageParts\\' . $this->entity . 'AdminType',
            'underscoreName' => strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $this->entity)),
            'prefix' => $this->prefix,
            'isV4' => $this->isSymfony4(),
        );

        $this->renderSingleFile(
            $this->skeletonDir . '/Entity/PageParts/' . $this->entity . '/',
            $this->bundle->getPath() . '/Entity/PageParts/',
            $this->entity . '.php',
            $params,
            true
        );

        $this->assistant->writeLine('Generating ' . $this->entity . ' Entity:       <info>OK</info>');
    }
147006
public function getPagePart(EntityManager $em)
    {
        return $em->getRepository($this->getPagePartEntityname())->find($this->getPagePartId());
    }
162594
private static StringBuffer generateBody(MetaEntity entity, Context context) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = null;
		try {
			pw = new PrintWriter( sw );

			if ( context.addGeneratedAnnotation() ) {
				pw.println( writeGeneratedAnnotation( entity, context ) );
			}
			if ( context.isAddSuppressWarningsAnnotation() ) {
				pw.println( writeSuppressWarnings() );
			}

			pw.println( writeStaticMetaModelAnnotation( entity ) );

			printClassDeclaration( entity, pw, context );

			pw.println();

			List<MetaAttribute> members = entity.getMembers();
			for ( MetaAttribute metaMember : members ) {
				pw.println( "	" + metaMember.getDeclarationString() );
			}

			pw.println();
			pw.println( "}" );
			return sw.getBuffer();
		}
		finally {
			if ( pw != null ) {
				pw.close();
			}
		}
	}
179571
private function generateMethods(): EntityGenerator
    {
        $this->entityClass
            ->addMethod('getId')
            ->setVisibility('public')
            ->addComment('Returns ' . strtolower($this->entityData['class']) . ' ID' . PHP_EOL)
            ->addComment('@return int')
            ->addBody('return $this->id;')
            ->setReturnType('int');

        foreach ($this->entityData['properties'] as $name => $type) {
            $this
                ->generateGetter($name, $type)
                ->generateSetter($name, $type);
        }

        return $this;
    }
1219703
private function generateSectionConfig()
    {
        if (count($this->sections) > 0) {
            $dir = $this->isSymfony4() ? $this->container->getParameter('kernel.project_dir') . '/config/kunstmaancms/pageparts/' : $this->bundle->getPath() . '/Resources/config/pageparts/';
            foreach ($this->sections as $section) {
                $data = $originalData = Yaml::parse(file_get_contents($dir . $section));
                if (array_key_exists('kunstmaan_page_part', $data)) {
                    $data['types'] = $originalData['kunstmaan_page_part']['pageparts'][substr($section, 0, -4)]['types'];
                }

                if (!array_key_exists('types', $data)) {
                    $data['types'] = array();
                }
                $class = $this->bundle->getNamespace() . '\\Entity\\PageParts\\' . $this->entity;
                $found = false;
                foreach ($data['types'] as $type) {
                    if ($type['class'] == $class) {
                        $found = true;
                    }
                }

                if (!$found) {
                    $data['types'][] = array(
                        'name' => str_replace('PagePart', '', $this->entity),
                        'class' => $class,
                    );
                }

                if (array_key_exists('kunstmaan_page_part', $originalData)) {
                    $originalData['kunstmaan_page_part']['pageparts'][substr($section, 0, -4)]['types'] = $data['types'];
                    $data = $originalData;
                }

                //Sf4 structure of the config file is nested deeper, increase the level when values are inlined
                $ymlData = Yaml::dump($data, $this->isSymfony4() ? 5 : 2);
                file_put_contents($dir . $section, $ymlData);
            }

            $this->assistant->writeLine('Updating ' . $this->entity . ' section config: <info>OK</info>');
        }
    }
693830
def _build_page(self, filepath):
        
        filename = filepath.split("/")[-1]
        # If filename starts with _ (underscore) or . (dot) do not build
        if not filename.startswith(("_", ".")) and (filename.endswith(PAGE_FORMAT)):
            meta = self._get_page_meta(filepath)
            content = self._get_page_content(filepath)

            # The default context for the page
            _default_page = {
                "build_dir": self.build_dir,
                "filepath": meta["filepath"],
                "context": {"page": meta},
                "content": content,
                "markup": meta.get("markup"),
                "template": meta.get("template"),
                "layout": meta.get("layout") or self.default_layout
            }

            # GENERATOR
            # Allows to generate
            _generator = meta.get("_generator")
            if _generator:
                data = self._data.get(_generator.get("data_source"))

                # We want these back in meta in they exists in the data
                special_meta = ["title", "slug", "description"]

                # SINGLE
                if _generator.get("type") == "single":
                    for d in data:
                        dmeta = copy.deepcopy(meta)
                        page = copy.deepcopy(_default_page)
                        for _ in special_meta:
                            if _ in d:
                                dmeta[_] = d.get(_)

                        # If generator has the slug, it will substitute if
                        # Slug in the generator must have token from the data
                        # to generate the slug
                        if "slug" in _generator:
                            dmeta["slug"] = _generator.get("slug").format(**d)

                        # Slug is required
                        if "slug" not in dmeta:
                            print("WARNING: Skipping page because it's missing `slug`")
                            continue
                        slug = dmeta.get("slug")
                        dmeta["url"] = slug
                        dmeta["context"] = d

                        page.update({
                            "filepath": slug,
                            "context": {"page": dmeta}
                        })
                        self.create_page(**page)

                if _generator.get("type") == "pagination":

                    per_page = int(_generator.get("per_page", self.site_config.get("pagination.per_page", 10)))
                    left_edge = int(_generator.get("left_edge", self.site_config.get("pagination.left_edge", 2)))
                    left_current = int(_generator.get("left_edge", self.site_config.get("pagination.left_current", 3)))
                    right_current = int(_generator.get("right_current", self.site_config.get("pagination.right_current", 4)))
                    right_edge = int(_generator.get("right_edge", self.site_config.get("pagination.right_edge", 2)))
                    padding = _generator.get("padding")
                    slug = _generator.get("slug")
                    limit = _generator.get("limit")

                    if "limit" in _generator:
                        data = data[:int(limit)]
                    data_chunks = utils.chunk_list(data, per_page)
                    len_data = len(data)

                    for i, d in enumerate(data_chunks):
                        dmeta = copy.deepcopy(meta)
                        page = copy.deepcopy(_default_page)

                        page_num = i + 1
                        _paginator = Paginator([],
                                               total=len_data,
                                               page=page_num,
                                               per_page=per_page,
                                               padding=padding,
                                               left_edge=left_edge,
                                               right_edge=right_edge,
                                               left_current=left_current,
                                               right_current=right_current)
                        _paginator.slug = slug
                        _paginator.index_slug = _generator.get("index_slug")

                        _slug = slug.format(**{"page_num": page_num})
                        dmeta["url"] = _slug
                        dmeta["context"] = d
                        dmeta["paginator"] = _paginator
                        page.update({
                            "filepath": _slug,
                            "context": {"page": dmeta}
                        })
                        self.create_page(**page)

                        # First page need to generate the index
                        if i == 0 and _generator.get("index_slug"):
                            page["filepath"] = _generator.get("index_slug")
                            self.create_page(**page)

            # NORMAL PAGE
            else:
                self.create_page(**_default_page)
228563
public function savePage()
    {
        // Get dependencies
        $pageMapper = ($this->container->dataMapper)('PageMapper');
        $pageElementMapper = ($this->container->dataMapper)('PageElementMapper');
        $pageSettingMapper = ($this->container->dataMapper)('PageSettingMapper');
        $markdown = $this->container->markdownParser;
        $toolbox = $this->container->toolbox;
        $json = $this->container->json;

        // Get page object
        $pageId = empty($this->request->getParsedBodyParam('id')) ? null : $this->request->getParsedBodyParam('id');
        $newSlug = $toolbox->cleanUrl($this->request->getParsedBodyParam('slug'));

        if (null !== $pageId) {
            $page = $pageMapper->findById($pageId);

            // Ensure we are not futzing with the home page slug
            if ($page->slug === 'home' && $newSlug !== 'home') {
                throw new Exception('PitonCMS: Cannot change home page slug');
            }
        } else {
            $page = $pageMapper->make();
        }

        $page->collection_id = $this->request->getParsedBodyParam('collection_id');
        $page->definition = $this->request->getParsedBodyParam('definition');
        $page->template = $this->request->getParsedBodyParam('template');
        $page->title = $this->request->getParsedBodyParam('title');
        $page->sub_title = $this->request->getParsedBodyParam('sub_title');
        $page->slug = $newSlug;
        $page->meta_description = $this->request->getParsedBodyParam('meta_description');
        $page->image_path = $this->request->getParsedBodyParam('image_path');

        // Process published date
        $publishedDate = $this->request->getParsedBodyParam('published_date');
        if (!empty($publishedDate)) {
            // The leading ! sets the time to 00:00:00
            $phpDateFormat = [
                'mm/dd/yyyy' => '!m/d/Y',
                'dd-mm-yyyy' => '!d-m-Y',
                'dd.mm.yyyy' => '!d.m.Y'
            ];

            $date = \DateTime::createFromFormat($phpDateFormat[$this->siteSettings['dateFormat']], $publishedDate);
            $page->published_date = $date->format('Y-m-d');
        }

        // Save Page and get ID
        $page = $pageMapper->save($page);

        // Save any custom page settings
        if ($this->request->getParsedBodyParam('setting_id')) {
            foreach ($this->request->getParsedBodyParam('setting_id') as $settingKey => $settingValue) {
                $setting = $pageSettingMapper->make();
                $setting->id = $this->request->getParsedBodyParam('setting_id')[$settingKey];

                // Check for a page setting delete
                if (isset($this->request->getParsedBodyParam('setting_delete')[$settingKey])) {
                    $pageSettingMapper->delete($setting);
                    continue;
                }

                $setting->page_id = $page->id;
                $setting->setting_key = $this->request->getParsedBodyParam('setting_key')[$settingKey];
                $setting->setting_value = $this->request->getParsedBodyParam('setting_value')[$settingKey];

                $pageSettingMapper->save($setting);
            }
        }

        // Save page elements by block
        foreach ($this->request->getParsedBodyParam('block_key') as $key => $value) {
            // Save element
            $pageElement = $pageElementMapper->make();
            $pageElement->id = $this->request->getParsedBodyParam('element_id')[$key];
            $pageElement->page_id = $page->id;
            $pageElement->block_key = $this->request->getParsedBodyParam('block_key')[$key];
            $pageElement->definition = $this->request->getParsedBodyParam('element_type')[$key];
            $pageElement->element_sort = $this->request->getParsedBodyParam('element_sort')[$key];
            $pageElement->title = $this->request->getParsedBodyParam('element_title')[$key];
            $pageElement->content_raw = $this->request->getParsedBodyParam('content_raw')[$key];
            $pageElement->content = $markdown->text($this->request->getParsedBodyParam('content_raw')[$key]);
            $pageElement->excerpt = $toolbox->truncateHtmlText($pageElement->content, 60);
            $pageElement->collection_id = $this->request->getParsedBodyParam('element_collection_id')[$key];
            $pageElement->gallery_id = $this->request->getParsedBodyParam('element_gallery_id')[$key];
            $pageElement->embedded = $this->request->getParsedBodyParam('embedded')[$key];

            // If the image path does not start with http then get base name
            $imagePath = $this->request->getParsedBodyParam('element_image_path')[$key];
            if (stripos($imagePath, 'http') === 0) {
                $pageElement->image_path = $imagePath;
            } else {
                $pageElement->image_path = pathinfo($imagePath, PATHINFO_BASENAME);
            }

            // Get the elementTemplateFile from element JSON file
            $jsonPath = ROOT_DIR . "structure/definitions/elements/{$pageElement->definition}";

            if (null === $elementDefinition = $json->getJson($jsonPath, 'element')) {
                throw new Exception('Element JSON Definition Error: ' . print_r($json->getErrorMessages(), true));
            }

            $pageElement->template = $elementDefinition->elementTemplateFile;

            $pageElement = $pageElementMapper->save($pageElement);
        }

        // Determine redirect path based on whether this is a collection
        if (!empty($this->request->getParsedBodyParam('collection_id'))) {
            $redirectPath = 'adminCollections';
        } else {
            $redirectPath = 'adminPages';
        }

        // Redirect back to show page
        return $this->redirect($redirectPath);
    }
240906
protected function generateEntitiesListFromQuery(): void
    {
        $query = $this->getAttribute('tableModel')->query();
        $this->applyQueryClosure($query);
        $this->checkColumnsValidity();
        $this->applySearchClauses($query);
        $this->applySortClauses($query);
        $this->paginateList($query);
        $this->applyClosuresOnPaginatedList();
    }
999337
def _entity_paginator(namespace, workspace, etype, page_size=500,
                            filter_terms=None, sort_direction="asc"):
    

    page = 1
    all_entities = []
    # Make initial request
    r = fapi.get_entities_query(namespace, workspace, etype, page=page,
                           page_size=page_size, sort_direction=sort_direction,
                           filter_terms=filter_terms)
    fapi._check_response_code(r, 200)

    response_body = r.json()
    # Get the total number of pages
    total_pages = response_body['resultMetadata']['filteredPageCount']

    # append the first set of results
    entities = response_body['results']
    all_entities.extend(entities)
    # Now iterate over remaining pages to retrieve all the results
    page = 2
    while page <= total_pages:
        r = fapi.get_entities_query(namespace, workspace, etype, page=page,
                               page_size=page_size, sort_direction=sort_direction,
                               filter_terms=filter_terms)
        fapi._check_response_code(r, 200)
        entities = r.json()['results']
        all_entities.extend(entities)
        page += 1

    return all_entities
460826
public function savePage(
        SiteEntity $siteEntity,
        $pageName,
        $pageRevision,
        $pageType,
        $saveData,
        $modifiedByUserId,
        $modifiedReason = Tracking::UNKNOWN_REASON,
        $author = Tracking::UNKNOWN_AUTHOR
    ): array {
        if (empty($pageType)) {
            $pageType = PageTypes::NORMAL;
        }

        $modifiedSiteWideContainers = [];

        if (!empty($saveData['containers'])) {
            foreach ($saveData['containers'] as $containerName => $containerData) {
                /** @var \Rcm\Entity\Container $container */
                $container = $siteEntity->getContainer($containerName);

                if (empty($container)) {
                    /** @var \Rcm\Repository\Container $containerRepo */
                    $containerRepo = $this->_em->getRepository(
                        \Rcm\Entity\Container::class
                    );
                    $container = $containerRepo->createContainer(
                        $siteEntity,
                        $containerName,
                        $modifiedByUserId,
                        $modifiedReason,
                        $author
                    );
                }

                $resultRevisionId = $this->saveContainer(
                    $container,
                    $containerData,
                    $modifiedByUserId,
                    $modifiedReason,
                    $author
                );

                /**
                 * If it deterimins there was no change, it saves nothing a returns an empty $resultRevisionId.
                 */
                $savedANewVersion = !empty($resultRevisionId);

                if ($savedANewVersion) {
                    $modifiedSiteWideContainers[$resultRevisionId] = $container;
                }
            }
        }

        $page = $this->getPageByName($siteEntity, $pageName, $pageType);

        return [
            'newPageRevisionId' => $this->saveContainer(
                $page,
                $saveData['pageContainer'],
                $modifiedByUserId,
                $modifiedReason,
                $author,
                $pageRevision
            ),
            'modifiedSiteWideContainers' => $modifiedSiteWideContainers
        ];
    }
176512
private function getPageEntity(Request $request, $preview, EntityManagerInterface $em, NodeTranslation $nodeTranslation)
    {
        /* @var HasNodeInterface $entity */
        $entity = null;
        if ($preview) {
            $version = $request->get('version');
            if (!empty($version) && is_numeric($version)) {
                $nodeVersion = $em->getRepository('KunstmaanNodeBundle:NodeVersion')->find($version);
                if (!is_null($nodeVersion)) {
                    $entity = $nodeVersion->getRef($em);
                }
            }
        }
        if (is_null($entity)) {
            $entity = $nodeTranslation->getPublicNodeVersion()->getRef($em);

            return $entity;
        }

        return $entity;
    }
957671
def generate_pages_by_file():
    """"""
    from veripress import app
    from veripress.model import storage
    from veripress.model.parsers import get_standard_format_name
    from veripress.helpers import traverse_directory

    deploy_dir = get_deploy_dir()

    def copy_file(src, dst):
        makedirs(os.path.dirname(dst), mode=0o755, exist_ok=True)
        shutil.copyfile(src, dst)

    with app.app_context(), app.test_client() as client:
        root_path = os.path.join(app.instance_path, 'pages')
        for path in traverse_directory(root_path):
            # e.g. 'a/b/c/index.md'
            rel_path = os.path.relpath(path, root_path)
            # e.g. ('a/b/c/index', '.md')
            filename, ext = os.path.splitext(rel_path)
            if get_standard_format_name(ext[1:]) is not None:
                # is source of custom page
                rel_url = filename.replace(os.path.sep, '/') + '.html'
                page = storage.get_page(rel_url, include_draft=False)
                if page is not None:
                    # it's not a draft, so generate the html page
                    makedirs(os.path.join(deploy_dir,
                                          os.path.dirname(rel_path)),
                             mode=0o755, exist_ok=True)
                    with open(os.path.join(deploy_dir, filename + '.html'),
                              'wb') as f:
                        f.write(client.get('/' + rel_url).data)
                if app.config['PAGE_SOURCE_ACCESSIBLE']:
                    copy_file(path, os.path.join(deploy_dir, rel_path))
            else:
                # is other direct files
                copy_file(path, os.path.join(deploy_dir, rel_path))
900447
public void savePreviousImplementedVersion(Page page, Integer version) {
        String value = version != null ? String.valueOf(version) : null;
        ContentEntityObject entityObject = getContentEntityManager().getById(page.getId());
        getContentPropertyManager().setStringProperty(entityObject, PREVIOUS_IMPLEMENTED_VERSION, value);
    }
1320559
public static void generate(Elements elementUtils, Filer filer, SQLiteDatabaseSchema schema,
			Set<GeneratedTypeElement> generatedEntities) throws Exception {
		BindTableGenerator visitor = new BindTableGenerator(elementUtils, filer, schema);

		List<SQLiteEntity> orderedEntities = BindDataSourceBuilder.orderEntitiesList(schema);

		for (SQLiteEntity item : orderedEntities) {
			visitor.visit(schema, item);
		}

		// generate table for generated entity
		for (GeneratedTypeElement genItem : generatedEntities) {
			visitor.visit(schema, genItem);
		}
	}
1355210
public function generateSite()
    {

        $template = new TemplateImpl($this->backendContainer);
        $pageStrategy = $this->backendContainer->getCurrentPageStrategyInstance();


        $cacheControl = $this->backendContainer->getCacheControlInstance();
        if ($this->config->isDebugMode()) {
            $cacheControl->disableCache();
            $template->setTwigDebug(true);
        }


        $currentPage = $pageStrategy->getCurrentPage();
        $template->setTemplateFromConfig($currentPage->getTemplate(), "_main");

        $ajaxServer = $this->backendContainer->getAJAXServerInstance();
        $id = null;
        if (($id = $this->GETValueOfIndexIfSetElseDefault('ajax')) !== null) {
            $template->onlyInitialize();
            $ajaxServer->registerHandlersFromConfig();
        }

        //Decide output mode
        if ($id !== null) {
            echo json_encode($ajaxServer->handleFromFunctionString($id, $this->GETValueOfIndexIfSetElseDefault('token')), $this->config->isDebugMode()?JSON_PRETTY_PRINT:0);

        } else if (!$cacheControl->setUpCache()) {
            echo $template->render();
        }

    }
824810
def _render_pages(self):
        """"""
        self.style_log = StyleLog(self.stylesheet)
        self.floats = set()
        self.placed_footnotes = set()
        self._start_time = time.time()

        part_page_counts = {}
        part_page_count = PartPageCount()
        last_number_format = None
        for part_template in self.part_templates:
            part = part_template.document_part(self, part_page_count.count + 1)
            if part is None:
                continue
            if part_template.page_number_format != last_number_format:
                part_page_count = PartPageCount()
            part_page_count += part.render(part_page_count.count + 1)
            part_page_counts[part_template.name] = part_page_count
            last_number_format = part_template.page_number_format
        sys.stdout.write('\n')     # for the progress indicator
        return part_page_counts
790860
private function generateFormType()
    {
        $this->generateEntityAdminType($this->bundle, $this->entity, 'PageParts', $this->fields);

        $this->assistant->writeLine('Generating form type : <info>OK</info>');
    }