CakePHP unit testing repository function that returns method

trying to unit test a repository method that returns an object, and the test fixtures are arrays, the return value is an object.
Would the data in the test fixtures need to be changed to become objects, or can i convert the retrieved data into an object at the start of the test. Test method is below

/**
     * Test Getting Details by Importer and Year method
     *
     * @return void
     */
    public function testGetDetailsByImporterAndYear(): void
    {
        $expectedImporterDetail = $this->getFixtureData('ImporterDetails', 0);
        $importer = $this->getFixtureData('Importers', 0);

        $year = 2021;
        $result = $this->ImporterDetails->getDetailsByImporterAndYear($importer['id'], $year);
        $this->assertEquals($expectedImporterDetail, $result, 'Should only be one result');

        $expectedResult = null;
        $importerId = PHP_INT_MAX;
        $yearMax = 2038;
        $result = $this->ImporterDetails->getDetailsByImporterAndYear($importerId, $yearMax);
        $this->assertSame($expectedResult, $result, 'Should be no result returned');
    }

and an example of the test data

        $data = [
            [
                'id' => '1',
                'client_id' => '1',
                'importer_id' => '1',
                'name' => 'Ethil Jones',
                'email' => '[email protected]',
                'address' => '136 Manor Way
Great Marton
FY3 7UT',
                'year' => '2021',
                'created' => '2021-12-07 22:32:59',
                'modified' => '2021-12-07 22:32:59',
            ],

Ive looked into mock objects, though not sure that would be the right use case here. Any pointers would be great. Bottom half of the test works, as the method may return null. Just the part where the object is returned struggling to assert same

How to fetch list of all the product item from tally server using php

I have to fetch product item list from the paritcular table list
from the tally server using php code.So in my tally server i have
the few tables like stock item,stock groups,stock category in my
inventory master.In my stock item table i have approx more than
3000 items in the list with product details,for this i have also
got the php code using curl method but that list is not coming
from stock item table it is coming from somewhere else.Please help
me how i can achieve this.

<?php

$res_str =<<<XML
 <ENVELOPE>
 <HEADER>
 <TALLYREQUEST>Export Data</TALLYREQUEST>
 </HEADER>
 <BODY>
 <EXPORTDATA>
 <REQUESTDESC>
 <REPORTNAME>stock category summary</REPORTNAME>
 </REQUESTDESC>
 </EXPORTDATA>
 </BODY>
 </ENVELOPE>
XML;


$url = "http://localhost:9000/";

        //setting the curl parameters.
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
// Following line is compulsary to add as it is:
        curl_setopt($ch, CURLOPT_POSTFIELDS,
                    "xmlRequest=" . $res_str);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
        $data = curl_exec($ch);
        //echo '<pre>';
        //var_dump($data);die;

        curl_close($ch);
        // get the xml object 
    $object = simplexml_load_string( $data );
    
    echo "<pre>";
    print_r($object);die;
    
?>

Display posts from multiple categories in WordPress

We have a WordPress site with two categories like

Category A – 500 posts

Category B – 320 Posts

We created a new category C and displayed the articles from category A. We tagged 200 articles in the A category and we want to show them like this:

Category A – 300 Post (500-200)

Category B – 320 Post

Category C – 200 Post (200 tagged artile)

Category C home page is working fine (Archive page by custom WP query) but pagination pages going to 404

Category C does not assign any articles I want to display articles from category B as only tagged articles.

Insert multiple rows with three single selects and one multiple select on each row

Every time the user clicks + a new row is added and when the user clicks x a new row is deleted user interface. There are four dropdowns. Month(single select) , Year(single select) , Main reason (single select), Secondary reason(multiple select). Main and secondary have the same id because they need to be inserted in the same column in database table structure

With the current code,only the first row inserted in database is correct (see second image). Everything else is messed up

PHP

if (isset($_POST[‘acute_id’]) && !empty($_POST[‘month_acute’]) && !empty($_POST[‘year_acute’]) ){

                array_push ($variations_cols, $db -> quoteName ('update_id') . ',' . $db -> quoteName ('acute_id')
                    . ',' . $db -> quoteName ('month_acute'). ',' . $db -> quoteName ('year_acute'));
                
                
                $unique_genes = array_unique ($_POST['acute_id'], SORT_NUMERIC); //remove duplicate genes
                $unique_keys  = array_keys ($unique_genes); // keys of unique values
                
            
                for ($i = 0; $i < count ($unique_genes); $i ++){
                    
                        array_push ($variations_vals, $db -> quote ($updated_id) . ',' . $db -> quote ($_POST['acute_id'][$i])
                            . ',' . $db -> quote ($_POST['month_acute'][$i]). ',' . $db -> quote ($_POST['year_acute'][$i]) );


                }

                insertIntoTable ($db, "patient_has_ac2", $variations_cols, $variations_vals);
            }

HTML

                                                <table id='acuteTable' class='table table-borderless acute_events_table enrol_dataset' style='display: none;'>
                                                <thead>
                                             
                                                </thead>
                                                <tbody>
                                               

                                                <tr class='acute_class text-center' style='display: none;'>
                                                    <th><label class='fw-bold control-label'><i class='error_asterisk'>*</i> Hospitalization/Emergency Admission Date</label></th>
                                                    <th><label class='fw-bold control-label'><i class='error_asterisk'>*</i> Main reason for each Hospitalization/Emergency admission</label></th>
                                                    <th><label class='fw-bold control-label'><i class='error_asterisk'>*</i> Secondary reason(s) for each Hospitalization/Emergency admission</label></th>
                                                    <th><button id='add_acute' type='button' class='btn btn-success'><i class='fa fa-plus'></i></button></th>
                                                </tr>
                                                
                                                <tr class='acute_class text-center' style='display: none;'>

                                                
                                                    <td class='form-group'>
                                                        <div class="row">
                                                            <select id='month_acute' name='month_acute[]' class='acute_date check_current_date month_check select2_cls form-control' style='width: fit-content;'>
                                                                    <option value=''>Month</option>
                                                                    <?php echo $month_list;  ?>
                                                            </select> 
                                                        
                                                            <select id='year_acute' name='year_acute[]' class='acute_date check_current_date year_check select2_cls form-control' style='width: fit-content;'>
                                                                    <option value=''>Year</option>
                                                                    <?php echo $year_list;  ?>
                                                            </select>
                                                        </div>  
                                                    </td>
                                                 
                                                   


                                                    <td class='form-group'>
                                                        <select id="select_other_primary1" name='acute_id[]' class='select2_cls acute_diagnosis genes form-control' style='width: 100%;'>
                                                            <?php echo $acute_complications; ?>
                                                        </select>
                                                        <div class='invalid-feedback feedback-icon'><i class='fa fa-times'></i> This is a <strong>mandatory</strong> field.</div>

                                                        <div class="other_primary1" style="display: none;"> 
                                                        <label class="control-label" for="transfusion_sel_past">
                                                            <i class="error_asterisk">*</i> Other main reason :
                                                        </label>
                                                        <textarea id="other_blood1" name="other_blood" class="form-control"></textarea>

                                                        </div>


                                                    </td>

                                                    <td class='form-group'>
                                                        <select name='acute_id[]' id="select_other_secondary2" class='select2_cls acute_diagnosis genes form-control' style='width: 100%;' multiple>
                                                            <?php echo $acute_complications; ?>
                                                        </select>
                                                        <div class='invalid-feedback feedback-icon'><i class='fa fa-times'></i> This is a <strong>mandatory</strong> field.</div>

                                                        <div class="other_secondary2" style="display: none;"> 
                                                        <label class="control-label" for="other_secondary2">
                                                            <i class="error_asterisk">*</i> Other secondary reason :
                                                        </label>
                                                        <textarea id="other_secondary_textarea2" name="other_secondary_textarea2" class="form-control"></textarea>

                                                        </div>


                                                    </td>




                                                    <!-- <td class='form-group'>
                                                        <select name='acute_secondary[]' class='select2_cls genotype_diagnosis allele_variations vars_select2 form-control' style='width: 100%;' data-placeholder='Select gene first'></select>
                                                        <div class="new_variation2" style="display: none;">
                                                            <input type="text" name="new_variation[]" class="new_variation_input2">
                                                        </div>
                                                        <div class='invalid-feedback feedback-icon'><i class='fa fa-times'></i> This is a <strong>mandatory</strong> field.</div>
                                                    </td> -->


                                                    
                                                </tr>

                                                </tbody>
                                            </table>

jQuery for adding rows

            $('#add_acute').off('click').on('click', function () {

            var acute_options = <?php echo json_encode ($acute_complications, JSON_UNESCAPED_SLASHES); ?>;

            var month_options = <?php echo json_encode ($month_list, JSON_UNESCAPED_SLASHES); ?>;

            var year_options = <?php echo json_encode ($year_list, JSON_UNESCAPED_SLASHES); ?>;



            $(".acute_events_table > tbody:last-child").append(
                '<tr class="acute_class text-center">' +



                '<td class="form-group">' +
                '<div class="row"> <select id="month_acute" name="month_acute[]" class="acute_date check_current_date month_check select2_cls form-control" data-placeholder="Month" style="width: fit-content;" ><option value="">Month</option>' +
                month_options + '</select><select id="year_acute" name="year_acute[]" class="acute_date check_current_date year_check select2_cls form-control" data-placeholder="Year"  style="width: fit-content;"  ><option value="">Year</option>' +
                year_options + '</select> </div>' +
                '<div class="invalid-feedback feedback-icon"><i class="fa fa-times"></i> This is a <strong>mandatory</strong> field.</div>' +
                '</td>'+



                '<td class="form-group">' +
                '<select name="acute_id[]" id="select_other_primary" class="select2_cls vars_select1 allele_variations acute_diagnosis form-control" style="width: 100%;" data-placeholder="Main reason" required>'+acute_options +'</select>' +
                '<div class="other_primary" style="display: none;"  >' +
                '<label class="control-label" for="other_primary_textarea"><i class="error_asterisk">*</i> Other main reason :</label>'+

                '<textarea id="other_primary_textarea" name="other_primary_textarea" class="form-control"></textarea>' +

                '</div>' +
                '<div class="invalid-feedback feedback-icon"><i class="fa fa-times"></i> This is a <strong>mandatory</strong> field.</div>' +
                '</td>'+



                '<td class="form-group">' +
                '<select name="acute_id[]" id="select_other_secondary" class="select2_cls vars_select2 allele_variations acute_diagnosis form-control" style="width: 100%;" data-placeholder="Secondary reason" required multiple>'+acute_options +'</select>' +
                '<div class="other_secondary" style="display: none;" >'+
                '<label class="control-label" for="other_secondary_textarea"><i class="error_asterisk">*</i> Other secondary reason :</label>'+
                '<textarea id="other_secondary_textarea" name="other_secondary_textarea" class="form-control"></textarea>'+
                
                '</div>'+
                '<div class="invalid-feedback feedback-icon"><i class="fa fa-times"></i> This is a <strong>mandatory</strong> field.</div>' +
                '</td>'+



                '<td><button type="button" class="btn btn-danger delete_row delete_row_causatives"><i class="fa fa-remove"></i></button></td>' +

                '</tr>'
            );

            $(".select2_cls").select2({width: 'resolve'}); //initialize select2 dropdowns

            });

            

PHP get WebKitFormBoundary name and it’s value

------WebKitFormBoundary2rntuFxldIBHkJLv
Content-Disposition: form-data; name="username"

james
------WebKitFormBoundary2rntuFxldIBHkJLv
Content-Disposition: form-data; name="email"

[email protected]
------WebKitFormBoundary2rntuFxldIBHkJLv
Content-Disposition: form-data; name="language"

en
------WebKitFormBoundary2rntuFxldIBHkJLv
Content-Disposition: form-data; name="message"

hello world

Is it possible to get the name=”username” and its value “james” and so on like this in below.

username=james&[email protected]&language=en&message=hello world

I know I’m new to programming but I’m trying my best to produce this result but no luck so I’m trying ask here.

The requested resource was not found on this server

create.blade.php

<div class="row mb-3">
    <div class="col-md-12 mb-3">
        <label for="body">Body</label>
        <textarea name="body" id="body" class="form-control"></textarea>
    </div>
</div>

<script src="{{ asset('themes/ckeditor/ckeditor.js') }}"></script>
<script>
    CKEDITOR.replace('body' ,{
        filebrowserUploadUrl : '/admin/upload/image',
        filebrowserImageUploadUrl :  '/admin/upload/image'
    });
</script>

web.php

Route::post('/admin/upload/image', 'AdminController@upload');

AdminController.php

public function upload()
{
    $year = Carbon::now()->year;
    $imagePath = "/admin/upload/image/{$year}/";
    $file = request()->file('upload');
    $filename = $file->getClientOriginalName();
    if (file_exists(public_path($imagePath).$filename)) {
        $filename = Carbon::now()->timestamp.$filename;
    }
    $file->move(public_path($imagePath), $filename);
    $url = $imagePath.$filename;
    return "<script>window.parent.CKEDITOR.tools.callFunction(1, '{$url}', '')</script>";
}

VerifyCsrfToken.php

protected $except = [
    'admin/upload/image'
];

When I upload an image in CKEditor I get this error.

The requested resource /admin/upload/image?CKEditor=body&CKEditorFuncNum=1&langCode=fa was not found on this server.

In PHP file, Summernote is almost funny functional except returning the data from the database displays the HTML tags instead of implementing them

I’m new to stack overflow and I’m still a beginner at PHP/Web Development so please bear with me. I have a simple blogging application that requires 5 forms but only one needs WYSIWYG (description). My PHP should be fine for inserting the actual data:

            // Prepare the query
        $insert_query = "INSERT INTO characters (name,rarity,constellation,affiliation,description, element_id, image_id, url) VALUES (:name,:rarity,:constellation,:affiliation,:description, :element,:id, :url)";

        // Prepare the databaase object
        $statement = $db->prepare($insert_query);
    




        //print_r($sanitized_post); 

        // Bind values to the placeholders
        $statement->bindValue(':name', $sanitized_post['name']);
        $statement->bindValue(':rarity', $sanitized_post['rarity']);
        $statement->bindValue(':constellation', $sanitized_post['constellation']);
        $statement->bindValue(':affiliation', $sanitized_post['affiliation']);
        $statement->bindValue(':description', $sanitized_post['description']);
        $statement->bindValue(':element', $sanitized_post['element']);
        $statement->bindValue(':id', $imageID, PDO::PARAM_INT);
        $statement->bindValue(':url', slug($url));

And the HTML forms for my fields look like this:

 <!-- Main post form -->
<div class="form-group">
<form method='post' enctype='multipart/form-data'>
    <p>
        <label for="name">Name</label>
        <input name="name" id="name" />
    </p>
    <p>
        <label for="rarity">Rarity</label>
        <input name="rarity" id="rarity" />
    </p>
    <p>
        <label for="constellation">Constellation</label>
        <input name="constellation" id="constellation" />
    </p>
    <p>
        <label for="affiliation">Affiliation</label>
        <input name="affiliation" id="affiliation" />
    </p>
    <p>
        <label>Description</label>
        <textarea name="description" id="description" class="form-control"></textarea>
        <script>
    
    $('#description').summernote({
        placeholder: 'Text',
        tabsize: 2,
        height: 100,
        toolbar: [
      ['style', ['style']],
      ['font', ['bold', 'underline', 'clear']],
      ['color', ['color']],
      ['para', ['ul', 'ol', 'paragraph']],
      ['table', ['table']],
      ['insert', ['link', 'picture', 'video']],
      ['view', ['fullscreen', 'codeview', 'help']]
    ]
    });
        </script>
    </p>

On my view.php, my data is returned like so:

   <ul>
   <li>Rarity: <?=$row['rarity']?></li>
   <li>Constellation: <?=$row['constellation']?></li>
   <li>Affiliation: <?=$row['affiliation']?></li>
   <li>Vision: <?=$row['element']?></li>
<h2><?= $row['description'] ?></h2>

But for some reason, on my view.php if I were to type “aaaaa”, it would print out as:

<p>aa<b>a</b>aa</p>

Which is odd, my peers confirm their code is functionally very similar to mine and they didn’t have this issue.

My tag in the HTML includes this:

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<!-- include summernote css/js -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/summernote.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/summernote.min.js"></script>

Please, any help is appreciated. My summernote is about 90% implemented. This appears to be the final roadblock.

Laravel updating multiple hasMany / belongsToMany relationships

I have inherited a project that has a a few CRUD forms … On the create form we need to create entries for a hasMany and belongsToMany relationship. So basically what i have got is the following

$movie = Movie::create($request->validated());

// Then to save the belongsToMany
foreach ($request['actors'] as $actor) {
  // do some data manipulation

  $actor = Actor::where('code', $actor->code)->first();

  $movie->actors()->attach($actor);
}

// Save the hasMany 
foreach ($request['comments'] as $comment) {
  // do some data manipulation

  $movie->comments()->create([
    'title' => $comment['title'],
    'body' => $comment['body'],
  ]);
}

I’m not sure if this is the best way of doing this, but it seems to work.

The problem I am having is that in the edit form, these actors / comments can be edited, added to or deleted and i am unsure of how to go about updating them. Is it possible to update them, or would it be better to delete the existing relationship data and re-add them?

I have never updated relationships, only added them so i am unsure how to even start.

Any help would be greatly appreciated.

Which template file does avada use for the blog post loop

Can someone please point me in the right direction regarding the location of the template file that contains the blogs posts loop Iā€™m using the blog element.

I’ve tried multiple files but it does not work, Would ideally like to add a link after the meta information

Any help would be greatly appreciated.

Kind redards

Property does not exists in template although its assigned

I’m working on a Symfony application to add meter values to a meter. A meter can have a set of measurements, and for each measurement I want to display a value form to enter values.

Fot this I have a function in a controller that creates an ArrayCollection of empty (new) elements depending on the corresponding measurements like so:

/**
 * @Route("/{id}/add", name="metervalue_add", methods={"GET","POST"})
 */
public function add(Request $request, Meter $meter): Response
{
    $metervalues = new ArrayCollection();
    $measurements = $meter->getMeasurements();
    // create an empty metervalue for each measurement of the meter
    foreach ($measurements as $measurement) {
        $mv = new MeterValue();
        $mv->setMeter($meter);
        $mv->setMeasurement($measurement);
        $metervalues->add($mv);
    }
    $form = $this->createForm(MeterValueAddType::class, ['metervalues' => $metervalues]);

    $form->handleRequest($request);

    // ... form submitting stuff
    // ...

    return $this->renderForm('metervalue/add.html.twig', [
        'form' => $form
    ]);
}

The corresponding MeterValueAddType looks like

class MeterValueAddType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('metervalues', CollectionType::class, [
                'entry_type' => MeterValueType::class
            ]);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => null,
        ]);
    }
}

