How to extend this function. The task is getLinkedPages must be created and return content depending on the parameter - pdf

How to extend this function. The task is getLinkedPages must be created and return content depending on the parameter.
/**
* Get the contents as a sorted collection tree.
*/
public function getTree(bool $showDrafts = false, bool $renderPages = false, bool $renderLinkedPages = false): Collection
{
$pages = $this->getPages($showDrafts, $renderPages);
$chapters = Chapter::visible()->where('book_id', '=', $this->book->id)->get();
$all = collect()->concat($pages)->concat($chapters);
$chapterMap = $chapters->keyBy('id');
$lonePages = collect();
$pages->groupBy('chapter_id')->each(function ($pages, $chapter_id) use ($chapterMap, &$lonePages) {
$chapter = $chapterMap->get($chapter_id);
if ($chapter) {
$chapter->setAttribute('visible_pages', collect($pages)->sortBy($this->bookChildSortFunc()));[enter image description here][1]
} else {
$lonePages = $lonePages->concat($pages);
}
});
$chapters->whereNull('visible_pages')->each(function (Chapter $chapter) {
$chapter->setAttribute('visible_pages', collect([]));
});
$all->each(function (Entity $entity) use ($renderPages) {
$entity->setRelation('book', $this->book);
if ($renderPages && $entity instanceof Page) {
$entity->html = (new PageContent($entity))->render();
}
});
return collect($chapters)->concat($lonePages)->sortBy($this->bookChildSortFunc());
}

Related

Is there a way to optimize the mapping of users?

I've created a method to call this getUserIdsByAllBranches() and the return would be an array. If array is not empty, I'll be doing another process. But I have a problem here in mapping or getting all the users with all branches.
Here's the code:
/**
* Get all User Ids of Branch Permission User
* By All Branches
* #param Array
* #return Array
*/
public function getUserIdsByAllBranches($override = [])
{
if (count($override) !== 0) {
foreach($override as $property => $value) {
${$property} = $value;
}
} else {
$branchLength = App::make(BranchRepository::class)->get()->count();
}
$userIdsWithAllBranches = [];
$userIds = $this->getUserIds();
foreach($userIds as $userId) {
$identical = true;
$userBranchIds = array_values($this->get()
->where('user_id', $userId)
->pluck(['branch_id'])
->unique()
->toArray());
if(count($userBranchIds) === $branchLength) {
$initialPermissions = [];
foreach($userBranchIds as $index => $userBranchId) {
if(!$identical) {
continue;
}
$branchUserPermissions = $this->get()
->where('user_id', $userId)
->where('branch_id', $userBranchId)
->sortBy('permission_id')
->pluck(['permission_id']);
if($index === 0) {
$initialPermissions = $branchUserPermissions;
} else {
if($initialPermissions != $branchUserPermissions) {
$identical = false;
}
}
}
} else {
$identical = false;
}
if($identical) {
array_push($userIdsWithAllBranches, $userId);
}
}
return $userIdsWithAllBranches;
}
/**
* Get all User Ids of Branch Permission User
*
* #return Array
*/
public function getUserIds()
{
return array_values($this->get()
->sortBy('user_id')
->pluck(['user_id'])
->unique()
->toArray());
}
This method getUserIds(), will be returning all the user ids for branch permission user table.
Branch Permission User Table:
branch_id
permission_id
user_id

Moq + xunit + asp.net core: service return null value

