/** * @When /^I make a request to "([^"]*)" with the following:$/ */ public function iMakeARequestToWithTheFollowing($url, TableNode $table) { $client = new Client(); $request = $client->post($this->locatePath($url), array(), $table->getRowsHash()); $response = $request->send(); $this->currentResponse = $response; }
/** * @Given /^the external "([^"]*)" user:$/ */ public function createExternalUser($service, TableNode $table) { $external_user = new ExternalUser(); $external_user->setService(strtolower($service)); $em = $this->getEntityManager(); foreach ($table->getRowsHash() as $field => $value) { switch ($field) { case 'name': $external_user->setName($value); break; case 'id': $external_user->setRemoteId($value); break; case 'email': $external_user->setEmail($value); break; case 'username': $external_user->setUsername($value); break; case 'picture': $external_user->setProfilePictureUrl($value); break; case 'user': $user = $em->getRepository('ActsCamdramSecurityBundle:User')->findOneByEmail($value); $external_user->setUser($user); break; } } $em->persist($external_user); $em->flush(); }
/** * @param string $code * @param TableNode $table * * @Given /^the following job "([^"]*)" configuration:$/ */ public function theFollowingJobConfiguration($code, TableNode $table) { $jobInstance = $this->getFixturesContext()->getJobInstance($code); $configuration = $jobInstance->getRawParameters(); foreach ($table->getRowsHash() as $property => $value) { $value = $this->replacePlaceholders($value); if (in_array($value, ['yes', 'no'])) { $value = 'yes' === $value; } if ('filters' === $property) { $value = json_decode($value, true); } $configuration[$property] = $value; } /** @var JobRegistry $jobRegistry */ $jobRegistry = $this->getMainContext()->getContainer()->get('akeneo_batch.job.job_registry'); $job = $jobRegistry->get($jobInstance->getJobName()); /** @var JobParametersFactory $jobParamsFactory */ $jobParamsFactory = $this->getMainContext()->getContainer()->get('akeneo_batch.job_parameters_factory'); $jobParams = $jobParamsFactory->create($job, $configuration); /** @var JobParametersValidator $jobParamsValidator */ $jobParamsValidator = $this->getMainContext()->getContainer()->get('akeneo_batch.job.job_parameters_validator'); $violations = $jobParamsValidator->validate($job, $jobParams, ['Default']); if ($violations->count() > 0) { $messages = []; /** @var ConstraintViolationInterface $violation */ foreach ($violations as $violation) { $messages[] = $violation->getMessage(); } throw new \InvalidArgumentException(sprintf('The parameters "%s" are not valid for the job "%s" due to violations "%s"', print_r($jobParams->all(), true), $job->getName(), implode(', ', $messages))); } $jobInstance->setRawParameters($jobParams->all()); $saver = $this->getMainContext()->getContainer()->get('akeneo_batch.saver.job_instance'); $saver->save($jobInstance); }
/** * Adds a question to the questionnaire with the provided data. * * @Given /^I add a "([^"]*)" question and I fill the form with:$/ * * @param string $questiontype The question type by text name to enter. * @param TableNode $fielddata */ public function i_add_a_question_and_i_fill_the_form_with($questiontype, TableNode $fielddata) { $validtypes = array('----- Page Break -----', 'Check Boxes', 'Date', 'Dropdown Box', 'Essay Box', 'Label', 'Numeric', 'Radio Buttons', 'Rate (scale 1..5)', 'Text Box', 'Yes/No'); if (!in_array($questiontype, $validtypes)) { throw new ExpectationException('Invalid question type specified.', $this->getSession()); } // We get option choices as CSV strings. If we have this, modify it for use in // multiline data. $rows = $fielddata->getRows(); $hashrows = $fielddata->getRowsHash(); $options = array(); if (isset($hashrows['Possible answers'])) { $options = explode(',', $hashrows['Possible answers']); $rownum = -1; // Find the row that contained multiline data and add line breaks. Rows are two item arrays where the // first is an identifier and the second is the value. foreach ($rows as $key => $row) { if ($row[0] == 'Possible answers') { $row[1] = str_replace(',', "\n", $row[1]); $rows[$key] = $row; break; } } $fielddata = new TableNode($rows); } $this->execute('behat_forms::i_set_the_field_to', array('id_type_id', $questiontype)); $this->execute('behat_forms::press_button', 'Add selected question type'); $this->execute('behat_forms::i_set_the_following_fields_to_these_values', $fielddata); $this->execute('behat_forms::press_button', 'Save changes'); }
/** * Assert no records from MakeDo request. * * @Then I should not have :type records matching the parameters: */ public function assertNoRetrievedRecords($type, TableNode $parameters) { // Retrieve records. $this->records = $this->getMakeDo()->getRecords($type, $parameters->getRowsHash()); if (!empty($this->records)) { throw new \Exception('There were records that matched the given parameters.'); } }
/** * Creates a dataformfield entrystate instance. * * @Given /^the following dataformfield entrystate exists:$/ * @param TableNode $data */ public function the_following_dataformfield_entrystate_exists(TableNode $data) { global $DB; $datahash = $data->getRowsHash(); // Get the dataform id. $idnumber = $datahash['dataform']; if (!($dataformid = $DB->get_field('course_modules', 'instance', array('idnumber' => $idnumber)))) { throw new Exception('The specified dataform with idnumber "' . $idnumber . '" does not exist'); } $df = new \mod_dataform_dataform($dataformid); // Get the field or create it if does not exist. $params = array('dataid' => $dataformid, 'name' => $datahash['name']); if (!($instance = $DB->get_record('dataform_fields', $params))) { $field = $df->field_manager->add_field('entrystate'); } else { $field = $df->field_manager->get_field($instance); } $field->name = $datahash['name']; // Set config (param1). $config = array(); // Must have states. if (!empty($datahash['states'])) { $config['states'] = implode("\n", explode('#', trim($datahash['states']))); // Transitions. $transitions = array(); $i = 0; while (isset($datahash["to{$i}"])) { if ($datahash["to{$i}"] === '') { $i++; continue; } $from = "from{$i}"; $to = "to{$i}"; $permission = "permission{$i}"; $notification = "notification{$i}"; $trans = array(); $trans['from'] = $datahash[$from]; $trans['to'] = $datahash[$to]; if (!empty($datahash[$permission])) { $trans['permission'] = $datahash[$permission]; } if (!empty($datahash[$notification])) { $trans['notification'] = $datahash[$notification]; } if ($trans) { $transitions[] = $trans; } $i++; } if ($transitions) { $config['transitions'] = $transitions; } } // Set param1. $field->param1 = $config ? base64_encode(serialize($config)) : null; $field->update($field->data); }
/** * @Then the car with the id :id should have property :propertyName with the following values: */ public function theCarWithTheIdShouldHavePropertyWithTheFollowingValues($id, $propertyName, TableNode $values) { $car = $this->repository->find($id); $getter = 'get' . ucfirst(strtolower($propertyName)); $data = $car->{$getter}(); foreach ($values->getRowsHash() as $key => $value) { assertTrue(isset($data[$key])); assertEquals($value, $data[$key]); } }
/** * Sets the specified global variable. A table with | variable_name | value | is expected. * * @Given /^I set global variables with values:$/ * @param TableNode $table */ public function i_set_global_variables_with_values(TableNode $table) { global $CFG; if (!($data = $table->getRowsHash())) { return; } foreach ($data as $label => $value) { ${$label} = $value; print "\nFrom table I've set \${$label} = {${$label}}"; } }
/** * Fills the respective fields of a choice. * * @Given /^I set the values of the choice with the id (?P<choice_id>-?\d+) to:$/ * * @param integer $choiceid id of the choice * @param TableNode $choicedata with data for filling the choice */ public function i_Set_The_Values_Of_The_Choice_With_The_Id_To($choiceid, TableNode $choicedata) { $result = new TableNode(); $choicedatahash = $choicedata->getRowsHash(); // The action depends on the field type. $steps = array(); foreach ($choicedatahash as $locator => $value) { array_push($steps, new Given("I set the field \"id_choices_{$choiceid}_{$locator}\" to \"{$value}\"")); } return $steps; }
/** * @example * Given user should have an access to the following pages * | page/url | * * @param string $not * @param TableNode $paths * * @throws \Exception * * @Given /^user should(| not) have an access to the following pages:$/ */ public function checkUserAccessToPages($not, TableNode $paths) { $code = empty($not) ? 200 : 403; $fails = []; foreach (array_keys($paths->getRowsHash()) as $path) { if (!$this->assertStatusCode($path, $code)) { $fails[] = $path; } } if (!empty($fails)) { throw new \Exception(sprintf('The following paths: "%s" are %s accessible!', implode(', ', $fails), $not ? '' : 'not')); } }
/** * @Given /^supplier "([^"]*)" exists with product:$/ */ public function supplierExistsWithProduct($name, TableNode $table) { $data = $table->getRowsHash(); $supplier = $this->supplierExists($name); $product = new Product($data['Name'], (double) $data['Price'], $supplier); if (isset($data['Description'])) { $product->setDescription($data['Description']); } var_dump($product->getPrice()); $this->getEntityManager()->persist($product); $this->getEntityManager()->flush(); $this->getParameterBag()->set('product', $product); }
/** * @Then /^The config should contain the following values:$/ * * @param TableNode $table * * @throws \Exception */ public function configContainsValues(TableNode $table) { $configFile = $this->kernel->getRootDir() . '/config/parameters.yml'; $yaml = Yaml::parse(file_get_contents($configFile))['parameters']; foreach ($table->getRowsHash() as $config => $value) { if (!array_key_exists($config, $yaml)) { throw new \Exception(sprintf('Key "%s" does not exist in config file', $config)); } if ($yaml[$config] != $value) { throw new \Exception(sprintf('Config "%s" does not match expected value. Expected "%s", got "%s"', $config, $value, $yaml[$config])); } } }
/** * @example * I check that email for "*****@*****.**" contains: * | subject | New email letter | * | body | The body of letter | * I also check that email contains: * | from | admin@example.com | * * @param string $to * Recipient. * @param TableNode $values * Left column - is a header key, right - value. * * @throws \RuntimeException * When any message was not sent. * @throws \InvalidArgumentException * @throws \RuntimeException * * @Given /^(?:|I )check that email for "([^"]*)" contains:$/ */ public function contains($to, TableNode $values) { $rows = $values->getRowsHash(); foreach ($this->getEmailMessages($to) as $message) { foreach ($rows as $field => $value) { if (empty($message[$field])) { throw new \InvalidArgumentException(sprintf('Message does not contain "%s" header.', $field)); } if (strpos($message[$field], $value) === false) { throw new \RuntimeException(sprintf('Value of "%s" does not contain "%s".', $field, $value)); } } } }
/** * @When /^getting sharees for$/ * @param \Behat\Gherkin\Node\TableNode $body */ public function whenGettingShareesFor($body) { $url = '/apps/files_sharing/api/v1/sharees'; if ($body instanceof \Behat\Gherkin\Node\TableNode) { $parameters = []; foreach ($body->getRowsHash() as $key => $value) { $parameters[] = $key . '=' . $value; } if (!empty($parameters)) { $url .= '?' . implode('&', $parameters); } } $this->sendingTo('GET', $url); }
/** * Creates a Dataform instance. * * @Given /^the following dataformfield time exists:$/ * @param TableNode $data */ public function the_following_dataformfield_time_exists(TableNode $data) { global $DB; $datahash = $data->getRowsHash(); // Get the dataform id. $idnumber = $datahash['dataform']; if (!($dataformid = $DB->get_field('course_modules', 'instance', array('idnumber' => $idnumber)))) { throw new Exception('The specified dataform with idnumber "' . $idnumber . '" does not exist'); } $df = new \mod_dataform_dataform($dataformid); // Get the field or create it if does not exist. $params = array('dataid' => $dataformid, 'name' => $datahash['name']); if (!($instance = $DB->get_record('dataform_fields', $params))) { $field = $df->field_manager->add_field('dataformview'); } else { $field = $df->field_manager->get_field($instance); } // Date only. $field->param1 = null; if (!empty($datahash['date only'])) { $field->param1 = 1; } // Masked. $field->param5 = null; if (!empty($datahash['masked'])) { $field->param5 = 1; } // Start year. $field->param2 = null; if (!empty($datahash['start year'])) { $field->param2 = $datahash['start year']; } // stop year. $field->param3 = null; if (!empty($datahash['stop year'])) { $field->param3 = $datahash['stop year']; } // Display format. $field->param4 = null; if (!empty($datahash['display format'])) { $field->param4 = $datahash['display format']; } // Default content. $field->default = null; if (!empty($datahash['default content'])) { $field->default = $datahash['default content']; } $field->update($field->data); }
/** * @Given /^([^""]*) with following data should be created:$/ */ public function objectWithFollowingDataShouldBeCreated($type, TableNode $table) { $data = $table->getRowsHash(); $type = str_replace(' ', '_', trim($type)); $object = $this->findOneByName($type, $data['name']); foreach ($data as $property => $value) { $objectValue = $object->{'get' . ucfirst($property)}(); if (is_array($objectValue)) { $objectValue = implode(',', $objectValue); } if ($objectValue !== $value) { throw new \Exception(sprintf('%s object::%s has "%s" value but "%s" expected', $type, $property, $objectValue, is_array($value) ? implode(',', $value) : $value)); } } }
/** * @param string $code * @param TableNode $table * * @Given /^the following job "([^"]*)" configuration:$/ */ public function theFollowingJobConfiguration($code, TableNode $table) { $jobInstance = $this->getFixturesContext()->getJobInstance($code); $configuration = $jobInstance->getRawConfiguration(); foreach ($table->getRowsHash() as $property => $value) { $value = $this->replacePlaceholders($value); if (in_array($value, ['yes', 'no'])) { $value = 'yes' === $value; } $configuration[$property] = $value; } $jobInstance->setRawConfiguration($configuration); // TODO use a Saver $this->getFixturesContext()->flush(); }
/** * @Given I should receive email: */ public function iShouldReceiveEmail(TableNode $table) { $files = $this->getSpoolFiles(); $files->sortByModifiedTime(); if ($files->count() < 1) { throw new \Exception("There should be at least 1 email"); } $expected = $table->getRowsHash(); if (false === ($email = $this->fetchEmail($expected['subject']))) { throw new \Exception(sprintf('There is no email with "%s" subject', $expected['subject'])); } expect(key($email->getFrom()))->toBe($expected['from']); expect(key($email->getTo()))->toBe($expected['to']); expect(key($email->getReplyTo()))->toBe($expected['replay_to']); }
/** * Fills a moodle form with field/value data. * * @Given /^I fill the moodle form with:$/ * @throws ElementNotFoundException Thrown by behat_base::find * @param TableNode $data */ public function i_fill_the_moodle_form_with(TableNode $data) { // Expand all fields in case we have. $this->expand_all_fields(); $datahash = $data->getRowsHash(); // The action depends on the field type. foreach ($datahash as $locator => $value) { // Getting the node element pointed by the label. $fieldnode = $this->find_field($locator); // Gets the field type from a parent node. $field = behat_field_manager::get_form_field($fieldnode, $this->getSession()); // Delegates to the field class. $field->set_value($value); } }
/** * Sends HTTP request to specific URL with field values from Table. * * @param string $method request method * @param string $url relative url * @param TableNode $post table of post values * * @When /^(?:I )?send a ([A-Z]+) request to "([^"]+)" with values:$/ */ public function iSendARequestWithValues($method, $url, TableNode $post) { $url = $this->prepareUrl($url); $this->prepareJsonContext(); $fields = array(); foreach ($post->getRowsHash() as $key => $val) { $fields[$key] = $this->replacePlaceHolder($val); } $bodyOption = array('body' => json_encode($fields)); $this->request = $this->getClient()->createRequest($method, $url, $bodyOption); if (!empty($this->headers)) { $this->request->addHeaders($this->headers); } $this->sendRequest(); }
public function i_set_the_following_administration_settings_values(TableNode $table) { if (!($data = $table->getRowsHash())) { return; } foreach ($data as $label => $value) { // We expect admin block to be visible, otherwise go to homepage. if (!$this->getSession()->getPage()->find('css', '.block_settings')) { $this->getSession()->visit($this->locate_path('/')); $this->wait(self::TIMEOUT * 1000, self::PAGE_READY_JS); } // Search by label. $searchbox = $this->find_field(get_string('searchinsettings', 'admin')); $searchbox->setValue($label); $submitsearch = $this->find('css', 'form.adminsearchform input[type=submit]'); $submitsearch->press(); $this->wait(self::TIMEOUT * 1000, self::PAGE_READY_JS); // Admin settings does not use the same DOM structure than other moodle forms // but we also need to use lib/behat/form_field/* to deal with the different moodle form elements. $exception = new ElementNotFoundException($this->getSession(), '"' . $label . '" administration setting '); // The argument should be converted to an xpath literal. $label = behat_context_helper::escape($label); // Single element settings. try { $fieldxpath = "//*[self::input | self::textarea | self::select]" . "[not(./@type = 'submit' or ./@type = 'image' or ./@type = 'hidden')]" . "[@id=//label[contains(normalize-space(.), {$label})]/@for or " . "@id=//span[contains(normalize-space(.), {$label})]/preceding-sibling::label[1]/@for]"; $fieldnode = $this->find('xpath', $fieldxpath, $exception); $formfieldtypenode = $this->find('xpath', $fieldxpath . "/ancestor::div[contains(concat(' ', @class, ' '), ' form-setting ')]" . "/child::div[contains(concat(' ', @class, ' '), ' form-')]/child::*/parent::div"); } catch (ElementNotFoundException $e) { // Multi element settings, interacting only the first one. $fieldxpath = "//*[label[contains(., {$label})]|span[contains(., {$label})]]" . "/ancestor::div[contains(concat(' ', normalize-space(@class), ' '), ' form-item ')]" . "/descendant::div[contains(concat(' ', @class, ' '), ' form-group ')]" . "/descendant::*[self::input | self::textarea | self::select]" . "[not(./@type = 'submit' or ./@type = 'image' or ./@type = 'hidden')]"; $fieldnode = $this->find('xpath', $fieldxpath); // It is the same one that contains the type. $formfieldtypenode = $fieldnode; } // Getting the class which contains the field type. $classes = explode(' ', $formfieldtypenode->getAttribute('class')); $type = false; foreach ($classes as $class) { if (substr($class, 0, 5) == 'form-') { $type = substr($class, 5); } } // Instantiating the appropiate field type. $field = behat_field_manager::get_field_instance($type, $fieldnode, $this->getSession()); $field->set_value($value); $this->find_button(get_string('savechanges'))->press(); } }
/** * @Given /^there is prototype "([^""]*)" with following configuration:$/ */ public function thereIsPrototypeWithFollowingConfiguration($name, TableNode $table) { $manager = $this->getEntityManager(); $repository = $this->getRepository('product_prototype'); $prototype = $repository->createNew(); $prototype->setName($name); $data = $table->getRowsHash(); foreach (explode(',', $data['options']) as $optionName) { $prototype->addOption($this->findOneByName('product_option', trim($optionName))); } foreach (explode(',', $data['attributes']) as $attributeName) { $prototype->addAttribute($this->findOneByName('product_attribute', trim($attributeName))); } $manager->persist($prototype); $manager->flush(); }
public function testTableFromArrayCreation() { $table1 = new TableNode(); $table1->addRow(array('username', 'password')); $table1->addRow(array('everzet', 'qwerty')); $table1->addRow(array('antono', 'pa$sword')); $table2 = new TableNode(<<<TABLE | username | password | | everzet | qwerty | | antono | pa\$sword| TABLE ); $this->assertEquals($table2->getRows(), $table1->getRows()); $this->assertEquals(array(array('username' => 'everzet', 'password' => 'qwerty'), array('username' => 'antono', 'password' => 'pa$sword')), $table1->getHash()); $this->assertEquals(array('username' => 'password', 'everzet' => 'qwerty', 'antono' => 'pa$sword'), $table2->getRowsHash()); }
/** * @param string $identifier * @param TableNode $table * * @throws \Exception * * @Given /^the product "([^"]*)" should not have the following values?:$/ */ public function theProductShouldNotHaveTheFollowingValues($identifier, TableNode $table) { $this->getMainContext()->getSubcontext('hook')->clearUOW(); $product = $this->getFixturesContext()->getEntity('Product', $identifier); foreach ($table->getRowsHash() as $rawCode => $value) { $infos = $this->getFieldExtractor()->extractColumnInfo($rawCode); $attribute = $infos['attribute']; $attributeCode = $attribute->getCode(); $localeCode = $infos['locale_code']; $scopeCode = $infos['scope_code']; $productValue = $product->getValue($attributeCode, $localeCode, $scopeCode); if (null !== $productValue) { throw new \Exception(sprintf('Product value for product "%s" exists', $identifier)); } } }
protected function upload_file_to_filemanager($filepath, $filemanagerelement, TableNode $data, $overwriteaction = false) { global $CFG; $filemanagernode = $this->get_filepicker_node($filemanagerelement); // Opening the select repository window and selecting the upload repository. $this->open_add_file_window($filemanagernode, get_string('pluginname', 'repository_upload')); // Ensure all the form is ready. $noformexception = new ExpectationException('The upload file form is not ready', $this->getSession()); $this->find('xpath', "//div[contains(concat(' ', normalize-space(@class), ' '), ' file-picker ')]" . "[contains(concat(' ', normalize-space(@class), ' '), ' repository_upload ')]" . "/descendant::div[contains(concat(' ', normalize-space(@class), ' '), ' fp-content ')]" . "/descendant::div[contains(concat(' ', normalize-space(@class), ' '), ' fp-upload-form ')]" . "/descendant::form", $noformexception); // After this we have the elements we want to interact with. // Form elements to interact with. $file = $this->find_file('repo_upload_file'); // Attaching specified file to the node. // Replace 'admin/' if it is in start of path with $CFG->admin . if (substr($filepath, 0, 6) === 'admin/') { $filepath = $CFG->dirroot . DIRECTORY_SEPARATOR . $CFG->admin . DIRECTORY_SEPARATOR . substr($filepath, 6); } $filepath = str_replace('/', DIRECTORY_SEPARATOR, $filepath); if (!is_readable($filepath)) { $filepath = $CFG->dirroot . DIRECTORY_SEPARATOR . $filepath; if (!is_readable($filepath)) { throw new ExpectationException('The file to be uploaded does not exist.', $this->getSession()); } } $file->attachFile($filepath); // Fill the form in Upload window. $datahash = $data->getRowsHash(); // The action depends on the field type. foreach ($datahash as $locator => $value) { $field = behat_field_manager::get_form_field_from_label($locator, $this); // Delegates to the field class. $field->set_value($value); } // Submit the file. $submit = $this->find_button(get_string('upload', 'repository')); $submit->press(); // We wait for all the JS to finish as it is performing an action. $this->getSession()->wait(self::TIMEOUT, self::PAGE_READY_JS); if ($overwriteaction !== false) { $overwritebutton = $this->find_button($overwriteaction); $this->ensure_node_is_visible($overwritebutton); $overwritebutton->click(); // We wait for all the JS to finish. $this->getSession()->wait(self::TIMEOUT, self::PAGE_READY_JS); } }
/** * @Given /^([^""]*) with following data should be created:$/ */ public function objectWithFollowingDataShouldBeCreated($type, TableNode $table) { $accessor = new PropertyAccessor(); $data = $table->getRowsHash(); $type = str_replace(' ', '_', trim($type)); $object = $this->waitFor(function () use($type, $data) { return $this->findOneByName($type, $data['name']); }); foreach ($data as $property => $value) { $objectValue = $accessor->getValue($object, $property); if (is_array($objectValue)) { $objectValue = implode(',', $objectValue); } if ($objectValue !== $value) { throw new \Exception(sprintf('%s object::%s has "%s" value but "%s" expected', $type, $property, $objectValue, is_array($value) ? implode(',', $value) : $value)); } } }
/** * Adds a page to the current ouwiki with the provided data. You should be in the main view page.. * * @Given /^I add a ouwiki page with the following data:$/ * @param TableNode $data */ public function i_add_a_ouwiki_page_with_the_following_data(TableNode $data) { $steps = array(); $datahash = $data->getRowsHash(); $i = 0; // The action depends on the field type. foreach ($datahash as $locator => $value) { $steps[] = new Given('I set the field "' . $locator . '" to "' . $value . '"'); if ($i == 0) { $steps[] = new Given('I press "' . get_string('create', 'ouwiki') . '"'); } else { continue; } $i++; } $steps[] = new Given('I press "' . get_string('savechanges') . '"'); return $steps; }
/** * @param TableNode $table * * * @Given /^the following CSV configuration to import:$/ */ public function theFollowingCSVToImport(TableNode $table) { $delimiter = ';'; $data = $table->getRowsHash(); $columns = implode($delimiter, array_keys($data)); $rows = []; foreach ($data as $values) { foreach ($values as $index => $value) { $value = in_array($value, ['yes', 'no']) ? (int) $value === 'yes' : $value; $rows[$index][] = $value; } } $rows = array_map(function ($row) use($delimiter) { return implode($delimiter, $row); }, $rows); array_unshift($rows, $columns); return $this->theFollowingFileToImport('csv', new PyStringNode(implode("\n", $rows))); }
/** * @Given /^there is archetype "([^""]*)" with following configuration:$/ */ public function thereIsArchetypeWithFollowingConfiguration($name, TableNode $table) { $manager = $this->getEntityManager(); $factory = $this->getFactory('product_archetype'); $data = $table->getRowsHash(); $archetype = $factory->createNew(); $archetype->setName($name); $archetype->setCode($data['code']); foreach (explode(',', $data['options']) as $optionName) { $option = $this->findOneBy('product_option', ['code' => trim($optionName)]); $archetype->addOption($option); } foreach (explode(',', $data['attributes']) as $attributeName) { $archetype->addAttribute($this->findOneByName('product_attribute', trim($attributeName))); } $manager->persist($archetype); $manager->flush(); }
/** * Creates a new course with the provided table data matching course settings names with the desired values. * * @Given /^I create a course with:$/ * @param TableNode $table The course data * @return Given[] */ public function i_create_a_course_with(TableNode $table) { $steps = array(new Given('I go to the courses management page'), new Given('I should see the "' . get_string('categories') . '" management page'), new Given('I click on category "' . get_string('miscellaneous') . '" in the management interface'), new Given('I should see the "' . get_string('categoriesandcoures') . '" management page'), new Given('I click on "' . get_string('createnewcourse') . '" "link" in the "#course-listing" "css_element"')); // If the course format is one of the fields we change how we // fill the form as we need to wait for the form to be set. $rowshash = $table->getRowsHash(); $formatfieldrefs = array(get_string('format'), 'format', 'id_format'); foreach ($formatfieldrefs as $fieldref) { if (!empty($rowshash[$fieldref])) { $formatfield = $fieldref; } } // Setting the format separately. if (!empty($formatfield)) { // Removing the format field from the TableNode. $rows = $table->getRows(); $formatvalue = $rowshash[$formatfield]; foreach ($rows as $key => $row) { if ($row[0] == $formatfield) { unset($rows[$key]); } } $table->setRows($rows); // Adding a forced wait until editors are loaded as otherwise selenium sometimes tries clicks on the // format field when the editor is being rendered and the click misses the field coordinates. $steps[] = new Given('I expand all fieldsets'); $steps[] = new Given('I set the field "' . $formatfield . '" to "' . $formatvalue . '"'); $steps[] = new Given('I set the following fields to these values:', $table); } else { $steps[] = new Given('I set the following fields to these values:', $table); } $steps[] = new Given('I press "' . get_string('savechanges') . '"'); return $steps; }