When I render the form all works fine, the empty objects are rendered as expected, I can submit the form and all data is inserted correctly in the DB, including measurement and meter ids.
However, in my template I cannot access reference properties of the metervalue object, like metervalues.measurement or metervalue.meter

{% for metervalue in form.metervalues %}
   {{ form_widget(metervalue.value) }}
   {{ form_widget(metervalue.date) }}

   Name of measurement: {{ metervalue.measurement.name }} <-- this throws the following error
{% endfor %}

Error: Neither the property “measurement” nor one of the methods
“measurement()”,
“getmeasurement()”/”ismeasurement()”/”hasmeasurement()” or “__call()”
exist and have public access in class
“SymfonyComponentFormFormView”.

I don’t understand why I can’t access the properties in here just to display them, as they are assigned above in the controller and stored correctly in the DB on save…

The property “measurement” and a correspoding “getmeasurement()” exist and e.g. if I display all saved objects in a list I can access these.

Any hints appreciated!

How to define a RegularExpresion Validation for an Controller Action Param, in TYPO3 v10/v11?

I’m updating an extension for usage in TYPO3 v10 or higher and have an issue with a regular Expression validator, i don’t know how to get in runnable in v10 or higher now. Tried the following:

/**
 * action list
 *
 * @param string $filterChar
 * @ExtbaseValidate("RegularExpression",options={ "regularExpression": "/^[0-9A-Za-z]{0,1}$/i" })
 * @return void
 */