I use xUnit as test runner in my asp.net core application.
Here is my test theory:
[Theory(DisplayName = "Search advisors by advisorId"),
ClassData(typeof(SearchAdvisorsByIdTestData))]
public async void SearchAdvisors_ByAdvisorId(int brokerDealerId, FilterParams filter)
{
// Arrange
var _repositoryMock = new Mock<IRepository>();
// Do this section means we bypass the repository layer
_repositoryMock
.Setup(x => x.SearchAdvisors(filter.CID.Value, new AdvisorSearchOptions
{
SearchKey = filter.SeachKey,
AdvisorId = filter.AdvisorId,
BranchId = filter.BranchId,
City = filter.City,
Skip = filter.Skip,
Limit = filter.Limit,
RadiusInMiles = filter.Limit,
Longitude = filter.Longitude,
Latitude = filter.Latitude
}))
.Returns(Task.FromResult<SearchResults<Advisor>>(
new SearchResults<Advisor>()
{
Count = 1,
Limit = 0,
Skip = 0,
ResultItems = new List<SearchResultItem<Advisor>>() {
//some initialize here
}
})
);
_advisorService = new AdvisorService(_repositoryMock.Object, _brokerDealerRepositoryMock, _brokerDealerServiceMock);
// Action
var model = await _advisorService.Search(brokerDealerId, filter);
Assert.True(model.AdvisorResults.Count == 1);
Assert.True(model.AdvisorResults[0].LocationResults.Count > 0);
}
The service like this
public async Task<ViewModelBase> Search(int brokerDealerId, FilterParams filter)
{
var opts = new AdvisorSearchOptions
{
SearchKey = filter.SeachKey,
AdvisorId = filter.AdvisorId,
BranchId = filter.BranchId,
City = filter.City,
Skip = filter.Skip,
Limit = filter.Limit,
RadiusInMiles = filter.Limit,
Longitude = filter.Longitude,
Latitude = filter.Latitude
};
var searchResults = await _repository.SearchAdvisors(filter.CID.Value, opts); // line 64 here
if (searchResults.Count == 0 && Utils.IsZipCode(filter.SeachKey))
{
}
//Some other code here
return model;
}
The issue was after run line 64 in the service. I always get null value of searchResults although I already mocked _repository in the test.
What was my wrong there?
Thank in advance.
Argument matcher for SearchAdvisors() mock does not work because you pass different instances of AdvisorSearchOptions. First instance is created in _repositoryMock.Setup() statement and the second one is created in Search() method itself.
There are several ways to fix this problem:
1.If you don't care about verifying whether instance of AdvisorSearchOptions passed to repository is filled correctly, just use It.IsAny<AdvisorSearchOptions>() matcher in mock setup:
_repositoryMock.Setup(x => x.SearchAdvisors(filter.CID.Value, It.IsAny<AdvisorSearchOptions>()))
.Returns(/*...*/);
2.In previous case the test will not verify that AdvisorSearchOptions is filled correctly. To do this, you could override Object.Equals() method in AdvisorSearchOptions class so that mock call will match for different instances:
public class AdvisorSearchOptions
{
// ...
public override bool Equals(object obj)
{
var cmp = obj as AdvisorSearchOptions;
if (cmp == null)
{
return false;
}
return SearchKey == cmp.SearchKey && AdvisorId == cmp.AdvisorId &&
/* ... compare all other fields here */
}
}
3.Another way to verify object passed to mock is to save the instance via Mock callback and then compare required fields:
AdvisorSearchOptions passedSearchOptions = null;
_repositoryMock
.Setup(x => x.SearchAdvisors(filter.CID.Value, It.IsAny<AdvisorSearchOptions>()))
.Returns(Task.FromResult<SearchResults<Advisor>>(
new SearchResults<Advisor>()
{
Count = 1,
Limit = 0,
Skip = 0,
ResultItems = new List<SearchResultItem<Advisor>>() {
//some initialize here
}
})
)
.Callback<int, AdvisorSearchOptions>((id, opt) => passedSearchOptions = opt);
// Action
// ...
Assert.IsNotNull(passedSearchOptions);
Assert.AreEqual(filter.SearchKey, passedSearchOptions.SearchKey);
Assert.AreEqual(filter.AdvisorId, passedSearchOptions.AdvisorId);
// Check all other fields here
// ...

Prestashop capitalize customer address

