in Behat, Is there a way to test for a specific tag? - behat

I have a function in my FeatureContext.php that uses #AfterScenario to clean up fake database entries created during the test. I'd like to add a #debug tag to a particular scenario tell the function to NOT delete the entries created for that scenario if the tag is present.
/**
* Deletes the records created during the scenarios.
* #AfterScenario
*/
public function cleanDB(AfterScenarioScope $scope)
{
// if !#debug present
// delete files from database
// end if
}

#lauda's answer got me close and I figured out the rest.
I used the hasTag() function of Behat's scenario object.
/**
* Deletes the NCP records created during the scenarios.
* #AfterScenario
*/
public function cleanDB(AfterScenarioScope $scope)
{
// if the #debug tag is set, ignore
if (!$scope->getScenario()->hasTag("debug")) {
// delete records from database
}
}
If I decorate the scenario with #debug, I can test for that and change my functionality.
#debug
Scenario: do the thing
...

Related

Typo3 Repository update

I just start to develop a new extension, where one image is included.
If I using the add function from repository the image will be correct saved.
But when I using the edit controller function to change the image file und use than the repository update function, the old image will be not overwritten, but an additional image will be added.
I also tried to use the combination of remove/add instead of update. The result was the same. This I absolutly don't understand!
I am using Typo3 8.7.9. and have used the Extension-Builder, the version in the git.
Can anybody give me a hint, where the problem could be?
You need to remove first FAL object. You can do this like below.
in your controller file You create function for remove old image Fal object.
/**
* remove ImageObject
*
* #param \vendor\ExtensionKey\Domain\Model\Modelname $object
* #return void
*/
public function removeImageObject(\vendor\ExtensionKey\Domain\Model\Modelname $object) {
if(!empty($object->getImage())){
$resourceFactory = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Resource\\ResourceFactory');
$fileReferenceObject = $resourceFactory->getFileReferenceObject($events->getImage()->getUid());
$fileWasDeleted = $fileReferenceObject->getOriginalFile()->delete();
}
}
I understand, that I have first to delete the Filereference (sys_file_reference). From my Recipe class (\TYPO3\CMS\Extbase\DomainObject\AbstractEntity) I already get the filereference object. Therefore I should able to use it to delete it.
I have added the following function.
/**
* Deletes the recipePic Filereference
*
* #param \TYPO3\CMS\Extbase\Domain\Model\FileReference $recipePic
* #return void
*/
public function delRecipePic(\TYPO3\CMS\Extbase\Domain\Model\FileReference $recipePic)
{
$this->recipePic->getOriginalFile()->delete();
$this->recipePic->delete();
}
But both calls are not working. What I am doing wrong?

Yii2 Event not run after login

