Giter VIP home page Giter VIP logo

api-platform / schema-generator Goto Github PK

View Code? Open in Web Editor NEW
454.0 29.0 108.0 2.14 MB

PHP Model Scaffolding from Schema.org and other RDF vocabularies

Home Page: https://api-platform.com/docs/schema-generator/

License: MIT License

PHP 99.30% Shell 0.53% Twig 0.17%
php schema-org doctrine web-ontology-language microdata vocabulary schema generator semantic php-model symfony json-ld api-platform hacktoberfest

schema-generator's Introduction

schema-generator's People

Contributors

alanpoulain avatar andreybolonin avatar aureluster avatar baspeeters avatar dependabot-preview[bot] avatar dunglas avatar jlagneau avatar keyermann avatar marciosmiderle avatar marcstraube avatar maxhelias avatar meyerbaptiste avatar nightio avatar patrick-yi-82 avatar pawelsuwinski avatar pborreli avatar peter279k avatar pfrenssen avatar pierredup avatar queercodinggirl avatar restotelry avatar scurron avatar soyuka avatar sroze avatar tangoman75 avatar thearrowrichard avatar theofidry avatar toby-griffiths avatar vincentchalamon avatar wrlss avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

schema-generator's Issues

Enhancement: Add Unique Constraint Option

I think an option should exist to allow a unique constraint on an ORM property, for example:

@ORM\Column(type="string", unique=true)

I don't yet know the mechanism for implementing this but it would be useful where you want unique entries for some fields in a database (e.g. usernames).

Wrong namespace used for Inflector

When I install schema-generator through Composer and try to generate the data types I get the following fatal error:

$ ./vendor/bin/schema generate-types src/ app/config/schema.yml 
PHP Fatal error:  Uncaught Error: Class 'Doctrine\Common\Util\Inflector' not found in /home/pieter/v/screeningapi/vendor/api-platform/schema-generator/src/TypesGenerator.php:651
Stack trace:
#0 /home/pieter/v/screeningapi/vendor/api-platform/schema-generator/src/TypesGenerator.php(222): ApiPlatform\SchemaGenerator\TypesGenerator->generateField(Array, Array, Object(EasyRdf_Resource), 'Thing', 'name', Object(EasyRdf_Resource))
#1 /home/pieter/v/screeningapi/vendor/api-platform/schema-generator/src/Command/GenerateTypesCommand.php(138): ApiPlatform\SchemaGenerator\TypesGenerator->generate(Array)
#2 /home/pieter/v/screeningapi/vendor/symfony/console/Command/Command.php(276): ApiPlatform\SchemaGenerator\Command\GenerateTypesCommand->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#3 /home/pieter/v/screeningapi/vendor/symfony/console/Application.php(933): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\ in /home/pieter/v/screeningapi/vendor/api-platform/schema-generator/src/TypesGenerator.php on line 651

The standalone Inflector package has renamed this namespace before their 1.0.0 release, see doctrine/inflector@54b8333#diff-9e179a11e3e7c8687e189c2288f2b3bcR20

error with asserting enums and typing

using api-platform 2.2.7 and following schema

# api/config/schema.yaml
# The list of types and properties we want to use
fluentMutatorMethods: true
types:
    DayOfWeek:
        properties: []
    OpeningHoursSpecification:
        properties:
            opens: ~
            closes: ~
            dayOfWeek: ~
            validFrom: ~
            validThrough: ~

generates

<?php

declare(strict_types=1);

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiProperty;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Enum\DayOfWeek;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * A structured value providing information about the opening hours of a place or a certain service inside a place.\\n\\n The place is \_\_open\_\_ if the \[\[opens\]\] property is specified, and \_\_closed\_\_ otherwise.\\n\\nIf the value for the \[\[closes\]\] property is less than the value for the \[\[opens\]\] property then the hour range is assumed to span over the next day.
 *
 * @see http://schema.org/OpeningHoursSpecification Documentation on Schema.org
 *
 * @ORM\Entity
 * @ApiResource(iri="http://schema.org/OpeningHoursSpecification")
 */
class OpeningHoursSpecification
{

    /**
     * @var string[] the day of the week for which these opening hours are valid
     *
     * @ORM\Column(type="simple_array")
     * @ApiProperty(iri="http://schema.org/dayOfWeek")
     * @Assert\NotNull
     * @Assert\Choice(callback={"DayOfWeek", "toArray"}, multiple=true)
     */
    private $dayOfWeeks = [];

    public function getDayOfWeeks(): Collection
    {
        return $this->dayOfWeeks;
    }
}

error1

  "hydra:description": "Return value of App\\Entity\\OpeningHoursSpecification::getDayOfWeeks() must be an instance of Doctrine\\Common\\Collections\\Collection, array returned",

fixed by changing

    public function getDayOfWeeks(): array

