Generates Generated/<class_name>Traits.php

@param PackageClass $package_class
@param array $traits
176571
private function generateTrait(PackageClass $package_class, array $traits)
    {
        $short_name = $package_class->getShortName();

        $this->writeIfVeryVerbose(
            '        - Generating trait of traits for <info>' . $package_class->getName() . '</info>'
        );

        $generated_namespace = $package_class->getGeneratedNamespaceName();

        $use_statements = array_filter(
            $traits,
            function (PackageClass $stmt) {
                return $stmt->isTrait();
            }
        );
        sort($use_statements);

        $data = $this->environment->render(
            'trait.php.twig',
            [
                'class_name' => $short_name,
                'namespace' => $generated_namespace,
                'use_statements' => $use_statements
            ]
        );

        $this->filesystem->dumpFile(
            $package_class->getGeneratedDirectory() . $short_name . 'Trait.php',
            $data
        );
    }
1199455
@SuppressWarnings("unchecked")
  public void gen(String fileName, String packageName) throws Exception {
    configuration = ConfigBuilder.build(new OverrideConfiguration());
    mapping = configuration.buildMapping();
    defaultCatalog = configuration.getProperties().getProperty(Environment.DEFAULT_CATALOG);
    defaultSchema = configuration.getProperties().getProperty(Environment.DEFAULT_SCHEMA);
    configuration.getProperties().put(Environment.DIALECT, dialect);
    // 1. first process class mapping
    Iterator<PersistentClass> iterpc = configuration.getClassMappings();
    while (iterpc.hasNext()) {
      PersistentClass pc = iterpc.next();
      Class<?> clazz = pc.getMappedClass();
      if (isNotBlank(packageName) && !clazz.getPackage().getName().startsWith(packageName)) continue;
      // add comment to table and column
      pc.getTable().setComment(messages.get(clazz, clazz.getSimpleName()));
      commentProperty(clazz, pc.getTable(), pc.getIdentifierProperty());
      commentProperties(clazz, pc.getTable(), pc.getPropertyIterator());
      PersistentClass mySuper = pc.getSuperclass();
      while(null!=mySuper){
        commentProperties(clazz, pc.getTable(), mySuper.getPropertyIterator());
        mySuper=mySuper.getSuperclass();
      }
      // generator sequence sql
      if (pc instanceof RootClass) {
        IdentifierGenerator ig = pc.getIdentifier().createIdentifierGenerator(
            configuration.getIdentifierGeneratorFactory(), dialect, defaultCatalog, defaultSchema,
            (RootClass) pc);
        if (ig instanceof PersistentIdentifierGenerator) {
          String[] lines = ((PersistentIdentifierGenerator) ig).sqlCreateStrings(dialect);
          sequences.addAll(Arrays.asList(lines));
        }
      }
      // generater table sql
      generateTableSql(pc.getTable());
    }

    // 2. process collection mapping
    Iterator<Collection> itercm = configuration.getCollectionMappings();
    while (itercm.hasNext()) {
      Collection col = itercm.next();
      if (isNotBlank(packageName) && !col.getRole().startsWith(packageName)) continue;
      // collection sequences
      if (col.isIdentified()) {
        IdentifierGenerator ig = ((IdentifierCollection) col).getIdentifier().createIdentifierGenerator(
            configuration.getIdentifierGeneratorFactory(), dialect, defaultCatalog, defaultSchema, null);

        if (ig instanceof PersistentIdentifierGenerator) {
          String[] lines = ((PersistentIdentifierGenerator) ig).sqlCreateStrings(dialect);
          sequences.addAll(Arrays.asList(lines));
        }
      }
      // collection table
      if (!col.isOneToMany()) {
        Table table = col.getCollectionTable();
        String owner = col.getTable().getComment();
        Class<?> ownerClass = col.getOwner().getMappedClass();
        // resolved nested compoent name in collection's role
        String colName = substringAfter(col.getRole(), col.getOwnerEntityName() + ".");
        if (colName.contains(".")) ownerClass = getPropertyType(col.getOwner(),
            substringBeforeLast(colName, "."));
        table.setComment(owner + "-" + messages.get(ownerClass, substringAfterLast(col.getRole(), ".")));

        Column keyColumn = table.getColumn((Column) col.getKey().getColumnIterator().next());
        if (null != keyColumn) keyColumn.setComment(owner + " ID");

        if (col instanceof IndexedCollection) {
          IndexedCollection idxCol = (IndexedCollection) col;
          Value idx = idxCol.getIndex();
          if (idx instanceof ToOne) commentToOne((ToOne) idx, (Column) idx.getColumnIterator().next());
        }
        if (col.getElement() instanceof ManyToOne) {
          Column valueColumn = (Column) col.getElement().getColumnIterator().next();
          commentToOne((ManyToOne) col.getElement(), valueColumn);
        } else if (col.getElement() instanceof Component) {
          Component cp = (Component) col.getElement();
          commentProperties(cp.getComponentClass(), table, cp.getPropertyIterator());
        }
        generateTableSql(col.getCollectionTable());
      }
    }
    Set<String> commentSet = CollectUtils.newHashSet(comments);
    comments.clear();
    comments.addAll(commentSet);
    // 3. export to files
    for (String key : files.keySet()) {
      List<List<String>> sqls = files.get(key);
      FileWriter writer = new FileWriter(fileName + "/" + key, false);
      writes(writer, sqls);
      writer.flush();
      writer.close();
    }
  }