I need to capitalize all user data in Prestashop 1.6 - I've managed to get it done for name, etc. but I don't know where I can do this for the address.
My guess is AddressController's processSubmitAddress() method, but I cannot find where does it take the input, so I can strotupper() that. Thanks for any guidance.
A little late, but here it is. Just change the ucfirst for whatever you need, in this case strotupper(). This is for the customer's address. In same file there should be other files for different customer data. This works also for PS 1.7.2 (tested)
Go to yourprojectfolder/classes/Address.php
Search for public function add($autodate = true, $null_values = false) on line 169.
Replace :
public function add($autodate = true, $null_values = false)
{
if (!parent::add($autodate, $null_values)) {
return false;
}
if (Validate::isUnsignedId($this->id_customer)) {
Customer::resetAddressCache($this->id_customer, $this->id);
}
return true;
}
With:
public function add($autodate = true, $null_values = false)
{
if (!parent::add($autodate, $null_values)) {
return false;
}
// Capitalize the first name
$this->firstname = ucfirst($this->firstname);
// Capitalize the first name
$this->lastname = ucfirst($this->lastname);
// Capitalize the address fields
$this->address1 = ucfirst($this->address1);
$this->address2 = ucfirst($this->address2);
if (Validate::isUnsignedId($this->id_customer)) {
Customer::resetAddressCache($this->id_customer, $this->id);
}
return true;
}
Search for public function update($null_values = false) on line 181.
Replace :
public function update($null_values = false)
{
// Empty related caches
if (isset(self::$_idCountries[$this->id])) {
unset(self::$_idCountries[$this->id]);
}
if (isset(self::$_idZones[$this->id])) {
unset(self::$_idZones[$this->id]);
}
if (Validate::isUnsignedId($this->id_customer)) {
Customer::resetAddressCache($this->id_customer, $this->id);
}
return parent::update($null_values);
}
With:
public function update($null_values = false)
{
// Empty related caches
if (isset(self::$_idCountries[$this->id])) {
unset(self::$_idCountries[$this->id]);
}
if (isset(self::$_idZones[$this->id])) {
unset(self::$_idZones[$this->id]);
}
// Capitalize the first name
$this->firstname = ucfirst($this->firstname);
// Capitalize the first name
$this->lastname = ucfirst($this->lastname);
// Capitalize the address fields
$this->address1 = ucfirst($this->address1);
$this->address2 = ucfirst($this->address2);
if (Validate::isUnsignedId($this->id_customer)) {
Customer::resetAddressCache($this->id_customer, $this->id);
}
return parent::update($null_values);
}
Instead of changing the PrestaShop core. You can also use the override option.
Create the file yourprojectfolder/override/classes/Address.php and insert this code and save the file:
<?php
/**
* Fix for capitalize and submit the first letters of the name and address input fields
*
* 2007-2015 PrestaShop
*
* NOTICE OF LICENSE
*
* #author Peter Visser <info#mark-app.com>
*/
class Address extends AddressCore
{
public function update($null_values = false)
{
// Empty related caches
if (isset(self::$_idCountries[$this->id])) {
unset(self::$_idCountries[$this->id]);
}
if (isset(self::$_idZones[$this->id])) {
unset(self::$_idZones[$this->id]);
}
// Capitalize the first name
$this->firstname = ucfirst($this->firstname);
// Capitalize the first name
$this->lastname = ucfirst($this->lastname);
// Capitalize the address fields
$this->address1 = ucfirst($this->address1);
$this->address2 = ucfirst($this->address2);
if (Validate::isUnsignedId($this->id_customer)) {
Customer::resetAddressCache($this->id_customer, $this->id);
}
return parent::update($null_values);
}
public function add($autodate = true, $null_values = false)
{
if (!parent::add($autodate, $null_values)) {
return false;
}
// Capitalize the first name
$this->firstname = ucfirst($this->firstname);
// Capitalize the first name
$this->lastname = ucfirst($this->lastname);
// Capitalize the address fields
$this->address1 = ucfirst($this->address1);
$this->address2 = ucfirst($this->address2);
if (Validate::isUnsignedId($this->id_customer)) {
Customer::resetAddressCache($this->id_customer, $this->id);
}
return true;
}
}
After that reset your cache for overrides bij deleting yourprojectfolder/cache/class_index.php
Source: https://www.prestashop.com/forums/topic/333935-capitalize-first-letters-of-address-input-fields-and-submit-to-database
Lacking the help, I decided to do a little workaround - I've actually set a trigger on the database, which on insert or update transforms the specified data with SQL's UPPER() function.

SQL "VIEW" in codeigniter