public function listAction(string $filterChar = '') {

But i got the following exception:

Invalid validate annotation in ABCMyExtControllerMyController->listAction(): The following validators have been defined for missing param "$": RegularExpression

What i’m doing wrong and how can i fix it, or what is the correct definition now for a RegularExpression validator for an action parameter?

how to pass data in view with php?

Blockquote
Hello, I will need an experienced look:
I am in training and I rely on a tutorial to carry out a blog project developed in php-> POO-> MVC.

https://www.youtube.com/watch?v=iB4NEbId6kY&list=PLeeuvNW2FHVgfbhZM3S8kqZOmnY7TEorW&index=3

when i switch to my content view, the tutorial uses laravel syntax, and phpstorm gives me an error when i echo my $ content variable in /views/layout.php at the root of my project.
Here are the following files:
enter image description here

PHP Function for get result between two number by entered parameter

I’m thinking about how to write a function for getting a result dependent on a specific range.

See my code:

function($number){
    if($number < 10){
        return 0;
    }else if($number>=10 && $number < 200){
        return customrange($number,10,200,0,200);
    }else if($number>=200 && $number < 1000){
        return customrange($number,200,1000,200,500);
    }else if($number>=1000 && $number < 3000){
        return customrange($number,1000,3000,500,800);
    }
}
function customrange($number,$min,$max,$minResult,$maxResult){
    return '????';
}

I need to fill customrange function for my code to be work but I haven’t any idea.

result of customrange function will be between $minResult and $maxResult parameter depending on how much $number is near to $min and $max

Examples:

customrange(10,10,200,0,200); // Result: 0;
customrange(105,10,200,0,200); // Result: 100;
customrange(200,10,200,0,200); // Result: 200;
customrange(200,200,1000,200,500); // Result: 200;
customrange(600,200,1000,200,500); // Result: 350;
customrange(1000,200,1000,200,500); // Result: 500;
customrange(1000,1000,3000,500,800); // Result: 500;
customrange(2000,1000,3000,500,800); // Result: 650;
customrange(3000,1000,3000,500,800); // Result: 800;

Thanks.

Looking for some WordPress shortcodes to include in php file

I am currently using a neat little plugin from WordPress’ repository called Citationic which displays a little box that generates the correct citation for the individual website to be included in a bibliography. I had a look at the php file and it is quite easy to modify the various templates. However, I am confused how to pull the published date from WordPress.

The APA style is as follows: Organisation. (Publish date). Title. Retrieved Current date, from siteurl.

The php is
$cion_styles = [
“apa” => ‘{sitename}. ({date}). {title}. Retrieved {date}, from {permalink}.’,

Now, my question is to what I have to change the first {date} to display the published date instead of the current date?
I hope that I made myself somewhat clear šŸ™‚

Thanks!