883821
public void createPackageContents() {
		if (isCreated) return;
		isCreated = true;

		// Create classes and their features
		afpEClass = createEClass(AFP);
		createEReference(afpEClass, AFP__STRUCTURED_FIELDS);

		sfEClass = createEClass(SF);
		createEAttribute(sfEClass, SF__NUMBER);
		createEAttribute(sfEClass, SF__OFFSET);
		createEAttribute(sfEClass, SF__ID);
		createEAttribute(sfEClass, SF__LENGTH);
		createEReference(sfEClass, SF__CHILDREN);
		createEAttribute(sfEClass, SF__RAW_DATA);
		createEAttribute(sfEClass, SF__CHARSET);

		unknsfEClass = createEClass(UNKNSF);

		sfGrouperEClass = createEClass(SF_GROUPER);

		tripletEClass = createEClass(TRIPLET);
		createEAttribute(tripletEClass, TRIPLET__LABEL);
		createEAttribute(tripletEClass, TRIPLET__CHARSET);
		createEAttribute(tripletEClass, TRIPLET__FILE_OFFSET);
		createEAttribute(tripletEClass, TRIPLET__TRIPLET_LENGTH);
		createEAttribute(tripletEClass, TRIPLET__TRIPLET_ID);
		createEAttribute(tripletEClass, TRIPLET__TRIPLET_NUMBER);

		// Create data types
		modcaStringEDataType = createEDataType(MODCA_STRING);
		modcaString4EDataType = createEDataType(MODCA_STRING4);
		modcaString8EDataType = createEDataType(MODCA_STRING8);
		modcaString32EDataType = createEDataType(MODCA_STRING32);
		charsetEDataType = createEDataType(CHARSET);
	}
276041
protected function generateRequirePackages(array $packagePairs)
    {
        $requires = [];

        foreach ($packagePairs as $packagePair) {
            $requires[$packagePair->getName()] = $packagePair->getVersion();
        }

        return $requires;
    }
764928
protected function prepareTraits(array $traits)
    {
        \natcasesort($traits);

        // My kingdom for a generator.
        $ret = [];

        foreach ($traits as $name) {
            if ($this->showItem($name)) {
                $ret[$name] = [
                    'name'  => $name,
                    'style' => self::IS_CLASS,
                    'value' => $this->presentSignature($name),
                ];
            }
        }

        return $ret;
    }
396884
public static void generate(ConfigurationImpl configuration,
                                ClassUseMapper mapper, PackageDoc pkgdoc) {
        PackageUseWriter pkgusegen;
        DocPath filename = DocPaths.PACKAGE_USE;
        try {
            pkgusegen = new PackageUseWriter(configuration,
                                             mapper, filename, pkgdoc);
            pkgusegen.generatePackageUseFile();
            pkgusegen.close();
        } catch (IOException exc) {
            configuration.standardmessage.error(
                "doclet.exception_encountered",
                exc.toString(), filename);
            throw new DocletAbortException(exc);
        }
    }
1118448
private function generateClass(): ServiceDTOGenerator
    {
        $this->DTOFile = (new PhpFile())
            ->addComment('This file is auto-generated.');

        $namespace = $this->inputData['namespace'] . '\\' . $this->inputData['module'] . 'Module\\' . $this->inputData['type'];

        $this->DTOClass = $this->DTOFile
            ->addNamespace($namespace)
            ->addClass($this->inputData['class'] . $this->inputData['type'])
            ->addComment($this->inputData['class'] . ' service ' . strtolower($this->inputData['type']) . PHP_EOL)
            ->addComment('@package ' . $namespace);

        return $this;
    }
1256643
private void generateClassFiles(ClassTree classtree) {
        String[] packageNames = configuration.classDocCatalog.packageNames();
        for (int packageNameIndex = 0; packageNameIndex < packageNames.length;
                packageNameIndex++) {
            generateClassFiles(configuration.classDocCatalog.allClasses(
                packageNames[packageNameIndex]), classtree);
        }
    }
543021
public function actionGenerate() {
		$versionList = MiscHelper::getAllVersions();
		$versionList = array_combine($versionList, $versionList);
		$selected = Select::display('Select package', $versionList);
		$version = Select::getFirstValue($selected);
		ApiDocHelper::generate($version);
		Output::block('Success generated');
	}