error 2

  "hydra:description": "The Choice constraint expects a valid callback",

fixed by changing

     * @Assert\Choice(callback={"App\Enum\DayOfWeek", "toArray"}, multiple=true)

Adding custom annotations & @Table annotations

HI there,

I would like to be able to add multi-column uniqueness and custom annotations to fields in my entities for example…

@Table(name="video_settings", 
  uniqueConstraints={
    @UniqueConstraint(name="video_unique", 
      columns={"video_dimension", "video_bitrate"}
    )
  }
)

… and…

/**
 * Some custom comments here
 * 
 * @ApiProperty(iri="http://schema.org/email")
 */
private $property

I thought I might be able to do this with a custom annotation generator, however because of the strict configuration, any additional fields are not allowed.

Is there another way to add additional fields to the config without these errors?

I guess it might be possible to add a hook into the existing commands to use a custom Configure class. Has any work been done on this at all, before I try to find the time to submit a PR?

Invalid schema generation

Hi,

I follow with tutorial at https://github.com/api-platform/docs/blob/master/tutorial/api.md#generating-the-data-model and when I run:

$ vendor/bin/schema generate-types src/ app/config/schema.yml

I get the following output:

[warning] Type "Book" cannot be found. Using "Thing" type to generate entity.
[warning] Type "Person" cannot be found. Using "Thing" type to generate entity.
[warning] Type "Organization" cannot be found. Using "Thing" type to generate entity.
[error] The property "name" (type "Thing") has an unknown type. Add its type to the config file.
[error] The property "description" (type "Thing") has an unknown type. Add its type to the config file.
[error] The property "genre" (type "Thing") has an unknown type. Add its type to the config file.
[error] The property "datePublished" (type "Thing") has an unknown type. Add its type to the config file.
[error] The property "illustrator" (type "Thing") has an unknown type. Add its type to the config file.
[error] The property "isbn" (type "Thing") has an unknown type. Add its type to the config file.
[error] The property "numberOfPages" (type "Thing") has an unknown type. Add its type to the config file.
[error] The property "name" (type "Thing") has an unknown type. Add its type to the config file.
[error] The property "description" (type "Thing") has an unknown type. Add its type to the config file.
[error] The property "url" (type "Thing") has an unknown type. Add its type to the config file.
[error] The property "birthDate" (type "Thing") has an unknown type. Add its type to the config file.
[error] The property "gender" (type "Thing") has an unknown type. Add its type to the config file.
[error] The property "name" (type "Thing") has an unknown type. Add its type to the config file.
[error] The property "description" (type "Thing") has an unknown type. Add its type to the config file.
[error] The property "url" (type "Thing") has an unknown type. Add its type to the config file.

and following entities:

Book

<?php

namespace AppBundle\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @see http://schema.org/Thing Documentation on Schema.org
 * 
 * @ORM\Entity
 * @ApiResource(iri="http://schema.org/Thing")
 */
class Book
{
    /**
     * @var int
     * 
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
    /**
     * @var ArrayCollection<Person>
     * 
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Person")
     * @ORM\JoinTable(name="book_author")
     */
    private $author;
    /**
     * @var Organization
     * 
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Organization")
     * @ORM\JoinColumn(nullable=false)
     */
    private $publisher;

    public function __construct()
    {
        $this->author = new ArrayCollection();
    }

    /**
     * Sets id.
     * 
     * @param int $id
     * 
     * @return $this
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * Gets id.
     * 
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Adds author.
     * 
     * @param Person $author
     * 
     * @return $this
     */
    public function addAuthor(Person $author)
    {
        $this->author[] = $author;

        return $this;
    }

    /**
     * Removes author.
     * 
     * @param Person $author
     * 
     * @return $this
     */
    public function removeAuthor(Person $author)
    {
        $this->author->removeElement($author);

        return $this;
    }

    /**
     * Gets author.
     * 
     * @return ArrayCollection<Person>
     */
    public function getAuthor()
    {
        return $this->author;
    }

    /**
     * Sets publisher.
     * 
     * @param Organization $publisher
     * 
     * @return $this
     */
    public function setPublisher(Organization $publisher = null)
    {
        $this->publisher = $publisher;

        return $this;
    }

    /**
     * Gets publisher.
     * 
     * @return Organization
     */
    public function getPublisher()
    {
        return $this->publisher;
    }
}

Organization

<?php

namespace AppBundle\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;

/**
 * @see http://schema.org/Thing Documentation on Schema.org
 * 
 * @ORM\Entity
 * @ApiResource(iri="http://schema.org/Thing")
 */