I want to create an SQL view within the codeigniter model. What is the best way of doing this?
I use mutliple models depending on wich table i need to work
application/core/MY_model.php
<?php
/**
* CRUD Model
* A base model providing CRUD, pagination and validation.
*/
class MY_Model extends CI_Model
{
public $table;
public $primary_key;
public $default_limit = 15;
public $page_links;
public $query;
public $form_values = array();
protected $default_validation_rules = 'validation_rules';
protected $validation_rules;
public $validation_errors;
public $total_rows;
public $date_created_field;
public $date_modified_field;
public $native_methods = array(
'select', 'select_max', 'select_min', 'select_avg', 'select_sum', 'join',
'where', 'or_where', 'where_in', 'or_where_in', 'where_not_in', 'or_where_not_in',
'like', 'or_like', 'not_like', 'or_not_like', 'group_by', 'distinct', 'having',
'or_having', 'order_by', 'limit'
);
function __construct()
{
parent::__construct();
}
public function __call($name, $arguments)
{
call_user_func_array(array($this->db, $name), $arguments);
return $this;
}
/**
* Sets CI query object and automatically creates active record query
* based on methods in child model.
* $this->model_name->get()
*/
public function get($with = array(), $include_defaults = true)
{
if ($include_defaults) {
$this->set_defaults();
}
foreach ($with as $method) {
$this->$method();
}
$this->query = $this->db->get($this->table);
return $this;
}
/**
* Query builder which listens to methods in child model.
* #param type $exclude
*/
private function set_defaults($exclude = array())
{
$native_methods = $this->native_methods;
foreach ($exclude as $unset_method) {
unset($native_methods[array_search($unset_method, $native_methods)]);
}
foreach ($native_methods as $native_method) {
$native_method = 'default_' . $native_method;
if (method_exists($this, $native_method)) {
$this->$native_method();
}
}
}
/**
* Call when paginating results.
* $this->model_name->paginate()
*/
public function paginate($with = array())
{
$uri_segment = '';
$offset = 0;
$per_page = $this->default_limit;
$this->load->helper('url');
$this->load->library('pagination');
$this->set_defaults();
foreach ($with as $method) {
$this->$method();
}
$this->total_rows = $this->db->count_all_results($this->table);
$uri_segments = $this->uri->segment_array();
foreach ($uri_segments as $key => $segment) {
if ($segment == 'page') {
$uri_segment = $key + 1;
if (isset($uri_segments[$uri_segment])) {
$offset = $uri_segments[$uri_segment];
}
unset($uri_segments[$key], $uri_segments[$key + 1]);
$base_url = site_url(implode('/', $uri_segments) . '/page/');
}
}
if (!$uri_segment) {
$base_url = site_url($this->uri->uri_string() . '/page/');
}
$config = array(
'base_url' => $base_url,
'uri_segment' => $uri_segment,
'total_rows' => $this->total_rows,
'per_page' => $per_page
);
if ($this->config->item('pagination_style')) {
$config = array_merge($config, $this->config->item('pagination_style'));
}
$this->pagination->initialize($config);
$this->page_links = $this->pagination->create_links();
/**
* Done with pagination, now on to the paged results
*/
$this->set_defaults();
foreach ($with as $method) {
$this->$method();
}
$this->db->limit($per_page, $offset);
$this->query = $this->db->get($this->table);
return $this;
}
function paginate_api($limit, $offset)
{
$this->set_defaults();
if (empty($limit)) {
$limit = $this->default_limit;
}
if (empty($offset)) {
$offset = 0;
}
$this->db->limit($limit, $offset);
return $this->db->get($this->table)->result();
}
/**
* Retrieves a single record based on primary key value.
*/
public function get_by_id($id, $with = array())
{
foreach ($with as $method) {
$this->$method();
}
return $this->where($this->primary_key, $id)->get()->row();
}
public function save($id = NULL, $db_array = NULL)
{
if (!$db_array) {
$db_array = $this->db_array();
}
if (!$id) {
if ($this->date_created_field) {
$db_array[$this->date_created_field] = time();
}
$this->db->insert($this->table, $db_array);
// $this->session->set_flashdata('alert_success', 'Record successfully created.');
return $this->db->insert_id();
} else {
if ($this->date_modified_field) {
$db_array[$this->date_modified_field] = time();
}
$this->db->where($this->primary_key, $id);
$this->db->update($this->table, $db_array);
// $this->session->set_flashdata('alert_success', 'Record successfully updated.');
return $id;
}
}
/**
* Returns an array based on $_POST input matching the ruleset used to
* validate the form submission.
*/
public function db_array()
{
$db_array = array();
$validation_rules = $this->{$this->validation_rules}();
foreach ($this->input->post() as $key => $value) {
if (array_key_exists($key, $validation_rules)) {
$db_array[$key] = $value;
}
}
return $db_array;
}
/**
* Deletes a record based on primary key value.
* $this->model_name->delete(5);
*/
public function delete($id, $others = array())
{
if (!empty($others)) {
foreach ($others as $k => $v) {
$this->db->where($k, $v);
}
} else {
$this->db->where($this->primary_key, $id);
}
return $this->db->delete($this->table);
// $this->session->set_flashdata('alert_success', 'Record successfully deleted.');
}
/**
* Returns the CI query result object.
* $this->model_name->get()->result();
*/
public function result()
{
return $this->query->result();
}
/**
* Returns the CI query row object.
* $this->model_name->get()->row();
*/
public function row()
{
return $this->query->row();
}
/**
* Returns CI query result array.
* $this->model_name->get()->result_array();
*/
public function result_array()
{
return $this->query->result_array();
}
/**
* Returns CI query row array.
* $this->model_name->get()->row_array();
*/
public function row_array()
{
return $this->query->row_array();
}
/**
* Returns CI query num_rows().
* $this->model_name->get()->num_rows();
*/
public function num_rows()
{
return $this->query->num_rows();
}
/**
* Used to retrieve record by ID and populate $this->form_values.
* #param int $id
*/
public function prep_form($id = NULL)
{
if (!$_POST and ($id)) {
$this->db->where($this->primary_key, $id);
$row = $this->db->get($this->table)->row();
foreach ($row as $key => $value) {
$this->form_values[$key] = $value;
}
}
}
/**
* Performs validation on submitted form. By default, looks for method in
* child model called validation_rules, but can be forced to run validation
* on any method in child model which returns array of validation rules.
* #param string $validation_rules
* #return boolean
*/
public function run_validation($validation_rules = NULL)
{
if (!$validation_rules) {
$validation_rules = $this->default_validation_rules;
}
foreach (array_keys($_POST) as $key) {
$this->form_values[$key] = $this->input->post($key);
}
if (method_exists($this, $validation_rules)) {
$this->validation_rules = $validation_rules;
$this->load->library('form_validation');
$this->form_validation->set_rules($this->$validation_rules());
$run = $this->form_validation->run();
$this->validation_errors = validation_errors();
return $run;
}
}
/**
* Returns the assigned form value to a form input element.
* #param type $key
* #return type
*/
public function form_value($key)
{
return (isset($this->form_values[$key])) ? $this->form_values[$key] : '';
}
}
then when i need a model for a specific database i use class inside models
models/content.php
class content_types extends MY_Model
{
function __construct()
{
parent::__construct();
$this->curentuserdata = $this->session->userdata('lg_result');
$this->userprofile = $this->session->userdata('user_profile');
}
public $table = 'content_types';
public $primary_key = 'id';
public $default_limit = 50;
public function default_order_by()
{
$this->db->order_by('id asc');
}
}
then where i need to call the model
$this->modelname->save($id,array());
$this->modelname->where()->get()->row();
so create one for the 'view table' and the others for insert tables

What does it return in this function return parent::beforeSave();?

I don't know what this function will return, just modified record attributes or anything other?
protected function beforeSave()
{
if ($this->getIsNewRecord())
{
$this->created = Yii::app()->localtime->UTCNow;
}
$this->lastmodified = Yii::app()->localtime->UTCNow;
if ($this->dob == '') {
$this->setAttribute('dob', null);
} else {
$this->dob=date('Y-m-d', strtotime($this->dob));
}
if($this->image!="")
{
$this->imgfile_name = $this->image->name;
$this->imgfile_type = $this->image->type;
$this->imgfile_size = $this->image->size;
}
$this->phone=substr($this->phone,0,3).substr($this->phone,4,3).substr($this->phone,8,4);
return parent::beforeSave();
}
CActiveRecord::beforeSave is supposed to return true if the model is in a valid state and can be saved, and false if it's not.