Creating Routing Paths using FosRestFundle in Symfony - rest

I am developing an Api for one of my projects in Symfony and I want create several routing paths like the following:
/api/messages/{id}
/api/messages/creator/{username}
/api/messages/receiver/{username}
My routing files are configured in this way (I will post just the info relating to the api config):
routing.yml:
NelmioApiDocBundle:
resource: "#NelmioApiDocBundle/Resources/config/routing.yml"
prefix: "/doc"
api:
type: rest
resource: "routing_api.yml"
prefix: /api
routing_api.yml:
api_message:
type: rest
resource: AppBundle\Controller\ApiMessagesController
api_chats:
type: rest
resource: AppBundle\Controller\ApiChatController
And my ApiMessagesController:
<?php
namespace AppBundle\Controller;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\View\RouteRedirectView;
use FOS\RestBundle\Controller\Annotations\RouteResource;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
/**
* Class ApiMessagesController
* #package AppBundle\Controller
*
* #RouteResource("messages")
*/
class ApiMessagesController extends FOSRestController{
/**
* Gets an individual Message
*
* #param int $id
* #return mixed
* #throws \Doctrine\ORM\NoResultException
* #throws \Doctrine\ORM\NonUniqueResultException
*
* #ApiDoc(
* output="AppBundle\Entity\Message",
* statusCodes={
* 200 = "Returned when successful",
* 404 = "Return when not found"
* }
* )
*/
public function getAction($id){;
return $this->get('app.message.manager')->findById($id);
}
/**
* Gets all messages sent by each users
*
* #param int $id
* #return mixed
* #throws \Doctrine\ORM\NoResultException
* #throws \Doctrine\ORM\NonUniqueResultException
*
* #ApiDoc(
* output="AppBundle\Entity\Message",
* statusCodes={
* 200 = "Returned when successful",
* 404 = "Return when not found"
* }
* )
*/
public function getCreatorAction($creator){
return $this->get('app.message.manager')->findByCreator($creator);
}
}
The route /api/messages/{id} works as I expected but I am really stuck right now about how to define the route /api/messages/creator/{creator} because Nelmio is telling me that I created this route /api/messages/{creator}/creator instead of /api/messages/creator/{username}
I think that I put all info regarding to my issue, but if something is missing tell me and I will update my question. Thanks

If you're not happy with URLs FOSRest does, you can always use #Route annotation and redefine everything you need.

Related

Punchout Iframe issue with Magento 2