class Organization
{
    /**
     * @var int
     * 
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * Sets id.
     * 
     * @param int $id
     * 
     * @return $this
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * Gets id.
     * 
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }
}

Person

<?php

namespace AppBundle\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;

/**
 * @see http://schema.org/Thing Documentation on Schema.org
 * 
 * @ORM\Entity
 * @ApiResource(iri="http://schema.org/Thing")
 */
class Person
{
    /**
     * @var int
     * 
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * Sets id.
     * 
     * @param int $id
     * 
     * @return $this
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * Gets id.
     * 
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }
}

I found that output on the TravisCI which reports the same:

https://travis-ci.org/api-platform/schema-generator/jobs/134156337

[feature-request] generate yml configuration instead of annotations

The title really says it all. When you put ORM-mapping information AND validation rules in the entity using annotations the entity file can become rather big and more difficult to read.

So sometimes I prefer to put al that in yaml files and I would really love it if the schema generator could have an option to generate those files instead of generating annotations.

[question] when use schema.org+schema-generator

Hello

[schema.org+schema-generator] is recommended for big and complex project

There is a recommendation when use or not schema.org
example :
is better to created entity User or Person like in schema.org

@Assert\NotNull annotation always added for attributes with custom name

On the last api-platform distribution.

Actual Result

When I generate entity with an attribute that is not in schema.org, @Assert\NotNull annotation is always added.

Expected Result

@Assert\NotNull should be added only when I write nullable: false.

Example

/api-platform/api/config/schema.yml

types:
    Thing:
        parent: false 
        properties:
            name: ~
            customName: {range: Text}
            otherCustomName: {range: Text, nullable: true, ormColumn: 'type="text", nullable=true'}

/api-platform/api/src/Entity/Thing.php

class Thing
{
[...]
    /**
     * @var string|null the name of the item
     *
     * @ORM\Column(type="text", nullable=true)
     * @ApiProperty(iri="http://schema.org/name")
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(type="text")
     * @Assert\NotNull
     */
    private $customName;

    /**
     * @var string
     *
     * @ORM\Column(type="text", nullable=true)
     * @Assert\NotNull
     */
    private $otherCustomName;
[...]

For a standard attribute, the @Assert\NotNull annotation is not added.
but that's the case for all other custom entities.

Generating the Normalizer / Denormalizer Class

Since we have all informations about a class and its properties, it should be easy to generate normalizer and a denormalizer compatible with the symfony interface.

I believe the performance of such generated normalizer would be better than using PropertyAccess (as it would plain php object only using simple methods).

However using templates for such generation is really a pain and it would be better to generate an AST which will then be transformed into PHP code.

I have done this in this library (for json schema) https://github.com/jolicode/jane and maybe we can collaborate to use this principle for schema.org model, WDYT ?

[enhancement] don't make abstract classes and embeddables api resources

Right now if I have this schema.yml

types:
    Thing:
        properties:
            name: ~

    Person:
        properties:
            familyName: ~

    Country:
        parent: false
        embeddable: true
        properties:
            address: { range: "Text" }

    PostalAddress:
        parent: false
        properties:
            addressCountry: { range: "Country", embedded: true }

It will generate all the entities and all entities are marked as an api resource in the class annotations. The only problem is that you don't want Thing and Country to be api resources. Thing is an abstract class so it can't even be initialized. And since Country is an embeddable it isn't linked to any database table so you can never fetch any countries from the api.

same table name for two relations

Hi!

I'm experiencing issue with php schema.

I've got following entity:

  Organization:
    properties:
      contactPoint: { range: Person }
      member: { range: Person, cardinality: (1..*) }

Which causes the following error at generation :

The table with name 'api.organization_person' already exists.

Is there an option to force relation table name ?

Thank you

[enhancement] generate entity constructors with all non-nullable properties

If my schema.yml says this:

Product:
  parent: false
  properties:
    name: { nullable: false }

Then I would love it if my generated Product.php then contains a constructor function which requires the $name property. Like this:

// src/AppBundle/Entity/Product.php

class Product
{
    // ...

    public function __construct(string $name)
    {
        $this->setName($name);
        // using the setter that already exists
        // so we can utilize any validation that that method might have
    }

