Class 'JsonValidator' not found - php

https://github.com/hasbridge/php-json-schema
Getting error Class 'JsonValidator' not found.
I did install composer.json as in git folder.
I did put my json schema, json data files in src/Json and created a php file to validate as mentioned in git.
getting error class Class 'JsonValidator' not found.

In their example, they're creating a JsonValidator object.
This is different from the actual namespace of the class, which is Json\Validator.
Try dropping use Json\Validator as JsonValidator at the top of your file so that you're able to refer to the class the same way the docs do.
I'd expand their docs from:
$someJson = '{"foo":"bar"}';
$jsonObject = json_decode($someJson);
$validator = new JsonValidator('/path/to/yourschema.json');
$validator->validate($jsonObject);
To
<?php
namespace Your\Domain;
use Json\Validator as JsonValidator;
require_once('./vendor/autoload.php');
$someJson = '{"foo": "bar"}';
$jsonObject = json_decode($someJson);
$validator = new JsonValidator('/path/to/yourschema.json');
$validator->validate($jsonObject);
Alternatively, you could substitute new JsonValidator('/path/to/yourschema.json') for new Json\Validator('/path/to/yourschema.json').
Edit: By the way - you might find the example schemas at json-schema.org helpful when using this library.
Here's the main one from that link:
{
"title": "Example Schema",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
}
},
"required": ["firstName", "lastName"]
}
Save this file somewhere in your project and refer to it instead of /path/to/yourschema.json.

Related

How to autoload a class inside the composer file and run a script?

I'm on Drupal 9.3.x trying to add a script to run with composer, following this guide
I've tried either to add the autoload and script part to the drupal project composer.json file
{
"name": "drupal/d9-starter-kit",
"description": "Project template for D9 starter kit",
"type": "project",
"license": "GPL-2.0-or-later",
"homepage": "https://www.drupal.org/project/drupal",
"support": {
"docs": "https://www.drupal.org/docs/user_guide/en/index.html",
"chat": "https://www.drupal.org/node/314178"
},
"autoload": {
"classmap": [
"Drupal\\d9_starter_kit\\Starter.php"
]
},
"scripts": {
"doStart": [
"Drupal\\d9_starter_kit\\Starter::doStart"
]
},
// require, extra, etc...
}
or to create a composer.json inside the custom module I've made
{
"name": "drupal/d9_starter_kit",
"type": "drupal-custom-module",
"description": "a module to script the start",
"license": "proprietary",
"authors": [
{
"name": "My name",
"email": "mymail#mail.com"
}
],
"require": {},
"autoload": {
"classmap": [
"src\\Starter.php"
]
},
"scripts": {
"doStart": [
"Drupal\\d9_starter_kit\\Starter::doStart"
]
}
}
and include that to the project composer file, according the the guide on Drupal site
The path of the Start class is web/modules/custom/d9_starter_kit/src/Starter.php
<?php
namespace Drupal\d9_starter_kit;
class Starter {
public static function doStart() {
print('test');
// TODO
}
}
I've tried various other syntax for the autoload part - e.g. d9_starter_kit\\Starter.php - but none works.
I get the following error
Could not scan for classes inside "Drupal\d9_starter_kit\Starter.php" which does not appear to be a file nor a folder
Class Drupal\d9_starter_kit\Starter is not autoloadable, can not call doStart script
What is the correct way to autoload the class and run a script? The objective of the latter is the same of the guide, copy, rename and edit some files in order of automate the "start up" of a custom project template.

Composer class not Found Error