I created a Behavior which contains function. This function should be afterLogon of User (yii/web/User::EVENT_AFTER_LOGIN).
But this function never will be triggered unfortunatelly.
I have a Behaviour class for the user model:
class UserBehavior extends Behavior
{
/**
* #inheritdoc
* #param \yii\base\Component $owner
*/
public function attach($owner)
{
parent::attach($owner);
$owner->on(\yii\web\User::EVENT_AFTER_LOGIN, [$this, 'updateLoginInformation']);
}
/**
* Update login information data:
* - login ip address
* - login time
*/
public function updateLoginInformation()
{
/** #var \common\models\User $owner */
$owner = $this->owner;
$owner->logged_in_ip = Yii::$app->request->getUserIP();
$owner->logged_in_at = time();
$owner->save();
}
}
I declared the events and the attach too.
But this events never be run after login...
I attached this behavior to the user model:
/**
* #inheritdoc
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
UserBehavior::className()
];
}
If I know well the the EVENT_AFTER_LOGIN will be triggered automatically by the Yii framework, this is the reason why I do not trigger it again.
And I do not where is the problem, because the updageLoginInformatin never called.
I usually use any logic I want in a model inside the proper action that calls it (IE: actionLogin). But I like your approach.
I just made a test here and the correct way to call the event is something like this:
$user = \Yii::$app->user;
$user->on($user::EVENT_AFTER_LOGIN, [$this, 'updateLoginInformation']);
I didn't create a behavior class, I just added this lines in my init(), but the logic is probably the same as yours.

Tx_Extbase_Domain_Repository_FrontendUserRepository->findAll() not working in typo3 4.5.30?

I am trying to run a simple query off of the Tx_Extbase_Domain_Repository_FrontendUserRepository. I cannot get anything to work except findByUid(), not even findAll().
In my controller I have this code which seems to work:
/**
* #var Tx_Extbase_Domain_Repository_FrontendUserRepository
*/
protected $userRepository;
/**
* Inject the user repository
* #param Tx_Extbase_Domain_Repository_FrontendUserRepository $userRepository
* #return void */
public function injectFrontendUserRepository(Tx_Extbase_Domain_Repository_FrontendUserRepository $userRepository) {
$this->userRepository = $userRepository;
}
/**
* action create
*
* #param Tx_BpsCoupons_Domain_Model_Coupon $newCoupon
* #return void
*/
public function createAction(Tx_BpsCoupons_Domain_Model_Coupon $newCoupon) {
...... some code .....
$user = $this->userRepository->findByUid(($GLOBALS['TSFE']->fe_user->user[uid]));
$newCoupon->setCreator($user);
...... some code .....
}
but in another function I want to look up a user not by uid but by a fe_users column called vipnumber (an int column) so I tried
/**
* check to see if there is already a user with this vip number in the database
* #param string $vip
* #return bool
*/
public function isVipValid($vip) {
echo "<br/>" . __FUNCTION__ . __LINE__ . "<br/>";
echo "<br/>".$vip."<br/>";
//$ret = $this->userRepository->findByUid(15); //this works!! but
$query = $this->userRepository->createQuery();
$query->matching($query->equals('vip',$vip) );
$ret = $query->execute(); //no luck
.................
and neither does this
$ret = $this->userRepository->findAll();
How can one work but not the others? In my setup I already put
config.tx_extbase.persistence.classes.Tx_Extbase_Domain_Model_FrontendUser.mapping.recordType >
which seems to be necessary for the fiondByUid to work, is i t preventing the other from working?
I am using typo3 v 4.5.30 with extbase 1.3
Thanks
If $this->userRepository->findByUid(15); works, there is no reason why $this->userRepository->findAll(); should not. However $this->userRepository->findAll(); returns not a single Object but a collection of all objects, so you have to iterate over them.
If you add a column to the fe_users, you have to add it to TCA and to your extbase model (you need a getter and a setter), too! After that you can call findByProperty($property) in your repository. In your case that would be
$user = $this->userRepository->findByVipnumber($vip);
This will return all UserObjects that have $vip set as their Vipnumber. If you just want to check if that $vip is already in use, you can call
$user = $this->userRepository->countByVipnumber($vip);
instead. Which obviously returns the number of Users that have this $vip;
You never use $query = $this->createQuery(); outside your Repository.
To add the property to the fronenduser Model you create your own model Classes/Domain/Model/FronendUser.php:
class Tx_MyExt_Domain_Model_FrontendUser extends Tx_Extbase_Domain_Model_FrontendUser {
/**
* #var string/integer
*/
protected $vipnumber;
}
Add a getter and a setter. Now you create your own FrontendUserRepository and extend the extbase one like you did with the model. You use this repository in your Controller. Now you're almost there: Tell Extbase via typoscript, that your model is using the fe_users table and everything should work:
config.tx_extbase {
persistence{
Tx_MyExt_Domain_Model_FrontendUser{
mapping {
tableName = fe_users
}
}
}
}
To disable storagePids in your repository in general, you can use this code inside your repository:
/**
* sets query settings repository-wide
*
* #return void
*/
public function initializeObject() {
$querySettings = $this->objectManager->create('Tx_Extbase_Persistence_Typo3QuerySettings');
$querySettings->setRespectStoragePage(FALSE);
$this->setDefaultQuerySettings($querySettings);
}
After this, your Querys will work for all PIDs.
I didn't have the opportunity to work with frontend users yet, so I don't know if the following applies in this case:
In a custom table I stumbled uppon the fact, that extbase repositories automatically have a look at the pids stored in each entry and check it against a set storage pid (possibly also the current pid if not set). Searching for a uid usually means you have a specific dataset in mind so automatic checks for other values could logically be ignored which would support your experiences. I'd try to set the storage pid for your extension to the place the frontend users are stored in ts-setup:
plugin.[replace_with_extkey].persistence.storagePid = [replace_with_pid]

Yii Framework: CModel replicating CActiveRecord functionality with WebServices

Has anyone tried or found an example of a class derived from CModel that replicates CActiveRecord functionality with WebServices instead of database connection???
If done with RESTFULL WebServices it would be great. If data is transmitted JSON encoded, wonderful!!...
I'd appretiate your help. Thanks.
I spend a lot of time looking for that as well, I came across this Yii extension on Github:
https://github.com/Haensel/ActiveResource
It allows you to have exactly what you are looking for, the readme isn't updated with the changes reflected in changes.md, so I recommend you read through this document as well.
EActiveResource for Yii
...is an extension for the Yii PHP framework allowing the user to create models that use RESTful services as persistent storage.
The implementation is inspired by Yii's CActiveRecord class and the Ruby on Rails implementation of ActiveResource (http://api.rubyonrails.org/classes/ActiveResource/Base.html).
HINT:
CAUTION: THIS IS STILL AN ALPHA RELEASE!
This project started as a draft and is still under development, so as long is there is no 1.0 release you may experience changes that could break your code. Look at the CHANGES.md file for further information
As there are thousands of different REST services out there that use a thousand different approaches it can be tricky to debug errors. Because of that I added extensive
tracing to all major functions, so you should always be able to see every request, which method it used and how the service responded. Just enable the tracing functionality of Yii
and look for the category "ext.EActiveResource"
INSTALL:
Add the extension to Yii by placing it in your application's extension folder (for example '/protected/extensions')
Edit your applications main.php config file and add 'application.extensions.EActiveResource.*' to your import definitions
Add the configuration for your resources to the main config
'activeresource'=>array(
'class'=>'EActiveResourceConnection',
'site'=>'http://api.aRESTservice.com',
'contentType'=>'application/json',
'acceptType'=>'application/json',
)),
'queryCacheId'=>'SomeCacheComponent')
4.) Now create a class extending EActiveResource like this (don't forget the model() function!):
QUICK OVERVIEW:
class Person extends EActiveResource
{
/* The id that uniquely identifies a person. This attribute is not defined as a property
* because we don't want to send it back to the service like a name, surname or gender etc.
*/
public $id;
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function rest()
{
return CMap::mergeArray(
parent::rest(),
array(
'resource'=>'people',
)
);
}
/* Let's define some properties and their datatypes
public function properties()
{
return array(
'name'=>array('type'=>'string'),
'surname'=>array('type'=>'string'),
'gender'=>array('type'=>'string'),
'age'=>array('type'=>'integer'),
'married'=>array('type'=>'boolean'),
'salary'=>array('type'=>'double'),
);
}
/* Define rules as usual */
public function rules()
{
return array(
array('name,surname,gender,age,married,salary','safe'),
array('age','numerical','integerOnly'=>true),
array('married','boolean'),
array('salary','numerical')
);
}
/* Add some custom labels for forms etc. */
public function attributeLabels()
{
return array(
'name'=>'First name',
'surname'=>'Last name',
'salary'=>'Your monthly salary',
);
}
}
Usage:
/* sends GET to http://api.example.com/person/1 and populates a single Person model*/
$person=Person::model()->findById(1);
/* sends GET to http://api.example.com/person and populates Person models with the response */
$persons=Person::model()->findAll();
/* create a resource
$person=new Person;
$person->name='A name';
$person->age=21;
$person->save(); //New resource, send POST request. Returns false if the model doesn't validate
/* Updating a resource (sending a PUT request)
$person=Person::model()->findById(1);
$person->name='Another name';
$person->save(); //Not at new resource, update it. Returns false if the model doesn't validate
//or short version
Person::model()->updateById(1,array('name'=>'Another name'));
/* DELETE a resource
$person=Person::model()->findById(1);
$person->destroy(); //DELETE to http://api.example.com/person/1
//or short version
Person::model()->deleteById(1);
Hope this helps you

Yii: shared password for member's area

What would be the best way to approach setting up a shared password protected area in Yii?
I am looking to have a view of a Group model, that can be accessed by a shared password created by the owner of that group - group members shouldn't have to log in, purely enter this passcode.
Should this still be done with Yii's built in auth tools? - or is there a simpler solution, bearing in mind that someone might want to access several groups.
You can do this using standard session mechanism built into PHP. When someone tries to view password-protected area, check the session variable, if the user haven't entered password yet then redirect him to some page with a password form (you can do the check using controller filters for example).
After the form is submitted, check correctness of password and if everything is ok, write it into the session. You can differentiate session keys by group ids.
You can use Yii filter capabilities to fire code before executing a controller action, and prevent actions that you do not want to allow.
I would create a common controller for all your group pages, and inherit other controller from this one if need to.
In the filter I would setup code to check/prompt for the password, and keep that in session.
For example we have a filter setup to detect if the user has accepted our revised Terms and Conditions. The filter will detect and will prevent access to the controller until the user doesn't confirm it.
class TocConfirmFilter extends CFilter {
/**
* Initializes the filter.
* This method is invoked after the filter properties are initialized
* and before {#link preFilter} is called.
* You may override this method to include some initialization logic.
*/
public function init() {
}
/**
* Performs the pre-action filtering.
* #param CFilterChain the filter chain that the filter is on.
* #return boolean whether the filtering process should continue and the action
* should be executed.
*/
protected function preFilter($filterChain) {
// do not perform this filter on this action
if ($filterChain->action->controller->id . '/' . $filterChain->action->id == 'public/onePublicPage') {
return true;
}
if (isset(Yii::app()->user->id)) {
$user = user::model()->findbyPk(Yii::app()->user->id);
if ($user === null)
throw new CHttpException(404, 'The requested user does not exist.');
if ($user->tocconfirmed == 0) {
Yii::app()->getRequest()->redirect(Yii::app()->createAbsoluteUrl('authorize/confirm'));
return false;
}
}
return true;
}
/**
* Performs the post-action filtering.
* #param CFilterChain the filter chain that the filter is on.
*/
protected function postFilter($filterChain) {
}
}