562959
public static void addClassesInPackageByFile(String packageName, String packagePath, List<Class<?>> classes) throws ClassNotFoundException {
        File dir = new File(packagePath);
        if (!dir.exists() || !dir.isDirectory()) {
            return;
        }
        File[] files = dir.listFiles(file -> (file.isDirectory()) || (file.getName().endsWith(".class")));
        if (Checker.isNotNull(files)) {
            for (File file : files) {
                if (file.isDirectory()) {
                    addClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), classes);
                } else {
                    String className = file.getName().substring(0, file.getName().length() - 6);
                    classes.add(Class.forName(packageName + '.' + className));
                }
            }
        }
    }
303111
private function isRelevant(PackageClass $package_class)
    {
        $class_name = $package_class->getName();
        if (strstr($class_name, '\\Generated\\')
            || $package_class->isInterface()
            || $package_class->isException()
            || strpos($class_name, $this->type) === false
        ) {
            return false;
        }
        return true;
    }
797119
public function addClassDependency(string $class, string $package, bool $required = true, bool $devDependency = false)
    {
        if ($devDependency) {
            $this->devDependencies[] = [
                'class' => $class,
                'name' => $package,
                'required' => $required,
            ];
        } else {
            $this->dependencies[] = [
                'class' => $class,
                'name' => $package,
                'required' => $required,
            ];
        }
    }
548075
private Set<ClassInfo> findClassByPackage(final String packageName, final String packagePath,
                                              final Class<?> parent, final Class<? extends Annotation> annotation,
                                              final boolean recursive, Set<ClassInfo> classes) throws ClassNotFoundException {

        // Get the directory of this package to create a File
        File dir = new File(packagePath);
        // If not exist or is not a direct return to the directory
        if ((!dir.exists()) || (!dir.isDirectory())) {
            log.warn("The package [{}] not found.", packageName);
        }
        // If present, get all the files under the package include the directory
        File[] dirFiles = accept(dir, recursive);
        // Loop all files
        if (null != dirFiles && dirFiles.length > 0) {
            for (File file : dirFiles) {
                // If it is a directory, continue scanning
                if (file.isDirectory()) {
                    findClassByPackage(packageName + '.' + file.getName(), file.getAbsolutePath(), parent, annotation, recursive, classes);
                } else {
                    // If the java class file is removed later. Class only leave the class name
                    String   className = file.getName().substring(0, file.getName().length() - 6);
                    Class<?> clazz     = Class.forName(packageName + '.' + className);
                    if (null != parent && null != annotation) {
                        if (null != clazz.getSuperclass() && clazz.getSuperclass().equals(parent) &&
                                null != clazz.getAnnotation(annotation)) {
                            classes.add(new ClassInfo(clazz));
                        }
                        continue;
                    }
                    if (null != parent) {
                        if (null != clazz.getSuperclass() && clazz.getSuperclass().equals(parent)) {
                            classes.add(new ClassInfo(clazz));
                        } else {
                            if (null != clazz.getInterfaces() && clazz.getInterfaces().length > 0 && clazz.getInterfaces()[0].equals(parent)) {
                                classes.add(new ClassInfo(clazz));
                            }
                        }
                        continue;
                    }
                    if (null != annotation) {
                        if (null != clazz.getAnnotation(annotation)) {
                            classes.add(new ClassInfo(clazz));
                        }
                        continue;
                    }
                    classes.add(new ClassInfo(clazz));
                }
            }
        }
        return classes;
    }
1202088
protected function getMethods(PackageClass $package_class)
    {
        try {
            $class = new \ReflectionClass($package_class->getName());
        } catch (\ReflectionException $e) {
            return [];
        }
        $methods = $class->getMethods();

        foreach ($methods as $key => $method) {
            if ($method->name === '__construct') {
                // The interface should not contain the constructor
                unset($methods[$key]);
                continue;
            }
            $methods[$key] = new ReflectionMethod($method);
        }

        return $methods;
    }
148117
public static function collectTraitsFromClassNode(ClassLike $classLikeNode, array &$traitAdaptations)
    {
        $traits = [];

        if (!empty($classLikeNode->stmts)) {
            foreach ($classLikeNode->stmts as $classLevelNode) {
                if ($classLevelNode instanceof TraitUse) {
                    foreach ($classLevelNode->traits as $classTraitName) {
                        if ($classTraitName instanceof FullyQualified) {
                            $traitName          = $classTraitName->toString();
                            $trait              = trait_exists($traitName, false)
                                ? new parent($traitName)
                                : new static($traitName);
                            $traits[$traitName] = $trait;
                        }
                    }
                    $traitAdaptations = $classLevelNode->adaptations;
                }
            }
        }

        return $traits;
    }
611954
public static void infoOnGeneratedClasses(Class<? extends Annotation> annotation, String packageName, String className) {
		String msg = String.format("class '%s' in package '%s' is generated by '@%s' annotation processor", className, packageName, annotation.getSimpleName());
		
		printMessage(msg);
	}
1017205
public function addMapping($package_class_name, $class_name)
    {
        $this->mappings[$package_class_name] = $class_name;
        self::add($package_class_name, $class_name);
    }