I've been working on a project and for which I needed to make a package. But it always returns
PHP Fatal error: Uncaught Error: Class 'youtubetomp3\downloader' not found
Here the structure of directory.
youtubetomp3/
src/
downloader.php
test/
downloaderTest.php
composer.json
composer.lock
and other files
The composer.json contains following details.
{
"name": "princeyadav05/youtubetomp3",
"description": "Downloads mp3 of a video given video-id",
"keywords": ["youtube", "songs", "downloader", "package"],
"license": "",
"authors": [
{
"name": "Prince Yadav",
"email": "princeyadav96#gmail.com"
}
],
"type": "package",
"require": {
"php": ">=5.4",
"php-ffmpeg/php-ffmpeg": "^0.11.0"
},
"require-dev": {
"phpunit/phpunit": "5.2.*"
},
"autoload": {
"psr-4": {
"princeyadav05\\youtubetomp3\\": "src/"
}
}
}
And this is how I'm creating object of class.
<?php
require 'vendor/autoload.php';
require 'scrapper.php';
include 'database.php';
echo "** WELCOME TO THE MP3 DOWNLOADER ** \n \n";
$name = readline("Hey There. Lets start with your name : ");
echo "\nHello " . $name . ".\n";
$search = readline("Please enter the search query : ");
$data_array = searchVideo($search); //returns data array
displayVideos($data_array); // returns video id
$download = new downloader();
$video_details = $download->downloadSong($video_id);
// returns array with video title, Duration, url, path
savingToDb($video_title, $video_duration, $video_url, $songs_path);
?>
Please help. I've tried many things but nothing worked.I'm really frustrated.
It's not clear whether you're including autoload.php file generated by composer. Would you mind posting the full code?
Then I'm not sure about your autoload directive, I would try something like this:
"autoload": {
"classmap": [
"src/"
]
},
see composer docs for more info

Symfony2 (deserialize): update entity (with association) with json