I am trying to integrate the punchout system with Magento 2.
Magento does not allow opening iframe due to security reasons. I have added 'x-frame-options' => '*' option to the env.php file but still not allow to open the Iframe.
Also, I have changed the below file but I did not get the exact result.
vendor\magento\framework\App\Response\HeaderProvider\XFrameOptions.php
I am getting the below response from punchout. After that I am getting a blank screen.
In the punchout response x-frame-options showing twice.
Can you guide which settings are required to open the site in the Iframe?
Thanks in advance
I found a solution:
1 - Remove the x-frame-options from the env.php
2 - Override the \Magento\Framework\App\Response\HeaderProvider\XFrameOptions.php file ( don't forget the di.xml ) and comment the content of the __construct
class XFrameOptions extends \Magento\Framework\App\Response\HeaderProvider\XFrameOptions
{
/** Deployment config key for frontend x-frame-options header value */
const DEPLOYMENT_CONFIG_X_FRAME_OPT = 'x-frame-options';
/** Always send SAMEORIGIN in backend x-frame-options header */
const BACKEND_X_FRAME_OPT = 'SAMEORIGIN';
/**
* x-frame-options Header name
*
* #var string
*/
protected $headerName = Http::HEADER_X_FRAME_OPT;
/**
* x-frame-options header value
*
* #var string
*/
protected $headerValue;
/**
* #param string $xFrameOpt
*/
public function __construct($xFrameOpt = 'SAMEORIGIN')
{
//$this->headerValue = $xFrameOpt;
}
}
I think this will work!

Set content-type HTTP header for 404 page in TYPO3 9.5

I am making a webservice using TYPO3. Everything in the frontend should be JSON with HTTP header Content-Type: application/json, however I am unable to change the Content-Type header for the 404 page. Whatever I try, it's always Content-Type: text/html; charset=utf-8. How can I change this?
This is my basic page TypoScript configuration:
page = PAGE
page {
config {
disableAllHeaderCode = 1
disablePrefixComment = 1
xhtml_cleaning = 0
admPanel = 0
}
10 = USER
10 {
userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->run
extensionName = MyExt
pluginName = MyPlugin
vendorName = MyVendor
}
}
The extension uses TYPO3\CMS\Extbase\Mvc\View\JsonView.
I've already tried adding the header using config.additionalHeaders.10.header = Content-Type: application/json. I've also tried setting [FE][pageNotFound_handling] to USER_FUNCTION:... and setting the headers in PHP.
I found the solution myself. From TYPO3 9.5 the default page not found handling can be overridden in the site configuration:
errorHandling:
-
errorCode: 404
errorHandler: PHP
errorPhpClassFQCN: Vendor\MyExt\PageErrorHandler\PageNotFoundHandler
And in EXT:MyExt/Classes/PageErrorHandler/PageNotFoundHandler.php:
<?php
namespace Vendor\MyExt\PageErrorHandler;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Core\Error\PageErrorHandler\PageErrorHandlerInterface;
/**
* Class PageNotFoundHandler
*/
class PageNotFoundHandler implements PageErrorHandlerInterface
{
/**
* Handle page error
*
* #param ServerRequestInterface $request
* #param string $message
* #param array $reasons
* #return ResponseInterface
*/
public function handlePageError(ServerRequestInterface $request, string $message, array $reasons = []): ResponseInterface
{
$response = new Response(404, ['Content-Type' => 'application/json'], '{"error":"Not found"}');
return $response;
}
}

error in new version of sails and mongodb when want to insert data to table

Sending 500 ("Server Error") response:
ReferenceError: user is not defined
at Object.createUser [as user/createuser] (E:\angular2\server-sails\test\api\controllers\UserController.js:13:5)
datasrore.js
/**
* Datastores
* (sails.config.datastores)
*
* A set of datastore configurations which tell Sails where to fetch or save
* data when you execute built-in model methods like `.find()` and `.create()`.
*
* > This file is mainly useful for configuring your development database,
* > as well as any additional one-off databases used by individual models.
* > Ready to go live? Head towards `config/env/production.js`.
*
* For more information on configuring datastores, check out:
* https://sailsjs.com/config/datastores
*/
module.exports.datastores = {
/***************************************************************************
* *
* Your app's default datastore. *
* *
* Sails apps read and write to local disk by default, using a built-in *
* database adapter called `sails-disk`. This feature is purely for *
* convenience during development; since `sails-disk` is not designed for *
* use in a production environment. *
* *
* To use a different db _in development_, follow the directions below. *
* Otherwise, just leave the default datastore as-is, with no `adapter`. *
* *
* (For production configuration, see `config/env/production.js`.) *
* *
***************************************************************************/
default: {
/***************************************************************************
* *
* Want to use a different database during development? *
* *
* 1. Choose an adapter: *
* https://sailsjs.com/plugins/databases *
* *
* 2. Install it as a dependency of your Sails app. *
* (For example: npm install sails-mysql --save) *
* *
* 3. Then pass it in, along with a connection URL. *
* (See https://sailsjs.com/config/datastores for help.) *
* *
***************************************************************************/
// adapter: 'sails-mysql',
// url: 'mysql://user:password#host:port/database',
adapter: 'sails-mongo',
url: 'mongodb://localhost:27017/server',
},
};
model.js:
/**
* Default model settings
* (sails.config.models)
*
* Your default, project-wide model settings. Can also be overridden on a
* per-model basis by setting a top-level properties in the model definition.
*
* For details about all available model settings, see:
* https://sailsjs.com/config/models
*
* For more general background on Sails model settings, and how to configure
* them on a project-wide or per-model basis, see:
* https://sailsjs.com/docs/concepts/models-and-orm/model-settings
*/
module.exports.models = {
/***************************************************************************
* *
* Whether the `.create()` and `.update()` model methods should ignore *
* (and refuse to persist) unrecognized data-- i.e. properties other than *
* those explicitly defined by attributes in the model definition. *
* *
* To ease future maintenance of your code base, it is usually a good idea *
* to set this to `true`. *
* *
* > Note that `schema: false` is not supported by every database. *
* > For example, if you are using a SQL database, then relevant models *
* > are always effectively `schema: true`. And if no `schema` setting is *
* > provided whatsoever, the behavior is left up to the database adapter. *
* > *
* > For more info, see: *
* > https://sailsjs.com/docs/concepts/orm/model-settings#?schema *
* *
***************************************************************************/
// schema: true,
/***************************************************************************
* *
* How and whether Sails will attempt to automatically rebuild the *
* tables/collections/etc. in your schema. *
* *
* > Note that, when running in a production environment, this will be *
* > automatically set to `migrate: 'safe'`, no matter what you configure *
* > here. This is a failsafe to prevent Sails from accidentally running *
* > auto-migrations on your production database. *
* > *
* > For more info, see: *
* > https://sailsjs.com/docs/concepts/orm/model-settings#?migrate *
* *
***************************************************************************/
migrate: 'alter',
/***************************************************************************
* *
* Base attributes that are included in all of your models by default. *
* By convention, this is your primary key attribute (`id`), as well as two *
* other timestamp attributes for tracking when records were last created *
* or updated. *
* *
* > For more info, see: *
* > https://sailsjs.com/docs/concepts/orm/model-settings#?attributes *
* *
***************************************************************************/
attributes: {
createdAt: { type: 'number', autoCreatedAt: true, },
updatedAt: { type: 'number', autoUpdatedAt: true, },
// id: { type: 'number', autoIncrement: true, },
//--------------------------------------------------------------------------
// /\ Using MongoDB?
// || Replace `id` above with this instead:
//
// ```
id: { type: 'string', columnName: '_id' },
// ```
//
// Plus, don't forget to configure MongoDB as your default datastore:
// https://sailsjs.com/docs/tutorials/using-mongo-db
//--------------------------------------------------------------------------
},
/******************************************************************************
* *
* The set of DEKs (data encryption keys) for at-rest encryption. *
* i.e. when encrypting/decrypting data for attributes with `encrypt: true`. *
* *
* > The `default` DEK is used for all new encryptions, but multiple DEKs *
* > can be configured to allow for key rotation. In production, be sure to *
* > manage these keys like you would any other sensitive credential. *
* *
* > For more info, see: *
* > https://sailsjs.com/docs/concepts/orm/model-settings#?dataEncryptionKeys *
* *
******************************************************************************/
dataEncryptionKeys: {
default: '3X6yTfIErxEHDahmUxEdiRFg8rR8eU0/H8Z2AiGnNmU='
},
/***************************************************************************
* *
* Whether or not implicit records for associations should be cleaned up *
* automatically using the built-in polyfill. This is especially useful *
* during development with sails-disk. *
* *
* Depending on which databases you're using, you may want to disable this *
* polyfill in your production environment. *
* *
* (For production configuration, see `config/env/production.js`.) *
* *
***************************************************************************/
cascadeOnDestroy: true
};
userController.js
module.exports = {
createUser: (req, res) => {
var params = req.allParams();
console.log('hello world')
user.create({name: 'samira'}).exec((err, userCreated) => {
res.ok('userCreated');
})
}
};
user.js
/**
* User.js
*
* #description :: A model definition. Represents a database table/collection/etc.
* #docs :: https://sailsjs.com/docs/concepts/models-and-orm/models
*/
module.exports = {
attributes: {
name: {
type: 'string'
}
// ╔═╗╦═╗╦╔╦╗╦╔╦╗╦╦ ╦╔═╗╔═╗
// ╠═╝╠╦╝║║║║║ ║ ║╚╗╔╝║╣ ╚═╗
// ╩ ╩╚═╩╩ ╩╩ ╩ ╩ ╚╝ ╚═╝╚═╝
// ╔═╗╔╦╗╔╗ ╔═╗╔╦╗╔═╗
// ║╣ ║║║╠╩╗║╣ ║║╚═╗
// ╚═╝╩ ╩╚═╝╚═╝═╩╝╚═╝
// ╔═╗╔═╗╔═╗╔═╗╔═╗╦╔═╗╔╦╗╦╔═╗╔╗╔╔═╗
// ╠═╣╚═╗╚═╗║ ║║ ║╠═╣ ║ ║║ ║║║║╚═╗
// ╩ ╩╚═╝╚═╝╚═╝╚═╝╩╩ ╩ ╩ ╩╚═╝╝╚╝╚═╝
},
};
how can i solve this error and im beginner in sails, thank you advanced.
Capitalise User...
User.create({name: 'samir...

The class 'X' was not found in the chain configured namespaces ... when I try a multiple connection with doctrine

So I know this is another "class X not found in namespace" but I can't find an answer to my senario:
I have a class "temp" (pretty name) that looks like that :
namespace DbBccCrawlBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
*
* #ORM\Entity
* #ORM\Table(name="temp")
*
*/
class Temp
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
and the orm in config.yml :
orm:
auto_generate_proxy_classes: "%kernel.debug%"
entity_managers:
extranet:
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
bdb:
naming_strategy: doctrine.orm.naming_strategy.underscore
connection: bdb
mappings:
DbBccBdbBundle: ~
crawl:
naming_strategy: doctrine.orm.naming_strategy.underscore
connection: crawl
mappings:
DbBccCrawlBundle: ~
the weird thing is the error itself :
The class 'DbBccCrawlBundle\Entity\Temp' was not found in the chain configured namespaces FOS\UserBundle\Entity, AppBundle\Entity, DbBccBiproBundle\Entity
I don't know why it search in this bundle (it should be DbBccCrawlBundle\Entity instead)
I've been searching all this afternoon, if you've got some ideas, please let me know.

Flexibility of Symfony annotations

I use annotations for stand Symfony routes such as...
/**
* #Route("/", name="homepage")
*/
...quite happily, however I would have liked/expected some flexibility with the comments to be able to make each new route more visually identifiable - for example:
/********************************************************************
* #Route("/", name="homepage")
********************************************************************/
However, when I try this, I get an error:
No route found for "GET /"
Is there a way the *s (or #s can be extended such as above? (or is there a strong reason for not being able to do this?)
I don't know why you cannot use /************ but I think one of these would be good enough for your purpose. I think 1st one looks better, at least to me!
/**
* ***********************************
* #param Request $request
*
* #Route("")
* #Method({"POST"})
*
* #throws Exception
* ***********************************
*/
/** ***********************************
* #param Request $request
*
* #Route("")
* #Method({"POST"})
*
* #throws Exception
* ***********************************/
/** *******************************
* #param Request $request
*
* #Route("")
* #Method({"POST"})
*
* #throws Exception
** ******************************/