    // ...
}

That way you can guarantee when I or another developer wants to initialize a new Product, that it will be a valid entity right after initialization.

Upgrade to Twig 2.0?

This package prevents using twig 2.0

Is it basically compatible and just needs an update to the composer.json? if so, it would be nice, if "^1.0 || ^2.0" can be used as the version contraint

api-platform/schema-generator  v1.2.0  requires  twig/twig (^1.0)
symfony/symfony                v3.3.2  requires  twig/twig (~1.34|~2.4)

[enhancement] add api endpoints for retrieving form schemas

So what I mean is to be able to make a GET request to something like /api/books/create.json and then get a json back which defines which fields are accepted for a create-action and what validation those fields have. And then of course also for /api/books/edit.json, since sometimes those two actions have different fields and validation associated with them.

Then I could write a service which translates that schema into a schema that for example Angular Formly can understand and boom! Automatic form generation directly from the entities themselves!

Enabling the possibility to extend FOSUserBundle's BaseUser class

Q A
Bug fix? no
New Feature? yes
BC Breaks? no
Deprecations? no
Tests pass? yes
Fixed tickets n/a
License MIT
Doc PR

I have a class Person and want it to automatically extend the FOSUserbundle's BaseUser class each time I'm rung the generator.

# File src/TypesGeneratorConfiguration.php

->prototype('array')
    ->children()
        ->arrayNode('extendsFOSUser')
            ->addDefaultsIfNotSet()
            ->info('Is the class should extend FOSUserBundle?')
            ->children()
                ->scalarNode('namespaceAlias')->defaultNull()->info('The FOSUserBundle namespace alias')->end()
            ->end()
        ->end()
    ...
/** File src/TypesGenerator.php **/

/**
     * @var string
     */
    const FOS_USER_BUNDLE_NAMESPACE = 'FOS\UserBundle\Model\User';
    /**
     * @var string
     */
    const FOS_USER_BUNDLE_NAMESPACE_ALIAS = 'BaseUser';


    /**
     * Generates files.
     */
    public function generate($config)
    {
        $baseClass = [
            ...
            'hasChild' => false,
            'abstract' => false,
            'extendsFOSUser' => false,
        ];
    }

    // Second pass
    foreach ($classes as &$class) {
        ...
        if (isset($config['types'][$class['name']]['extendsFOSUser'])) {
            if (false === $class['parent']) {
                $configFOSNamespaceAlias = $config['types'][$class['name']]['extendsFOSUser']['namespaceAlias'];
                $class['parent'] = null !== $configFOSNamespaceAlias ? $configFOSNamespaceAlias : self::FOS_USER_BUNDLE_NAMESPACE_ALIAS;
                $class['uses'][] = sprintf('%s as %s', self::FOS_USER_BUNDLE_NAMESPACE, $class['parent']);
            } else {
                $this->logger->error(sprintf('[extendsFOSUser] class "%s" already extends class "%s"', $class['name'], $class['parent']));
            }
        }
    }

I'd like to check if the FOSUserbundle bundle is:
1/ Installed
2/ Activated

Could someone tell me what's the best practise, please?
Does anyone extend the Person class with FOSUserBundle?
How do you manage it, by hand?

Thanks

@Assert\NotNull annotation automatically added in all fields

Taken from api-platform/api-platform#363

Actual Result

When generate entity file using schema.yml file, @Assert\NotNull annotation automatically added.

Expected Result

@Assert\NotNull should not add in entity file

/api-platform/app/config/schema.yml

    Users:                       
        parent: false
        properties:
            createdAt: { range: "DateTime" }
            updatedAt: { range: "DateTime" } 
            username: { range: "Text", ormColumn: 'type="string", length=255' }
            email: { range: "Text", ormColumn: 'type="string", length=255' }
            password: { range: "Text", ormColumn: 'type="string", length=255' }

Entity generate using command:

php vendor/bin/schema generate-types src/ app/config/schema.yml

/api-platform/src/AppBundle/Entity/Users.php

<?php

namespace AppBundle\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * The most generic type of item.
 *
 * @see http://schema.org/Thing Documentation on Schema.org
 *
 * @ORM\Entity
 * @ApiResource(iri="http://schema.org/Thing")
 */
class Users
{
    /**
     * @var int
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var \DateTime
     *
     * @ORM\Column(type="datetime")
     * @Assert\DateTime
     * @Assert\NotNull
     */
    private $createdAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(type="datetime")
     * @Assert\DateTime
     * @Assert\NotNull
     */
    private $updatedAt;

    /**
     * @var string
     *
     * @ORM\Column(type="string", length=255)
     * @Assert\Type(type="string")
     * @Assert\NotNull
     */
    private $username;

    /**
     * @var string
     *
     * @ORM\Column(type="string", length=255)
     * @Assert\Type(type="string")
     * @Assert\NotNull
     */
    private $email;