I got the serializer in Symfony working, i can GET and POST json with the EntityController. I have an edit form where an existing object/entity can be edited and saved. When the edited object gets posted (as a json object) the json objects gets deserialized, persisted and flushed tot the database. So far so good, at least as long as i dont post associated (ManyToMany) entities.
I have two entities (with a ManyToMany association):
Object
Element
This works (see also the jsonEditAction in the controller(posted below)):
{
"id": "1",
"name": "object 1"
}
My question is: How can i edit the object with associated entities in the json, like this:
{
"id": "1",
"name": "object 1",
"elements": {
"0": "1",
"1": "2"
}
}
When i post the above json i get the following notice from Symfony:
"message": "Expected argument of type \"AppBundle\Entity\Element\", \"integer\" given",
"class": "Symfony\Component\PropertyAccess\Exception\InvalidArgumentException",
For further information; this is the editAction where the Json is posted to:
public function jsonEditAction(Request $request, $id) {
$serializer = $this->initSerializer();
$em = $this->getDoctrine()->getManager();
$object = $em->getRepository('AppBundle:Object')->findOneById($id);
$data = $request->getContent();
$serializer->deserialize($data, 'AppBundle\Entity\Object', 'json', array('object_to_populate' => $object));
try {
$em->persist($object);
$em->flush();
$view = $this->view($object, 200)
->setTemplate("object/json.html.twig");
} catch (Exception $e) {
$view = $this->view('Caught exception: ' . $e->getMessage() . "\n", 500)
->setTemplate("object/json.html.twig");
}
return $this->handleView($view);
}
private function initSerializer() {
$encoders = array(new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$serializer = new Serializer($normalizers, $encoders);
return $serializer;
} `
Should i walk to the array with elements and find them one by one and then add them to the 'object' entity? Or is there a 'build-in' solution in the serializer that i missed/ didn't see?
UPDATE:
Also the JSON like suggested by Alexey didn't work:
{
"id": 2,
"name": "Object 2c",
"elements": [{
"id": 1
}, {
"id": 2
}]
}
UPDATE:
My question is a duplicate of:
Deserialize an entity with a relationship with Symfony Serializer Component
There is a pull request created and will be merged in Symfony 3.2...
You have a bad JSON, Symfony says you the same.
A good JSON can look like this:
{
"id": "1",
"name": "object 1",
"elements": [
{"id": "254", "name": "element 254"},
{"id": "301", "name": "element 301"}
]
}
Symfony tries to deserialize an Element object from "1" and "2" in your original JSON and fails.

How to to prevent doctrine2 from returning certain fields

What I have coded is a oneToMany relationship with doctrine
one user ---> has many notifications
This is how I get the data
/**
* #Route("/test")
*/
public function testRoute()
{
//get the user notifications
$notifications = $this->getUser()->getNotifications();
//return json response
$serializer = $this->get('serializer');
$json = $serializer->serialize($notifications, 'json');
$response = new Response($json);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
This is what the controller returns
[
{
"id": 1,
"receiver": 1,
"notification_type": "new_comment",
"triggered_by": {
"id": 1,
"username": "gabriel",
"username_canonical": "gabriel",
"password": "3e6bS2I==",
"email": "ga#ga.de",
"first_name": "Gabriel",
"last_name": "ThaKid",
"likes_counter": 0,
"dislikes_counter": 2,
"favourites_counter": 0,
"profile_pic": "profilepic_60181.png",
"salt": "Lqch0N84UH1QmFI5O",
"form_token": "sO6NgWd",
"is_active": true,
"registration_confirmation": "success",
"secret_confirmation_id": "qTwNGm4CSKHzJOe8ry9DcXavt",
"socket_token": "KuMlxYHa"
},
"created_at": "2014-12-16T13:36:20+0100",
"link_to": "#test"
},
{
"id": 2,
"receiver": 1,
"notification_type": "new_comment",
"triggered_by": {
"id": 1,
"username": "gabriel",
"username_canonical": "gabriel",
"password": "3e6bS2IYX1DONLA/70a8hzMUQ==",
"email": "ga#ga.de",
"first_name": "Gabriel",
"last_name": "ThaKid",
"likes_counter": 0,
"dislikes_counter": 2,
"favourites_counter": 0,
"profile_pic": "profilepic_60181.png",
"profile_rank": "Beginner", (...)
},
"created_at": "2014-12-16T13:36:24+0100",
"link_to": "#test"
}
]
I think you get the point, it returns the notifications of a certain user which is allright,
I also need certain fields from the user, like the lastname and the firstname, so the returned data is usable in the application.
But doctrine also returns the hashed password and the salt along with tokens and information the user doesn't need to know.
how do I tell doctrine not to return those fields or not to fetch them to begin with?
This is not about Doctrine, this is the default Serializer that tries to fetch and return all of the values available.
Take a look at the Serializer component documentation to understand how to ignore properties. Basically, you'll have to pass a normalizer into your serializer's constructor:
<?php
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
$normalizer = new GetSetMethodNormalizer();
$normalizer->setIgnoredAttributes(array('age'));
$encoder = new JsonEncoder();
$serializer = new Serializer(array($normalizer), array($encoder));
$serializer->serialize($person, 'json');
Also, I'd strongly suggest to switch to JMSSerializer and/or use FOSRestBundle, as it gives a lot more flexibility for the serialization. The property list is configured against contexts, and has base exclusion strategies. This way, you'd only need to list properties to expose, not to exclude:
AppBundle\Entity\Car:
exclusion_policy: all
properties:
id:
expose: true
vendor:
expose: true
title:
expose: true
In the given example, all properties that were not listed would be excluded.
You should create a custom repository class.
In this class create a method like this:
// src/AppBundle/Entity/NotificationRepository.php
namespace AppBundle\Entity;
use Doctrine\ORM\EntityRepository;
class NotificationRepository extends EntityRepository
{
public function findAllByUser()
{
return $this->getEntityManager()
->createQuery(
'SELECT [only the fields you need] FROM [....]'
)
->getResult();
}
}
For the DQL query you could use the partial object syntax.

Referencing a custom composer package in Slim PHP

I'm trying to figure out how to reference a custom class using composer
my composer.json file looks like this:
{
"name": "adtools_api",
"repositories": [
{
"type": "package",
"package": {
"name": "qz/adtools_middleware",
"version": "dev-master",
"source": {
"url": "repo-name",
"type": "git",
"reference": "master"
}
}
}
],
"require": {
"slim/slim": "2.*",
"qz/adtools_middleware": "src/"
}
}
and the folder structure looks like this:
app
routes
vendor
composer
qz
adtools_middleware
src
hello-world.php
slim
composer.json
index.php
I'm trying to reference the hello-world.php file which looks like this:
<?php
namespace HelloWorld;
class SayHello
{
public static function world()
{
return 'Hello World, Composer!';
}
}
?>
In the index.php file I'm trying to reference the class like this:
$hello = new HelloWorld\SayHello();
but getting an error telling me "Fatal error: Class 'HelloWorld\SayHello' not found in..."
If anyone can point me in the right direction that would be great! Thank you!
Can you check the autoload inside the vendor folder and see if your HelloWorld namespace is loaded?
If not, you may need to add autoload attribute to your composer.json file, like this
{
"autoload": {
"psr-0": {"HelloWorld": "qz/adtools_middleware/src/"}
},
to load the HelloWorld namespace in your project

Categories