    /**
     * @var string
     *
     * @ORM\Column(type="string", length=255)
     * @Assert\Type(type="string")
     * @Assert\NotNull
     */
    private $password;
    ....
    ....
    ....
}

Generate JSON-LD

Hi,
I've generated PHP-Models with the php-schema tool.

Now i want to generate JSON-LD code from the given PHP-Models,
but there is nothing but an note about serializing the data as JSON-LD.
Are there any examples how to serialize/generate the JSON-LD code?
I cant find anything about this in the documentation.

Notice: I does not use symfony, i'm working with zf2.

regards

Choose a different entity name

Is it possible to choose a different Entity name than the id from schema.org? For example, if I want to use the Organization type I would list Organization under types in the yaml file. Then the Entity would be called Organization and placed in Organization.php. What if I want to use the Organization type but call the Entity something else (Team, Club, Group, or whatever)? I may have missed this in the documentation, but it looks to me like the only way to do this is to manually refactor the output files in my IDE.

Generate Entities from our own schema extending schema.org

Hi,

I don't know if these is an issue or a feature not already implemented.

I have for example, a vocabulary that extends schema.org vocabulary

File data/schema.rdfa

<div typeof="rdfs:Class" resource="http://example/Language">
      <span class="h" property="rdfs:label">Language</span>
      <span>Subclass of: <a property="rdfs:subClassOf" href="http://schema.org/Language">Language</a></span>
      <span property="rdfs:comment"></span>
</div>

<div typeof="rdfs:Property" resource="http://example/locale">
    <span property="rdfs:label">locale</span>
    <span property="rdfs:range">Text</span>
    <span property="rdfs:comment">locale of the language</span>
    <span property="rdfs:domain">http://example/Language</span>
</div>

Here is the yml file to generate my entities

rdfa:
   - http://schema.org/docs/schema_org_rdfa.html
   - data/schema.rdfa
annotationGenerators:
    - SchemaOrgModel\AnnotationGenerator\PhpDocAnnotationGenerator
    - SchemaOrgModel\AnnotationGenerator\DoctrineOrmAnnotationGenerator
    - SchemaOrgModel\AnnotationGenerator\ConstraintAnnotationGenerator
    - SchemaOrgModel\AnnotationGenerator\DunglasJsonLdApiAnnotationGenerator
namespaces:
  entity: AppBundle\Entity
types:
  http://example/Language:
    properties:
      name: ~
      locale: ~

I execute :

./bin/schema generate-types src app/config/schema.yml -vvv
[critical] Type "http://example/Language" cannot be found.

So, what is the problem ?
php-schema doesn't support extending another schema yet ?
And the solution is to generate entities from schema.org only and modify them after ?

Thanks

~ = including all its properties ?

Hi,

In the Api-platform documentation, it is said that TypeId: ~ = including all its properties

types: 
  BlogPosting: ~ # A type to generate a PHP entity class from, including all its properties

But when I use bin/schema generate-types src/ app/config/schema.yml, it generate only the id.
am I doing something wrong ?

Thank you for your assistance ;)

Wrong hard-coded paths for autoload.php

Original issue: api-platform/api-platform#684
Author: @danielclariondoor

Running "docker-compose exec php vendor/bin/schema" as mentioned in the documentation results in

Warning: require_once(/srv/api/vendor/bin/../vendor/autoload.php): failed to open stream: No such file or directory in /srv/api/vendor/bin/schema on line 15

Fatal error: require_once(): Failed opening required '/srv/api/vendor/bin/../vendor/autoload.php' (include_path='.:/usr/local/lib/php') in /srv/api/vendor/bin/schema on line 15

It seems like the schema executable doesn't support running from vendor/bin. But it'd be better if we could avoid hard-coded paths... (How?)

Add optional config to enforce line lengths

As this project is responsible for generating classes to be included in other projects. Each of these projects may have different code standards.

I use PSR-2 coding styles in my projects. One of the requirements relates to line lengths. Instead of beginning the conversation of "enforcing code standards" and the nightmare that might be under there, I wanted to propose a hook to allow you to express some line limits and update the publishing tool to enforce these.

For now, I have to manually update these classes.

Thoughts?

Publish a generated version to packagist.

Would it be possible to publish all generated models to packagist?

While the code generator allows me to generate code from schema.org, I cannot code against a common / wellknown interface.

For example https://github.com/php-fig/http-message is a set of interfaces that I can include and code against.

Ideally I'd like to see the same for Schema.org. Since you have built the schema generator I wanted to give you the option first!
If you are not interested I will consider using your generator to generate and publish a repository to packagist!

Cheers

Full Schema generation incorrect

Hi,

When attempting to generate the entire schema as described in the documentation:

Without configuration file, the tool will build the entire Schema.org vocabulary. If no properties are specified for a given type, all its properties will be generated.

No properties are generated in any of the Entities. Example config:

rdfa:
  - vendor/api-platform/schema-generator/tests/data/schema.rdfa

# The PHP namespace of generated entities
namespaces:
  # The namespace of the generated entities
  entity: App\Schema\Entity
  # The namespace of the generated enumerations
  enum: App\Schema\Enum
  # The namespace of the generated interfaces
  interface: App\Schema\Model

annotationGenerators:
    - ApiPlatform\SchemaGenerator\AnnotationGenerator\PhpDocAnnotationGenerator

This generates all schema Entities and Enum but the entities are only generated with the ID setters/getters. Specifying each type individually creates the remaining properties as expected.

Possibly the same issue as #62, however the solution to use the test schema.rdfa does not work in my example.

Generate properties from parent class in subclass

Hi,

Thanks for this package.
I try to generate entities with this app/config/schema.yml configuration :

rdfa:
  - https://raw.githubusercontent.com/schemaorg/schemaorg/sdo-gozer/data/schema.rdfa
annotationGenerators:
    - SchemaOrgModel\AnnotationGenerator\PhpDocAnnotationGenerator
    - SchemaOrgModel\AnnotationGenerator\DoctrineOrmAnnotationGenerator
    - SchemaOrgModel\AnnotationGenerator\ConstraintAnnotationGenerator
    - SchemaOrgModel\AnnotationGenerator\DunglasApiAnnotationGenerator
namespaces:
  entity: AppBundle\Entity
debug: true
types:
  Thing:
    properties:
      name: ~
      description: ~
      url: ~
  CreativeWork: ~
  WebSite:
    properties:
      mainEntityOfPage:
        range: WebPage
        cardinality: (0..1)
  WebPage:
    properties:
      mainEntityOfPage:
        range: Organization
        cardinality: (0..1)
      mainEntity:
        range: WebSite
        cardinality: (0..1)
  Organization: ~

I generate the entities with the command : bin/schema generate-types src/ app/config/schema.yml
My problem is that the 2 properties mainEntityOfPage (which belong to Thing) and mainEntity (which belong to CreativeWork) were not generated in WebSite and WebPage entities.
I try to add directly mainEntityOfPage or mainEntity in subclasses because in parent classes, the targetEntity depends on the entity.

What is the best way to manage that ?
Do I have to insert manually mainEntityOfPage mainEntity attributes, and getter / setter ?

Thanks,
Jean-Fei

Add support for Symfony's access control expressions

Hi

As per security docs it would be great if we could add this to the generator. e.g. person.yaml

types:
    Person: 
        security: |
            attributes={"access_control"="is_granted('ROLE_USER')"},
            collectionOperations={
                "get",
                "post"={"access_control"="is_granted('ROLE_ADMIN')"}
            },
            itemOperations={
                "get"={"access_control"="is_granted('ROLE_USER') and object.owner == user"}
            }

[enhancement] turn enums into embeddables

You can do this by requiring the enum package in the composer.json of this project and then extending it so you can make this:

namespace ApiPlatform\SchemaGenerator;

use Doctrine\ORM\Mapping as ORM;
use MyCLabs\Enum\Enum as OriginalEnum;

/** @ORM\Embeddable */
class Enum extends OriginalEnum
{
    /** @ORM\Column */
    protected $value;
}

And of course then making every generated enum extend this enum class.

edit:

yes I guess this should probably be a part of doctrine itself instead of this schema-generator. But I'm afraid that it would never be implemented in doctrine, so that's why I'm asking here.

Integrate Relationships outside schema generator bundle for ownership

Hello there! Fantastic project, I love it 👍

I have defined my custom AuthBundle with my entities inside App\Entity\AuthBundle without the schema generator and I am trying to generate my APIs schemas as follows:

namespaces:
     entity: App\Entity\ArticlesBundle

types:
     Articles:
          ....
          user: { range: App\Entity\AuthBundle\User, cardinality: (*..1) }

but I always get an undefined index
Is there something that I am missing from the documentation?

I was hoping for something similar to this PR:

namspace:
     entity: ...
     alias:
        - { namespace: App\Entity\AuthBundle, resolvePath: src/Entity/AuthBundle }

this has been overwritten by a more general "prefix" in this PR that I am not fully understanding.

Is there any Yaml solution for implementing this?
Thank you 🥇

property columnPrefix only allow boolean value

...But doctrine allow prefixes like this: columnPrefix="myprefix_"

schema.yml:

Vehicle:
        properties:
                emissionsCO2: { range: "VehicleEmissionsCO2", embedded: true, columnPrefix: "emissionsCO2_" }

Error:

Invalid type for path "config.types.Vehicle.properties.emissionsCO2.columnPrefix". Expected boolean, but got string.
Hint: The property columnPrefix

The schema generator puts the files in the wrong folder

Original issue: api-platform/api-platform#685
Author: @danielclariondoor

Running "vendor/bin/schema generate-types api/src/ api/config/schema.yaml"
The files are placed into src/AppBundle/Entity/ with a namespace to match, instead of in src/Entity, which is where services.yaml expects to find them. This causes a fatal error in the api frontend:

(2/2) FileLoaderLoadException
Expected to find class "App\AppBundle\Entity\PostalAddress" in file "/srv/api/src/AppBundle/Entity/PostalAddress.php" while importing services from resource "../src/*", but it was not found! Check the namespace prefix used with the resource in /srv/api/config/services.yaml (which is loaded in resource "/srv/api/config/services.yaml").

How do I define a OneToMany relationship in the schema.yml file

I'm trying to create a OneToMany relationship in my schema.yml file, as I can see the documentation that the Person class has an $address that's a @ManyToOne, but I cannot find info on how to configure this from the schema.yml file.

Is this possible, and if so, is it documented anywhere?

The inheritance of entities and the namespaces

Hello everyone,

One little example is worth a thousand words:

Person:
    namespaces:
        class: AppBundle\Entity\SchemaOrg
    properties:
        gender: ~
        givenName: ~
        familyName: ~
        ....

Profile:
    properties:
        ....

Entity generated :

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
....

/**
 * @ORM\Entity
 */
class Profile extends Person
{
    /**
     * @var int
     * 
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    ...

The generator does not take into account the Person namespace, it lacks the use operator

use AppBundle\Entity\SchemaOrg\Person

it's a bug?

Thanks

[enhancement] also generate faker yaml files which leverages hautelook/AliceBundle

I guess it should be possible to map every Schema.org property to a reasonable faker-data-point. This would just be so nice to have. To be able to just write a simple yaml file saying what schemas with which properties you want to use from Schema.org, execute a console command and then to immediately have entities, working api endpoints and fake data ready to go.

Bad assert @Assert\Choice in Enum

I have a problem when generating an Enum class. I dont now if i am doing somthing wrong. The assert choice callback is generated without the enum namespace:

@Assert\Choice(callback={"ItemAvailability", "toArray"})
should be
@Assert\Choice(callback={"App\Enum\ItemAvailability", "toArray"})

types:
  Offer:
    parent: false
    properties:
      availability: { range: ItemAvailability }
  ItemAvailability:
    parent: false
    properties: {}
class Offer
{
/**
     * @var string|null the availability of this item—for example In stock, Out of stock, Pre-order, etc
     *
     * @ORM\Column(nullable=true)
     * @Assert\Choice(callback={"ItemAvailability", "toArray"})
     * @ApiProperty(iri="http://schema.org/availability")
     */
    private $availability;
}

If I am doing correct I think the error could be in the next line

https://github.com/api-platform/schema-generator/blob/master/src/AnnotationGenerator/ConstraintAnnotationGenerator.php#L74

If I change the line 74 works ok.

$assert = sprintf('@Assert\Choice(callback={"%s", "toArray"}', $field['range']);
$assert = sprintf('@Assert\Choice(callback={"%s%s", "toArray"}', sprintf('%s\\%s', $this->config['namespaces']['enum'], $class['name']), $field['range']);

Symfony 4 and wrong path to Entities

Symfony 4 updates file structure and removes AppBundle folder.

The easiest solution would be to remove AppBundle from path and change default namespace from AppBundle to App.

Customize output configuration, retain namespace

Hello, great package.

I have just begun utilizing this package in one of my projects and have encountered a roadblock. My project utilizes composer and a PSR-4 autoloading namespace to associate all files in ./src with Vendor\Package namespace.

When configuring the utility I've educated myself on the process of declaring the desired namespace; my current configuration:

namespaces:
  entity: "Vendor\Package\Schema"

When I execute the following build command:

bin/schema generate-types ./src config.yml

It creates the directory structure src > Vendor > Package > Schema, filled with classes (this does not surprise me; it is what the documentation says), each appropriately namespaced Vendor\Package\Schema.

Is there a way to specify the target namespace and a mapping of a base directory to parent namespace such that I can build into my ./src directory and it will create src > Schema, filled with my classes, each appropriately namespaced Vendor\Package\Schema?

An example from my thoughts might be to include an option in the build command like:

bin/schema generate-types ./src config.yml --base-namespace=Vendor\Package

Any thoughts?

Using ormColumn on a property defaults it to not nullable

Don't know whether this is a bug or a documentation issue, but using the ormColumn key under a property in the schema file defaults that property to non-nullable.

Using the nullable key under the property has no effect. You can set the property to be nullable within the ormColumn value.

Schema

types:
    Person:
        properties:
            telephone:      { ormColumn: 'type="string",length=100', nullable: true }

Expected class:

class Person
{
    /**
     * @var string|null
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="UUID")
     * @ORM\Column(type="guid")
     * @Assert\Uuid
     */
    private $id;

    /**
     * @var string|null the telephone number
     *
     * @ORM\Column(type="string",length=100,nullable=true)
     * @ApiProperty(iri="http://schema.org/telephone")
     */
    private $telephone;

Expected SQL

CREATE TABLE person (id CHAR(36) NOT NULL COMMENT '(DC2Type:guid)', telephone VARCHAR(100) DEFAULT NULL

Actual class:

class Person
{
    /**
     * @var string|null
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="UUID")
     * @ORM\Column(type="guid")
     * @Assert\Uuid
     */
    private $id;

    /**
     * @var string|null the telephone number
     *
     * @ORM\Column(type="string",length=100)
     * @ApiProperty(iri="http://schema.org/telephone")
     */
    private $telephone;

Actual SQL:

CREATE TABLE person (id CHAR(36) NOT NULL COMMENT '(DC2Type:guid)', telephone VARCHAR(100) NOT NULL

Workaround:

types:
    Person:
        properties:
            telephone:      { ormColumn: 'type="string",length=100,nullable=true' }

Other info

api-platform/api-pack             1.1.0              A pack for API Platform
api-platform/core                 v2.2.8             The ultimate solution to create web APIs.
api-platform/schema-generator     v2.1.0             Various tools to generate a data model based on Schema.org vocables

For properties without ormColumn set, nullable is the default as stated in the docs.

Relation table indexes set to "UNIQUE" using schema generator

Actual Result

In relationships table fields user_id and other_user_id are set as indexes type "UNIQUE".

Expected Result

In relationships table fields user_id and other_user_id are should set as indexes type "INDEX".

Sample Schema & Entity

In below example attached users and user_friends table structure.

/api-platform/app/config/schema.yml

    Users:                       
        parent: false
        properties:
            createdAt: { range: "DateTime" }
            updatedAt: { range: "DateTime" } 
            role: { range: "Roles", ormColumn: 'type="bigint"' }
            username: { range: "Text", ormColumn: 'type="string", length=255' }
            email: { range: "Text", ormColumn: 'type="string", length=255' }
            password: { range: "Text", ormColumn: 'type="string", length=255' }
            firstName: { range: "Text", ormColumn: 'type="string", length=255, nullable=true' }
            lastName: { range: "Text", ormColumn: 'type="string", length=255, nullable=true' }

    UserFriends:   
        parent: false
        properties:
            createdAt: { range: "DateTime" }
            updatedAt: { range: "DateTime" } 
            User: { range: "Users", ormColumn: 'type="bigint"' }
            otherUser: { range: "Users", ormColumn: 'type="bigint"' }

Entity generate using command:

php vendor/bin/schema generate-types src/ app/config/schema.yml

/api-platform/src/AppBundle/Entity/Users.php

<?php

namespace AppBundle\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * The most generic type of item.
 *
 * @see http://schema.org/Thing Documentation on Schema.org
 *
 * @ORM\Entity
 * @ApiResource(iri="http://schema.org/Thing")
 */
class Users
{
    /**
     * @var int
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
    ....
    ....
    ....
}

/api-platform/src/AppBundle/Entity/UserFriends.php

<?php

namespace AppBundle\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * The most generic type of item.
 *
 * @see http://schema.org/Thing Documentation on Schema.org
 *
 * @ORM\Entity
 * @ApiResource(iri="http://schema.org/Thing")
 */
class UserFriends
{
    /**
     * @var int
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var \DateTime
     *
     * @ORM\Column(type="datetime")
     * @Assert\DateTime
     * @Assert\NotNull
     */
    private $createdAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(type="datetime")
     * @Assert\DateTime
     * @Assert\NotNull
     */
    private $updatedAt;

    /**
     * @var Users
     *
     * @ORM\OneToOne(targetEntity="AppBundle\Entity\Users")
     * @ORM\JoinColumn(nullable=false)
     * @Assert\NotNull
     */
    private $User;

    /**
     * @var Users
     *
     * @ORM\OneToOne(targetEntity="AppBundle\Entity\Users")
     * @ORM\JoinColumn(nullable=false)
     * @Assert\NotNull
     */
    private $otherUser;
    ....
    ....
    ....
}

Update Table using command

php bin/console doctrine:schema:update --force

Create Table Structure

table_users
table_ user_friends

Error with schema generator

from @vdebes at api-platform/api-platform#653
app/config/schema.yml

  Person:
    properties:
      email: { unique: true, nullable: false }
      identifier: { range: "Text", unique: true, nullable: false }

src/AppBundle/Entity/Person.php

class Person
{
    /**
     * @var int|null
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @var string email address
     *
     * @ORM\Column(type="text"unique=true)
     * @ApiProperty(iri="http://schema.org/email")
     * @Assert\Email
     * @Assert\NotNull
     */
    private $email;

    /**
     * @var string
     * @ORM\Column(type="text"unique=true)
     * @ApiProperty(iri="http://schema.org/identifier")
     * @Assert\NotNull
     */
    private $identifier;

The generated Person entity displays @ORM\Column(type="text"unique=true) which is incorrect and needs to be corrected before a schema update.

Support namespaces other than schema.org (and fix the Doc)

Currently the namespace is hardcoded in the TypesGenerator.

(by the way: the "rdfa" configuration key documentation and the name itself is not correct. There is support for many more Parsers in the used Lib EasyRdf than just RDFa. The config key should be renamed at the same moment when other namespaces are supported.)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.